blob: f20ece560015ff65c473a28a9cec652ff04d8570 [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;
Benjamin Kramer642f1732015-07-02 21:03:14 +000076 for (Stmt *SubStmt : Node->children())
77 IsInvalid |= Visit(SubStmt);
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 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000148}
Chris Lattner58258242008-04-10 02:22:51 +0000149
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
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000165 // If we have a throw-all spec at this point, ignore the function.
166 if (ComputedEST == EST_None)
167 return;
168
Davide Italiano1a7f6482015-07-16 22:37:54 +0000169 switch(EST) {
170 // If this function can throw any exceptions, make a note of that.
171 case EST_MSAny:
172 case EST_None:
173 ClearExceptions();
174 ComputedEST = EST;
175 return;
176 // FIXME: If the call to this decl is using any of its default arguments, we
177 // need to search them for potentially-throwing calls.
178 // If this function has a basic noexcept, it doesn't affect the outcome.
179 case EST_BasicNoexcept:
180 return;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000181 // If we're still at noexcept(true) and there's a nothrow() callee,
182 // change to that specification.
Davide Italiano1a7f6482015-07-16 22:37:54 +0000183 case EST_DynamicNone:
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000184 if (ComputedEST == EST_BasicNoexcept)
185 ComputedEST = EST_DynamicNone;
186 return;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000187 // Check out noexcept specs.
Davide Italiano1a7f6482015-07-16 22:37:54 +0000188 case EST_ComputedNoexcept:
189 {
Richard Smithf623c962012-04-17 00:58:00 +0000190 FunctionProtoType::NoexceptResult NR =
191 Proto->getNoexceptSpec(Self->Context);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000192 assert(NR != FunctionProtoType::NR_NoNoexcept &&
193 "Must have noexcept result for EST_ComputedNoexcept.");
194 assert(NR != FunctionProtoType::NR_Dependent &&
195 "Should not generate implicit declarations for dependent cases, "
196 "and don't know how to handle them anyway.");
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000197 // noexcept(false) -> no spec on the new function
198 if (NR == FunctionProtoType::NR_Throw) {
199 ClearExceptions();
200 ComputedEST = EST_None;
201 }
202 // noexcept(true) won't change anything either.
203 return;
204 }
Davide Italiano1a7f6482015-07-16 22:37:54 +0000205 default:
206 break;
207 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000208 assert(EST == EST_Dynamic && "EST case not considered earlier.");
209 assert(ComputedEST != EST_None &&
210 "Shouldn't collect exceptions when throw-all is guaranteed.");
211 ComputedEST = EST_Dynamic;
212 // Record the exceptions in this function's exception specification.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000213 for (const auto &E : Proto->exceptions())
David Blaikie82e95a32014-11-19 07:49:47 +0000214 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000215 Exceptions.push_back(E);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000216}
217
Richard Smith938f40b2011-06-11 17:19:42 +0000218void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000219 if (!E || ComputedEST == EST_MSAny)
Richard Smith938f40b2011-06-11 17:19:42 +0000220 return;
221
222 // FIXME:
223 //
224 // C++0x [except.spec]p14:
NAKAMURA Takumi53648472011-06-21 03:19:28 +0000225 // [An] implicit exception-specification specifies the type-id T if and
226 // only if T is allowed by the exception-specification of a function directly
227 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith938f40b2011-06-11 17:19:42 +0000228 // function it directly invokes allows all exceptions, and f shall allow no
229 // exceptions if every function it directly invokes allows no exceptions.
230 //
231 // Note in particular that if an implicit exception-specification is generated
232 // for a function containing a throw-expression, that specification can still
233 // be noexcept(true).
234 //
235 // Note also that 'directly invoked' is not defined in the standard, and there
236 // is no indication that we should only consider potentially-evaluated calls.
237 //
238 // Ultimately we should implement the intent of the standard: the exception
239 // specification should be the set of exceptions which can be thrown by the
240 // implicit definition. For now, we assume that any non-nothrow expression can
241 // throw any exception.
242
Richard Smithf623c962012-04-17 00:58:00 +0000243 if (Self->canThrow(E))
Richard Smith938f40b2011-06-11 17:19:42 +0000244 ComputedEST = EST_None;
245}
246
Anders Carlssonc80a1272009-08-25 02:29:20 +0000247bool
John McCallb268a282010-08-23 23:25:46 +0000248Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000249 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000250 if (RequireCompleteType(Param->getLocation(), Param->getType(),
251 diag::err_typecheck_decl_incomplete_type)) {
252 Param->setInvalidDecl();
253 return true;
254 }
255
Anders Carlssonc80a1272009-08-25 02:29:20 +0000256 // C++ [dcl.fct.default]p5
257 // A default argument expression is implicitly converted (clause
258 // 4) to the parameter type. The default argument expression has
259 // the same semantic constraints as the initializer expression in
260 // a declaration of a variable of the parameter type, using the
261 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000262 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
263 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000264 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
265 EqualLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000266 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000267 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman5f101b92009-12-22 02:46:13 +0000268 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000269 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000270 Arg = Result.getAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000271
Richard Smithc406cb72013-01-17 01:17:56 +0000272 CheckCompletedExpr(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000273 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000274
Anders Carlssonc80a1272009-08-25 02:29:20 +0000275 // Okay: add the default argument to the parameter
276 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000277
Douglas Gregor758cb672010-10-12 18:23:32 +0000278 // We have already instantiated this parameter; provide each of the
279 // instantiations with the uninstantiated default argument.
280 UnparsedDefaultArgInstantiationsMap::iterator InstPos
281 = UnparsedDefaultArgInstantiations.find(Param);
282 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
283 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
284 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
285
286 // We're done tracking this parameter's instantiations.
287 UnparsedDefaultArgInstantiations.erase(InstPos);
288 }
289
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000290 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000291}
292
Chris Lattner58258242008-04-10 02:22:51 +0000293/// ActOnParamDefaultArgument - Check whether the default argument
294/// provided for a function parameter is well-formed. If so, attach it
295/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000296void
John McCall48871652010-08-21 09:40:31 +0000297Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000298 Expr *DefaultArg) {
299 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000300 return;
Mike Stump11289f42009-09-09 15:08:12 +0000301
John McCall48871652010-08-21 09:40:31 +0000302 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000303 UnparsedDefaultArgLocs.erase(Param);
304
Chris Lattner199abbc2008-04-08 05:04:30 +0000305 // Default arguments are only permitted in C++
David Blaikiebbafb8a2012-03-11 07:00:24 +0000306 if (!getLangOpts().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000307 Diag(EqualLoc, diag::err_param_default_argument)
308 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000309 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000310 return;
311 }
312
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000313 // Check for unexpanded parameter packs.
314 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
315 Param->setInvalidDecl();
316 return;
Benjamin Kramer3b8044c2015-03-27 13:58:31 +0000317 }
318
319 // C++11 [dcl.fct.default]p3
320 // A default argument expression [...] shall not be specified for a
321 // parameter pack.
322 if (Param->isParameterPack()) {
323 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
324 << DefaultArg->getSourceRange();
325 return;
326 }
327
Anders Carlssonf1c26952009-08-25 01:02:06 +0000328 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000329 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
330 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000331 Param->setInvalidDecl();
332 return;
333 }
Mike Stump11289f42009-09-09 15:08:12 +0000334
John McCallb268a282010-08-23 23:25:46 +0000335 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000336}
337
Douglas Gregor58354032008-12-24 00:01:03 +0000338/// ActOnParamUnparsedDefaultArgument - We've seen a default
339/// argument for a function parameter, but we can't parse it yet
340/// because we're inside a class definition. Note that this default
341/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000342void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000343 SourceLocation EqualLoc,
344 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000345 if (!param)
346 return;
Mike Stump11289f42009-09-09 15:08:12 +0000347
John McCall48871652010-08-21 09:40:31 +0000348 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Nick Lewycky0f292892013-09-22 10:06:57 +0000349 Param->setUnparsedDefaultArg();
Anders Carlsson84613c42009-06-12 16:51:40 +0000350 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000351}
352
Douglas Gregor4d87df52008-12-16 21:30:33 +0000353/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
354/// the default argument for the parameter param failed.
Serge Pavlovb4b35782014-07-22 01:54:49 +0000355void Sema::ActOnParamDefaultArgumentError(Decl *param,
356 SourceLocation EqualLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000357 if (!param)
358 return;
Mike Stump11289f42009-09-09 15:08:12 +0000359
John McCall48871652010-08-21 09:40:31 +0000360 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000361 Param->setInvalidDecl();
Anders Carlsson84613c42009-06-12 16:51:40 +0000362 UnparsedDefaultArgLocs.erase(Param);
Serge Pavlovb4b35782014-07-22 01:54:49 +0000363 Param->setDefaultArg(new(Context)
Fariborz Jahanian7bd22e92014-10-01 18:03:51 +0000364 OpaqueValueExpr(EqualLoc,
365 Param->getType().getNonReferenceType(),
366 VK_RValue));
Douglas Gregor4d87df52008-12-16 21:30:33 +0000367}
368
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000369/// CheckExtraCXXDefaultArguments - Check for any extra default
370/// arguments in the declarator, which is not a function declaration
371/// or definition and therefore is not permitted to have default
372/// arguments. This routine should be invoked for every declarator
373/// that is not a function declaration or definition.
374void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
375 // C++ [dcl.fct.default]p3
376 // A default argument expression shall be specified only in the
377 // parameter-declaration-clause of a function declaration or in a
378 // template-parameter (14.1). It shall not be specified for a
379 // parameter pack. If it is specified in a
380 // parameter-declaration-clause, it shall not occur within a
381 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000382 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattner83f095c2009-03-28 19:18:32 +0000383 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000384 DeclaratorChunk &chunk = D.getTypeObject(i);
385 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000386 if (MightBeFunction) {
387 // This is a function declaration. It can have default arguments, but
388 // keep looking in case its return type is a function type with default
389 // arguments.
390 MightBeFunction = false;
391 continue;
392 }
Alp Tokerc5350722014-02-26 22:27:52 +0000393 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
394 ++argIdx) {
395 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000396 if (Param->hasUnparsedDefaultArg()) {
Alp Tokerc5350722014-02-26 22:27:52 +0000397 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
David Majnemerb3c6d522015-01-13 07:42:33 +0000398 SourceRange SR;
399 if (Toks->size() > 1)
400 SR = SourceRange((*Toks)[1].getLocation(),
401 Toks->back().getLocation());
402 else
403 SR = UnparsedDefaultArgLocs[Param];
Douglas Gregor4d87df52008-12-16 21:30:33 +0000404 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
David Majnemerb3c6d522015-01-13 07:42:33 +0000405 << SR;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000406 delete Toks;
Craig Topperc3ec1492014-05-26 06:22:03 +0000407 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
Douglas Gregor58354032008-12-24 00:01:03 +0000408 } else if (Param->getDefaultArg()) {
409 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
410 << Param->getDefaultArg()->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +0000411 Param->setDefaultArg(nullptr);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000412 }
413 }
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000414 } else if (chunk.Kind != DeclaratorChunk::Paren) {
415 MightBeFunction = false;
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000416 }
417 }
418}
419
David Majnemer502b0ed2013-06-25 23:09:30 +0000420static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
421 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
422 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
423 if (!PVD->hasDefaultArg())
424 return false;
425 if (!PVD->hasInheritedDefaultArg())
426 return true;
427 }
428 return false;
429}
430
Craig Toppere4794282012-09-21 04:33:26 +0000431/// MergeCXXFunctionDecl - Merge two declarations of the same C++
432/// function, once we already know that they have the same
433/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
434/// error, false otherwise.
James Molloye9430032012-03-13 08:55:35 +0000435bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
436 Scope *S) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000437 bool Invalid = false;
438
Richard Smithc7d48d12015-05-20 17:50:35 +0000439 // The declaration context corresponding to the scope is the semantic
440 // parent, unless this is a local function declaration, in which case
441 // it is that surrounding function.
442 DeclContext *ScopeDC = New->isLocalExternDecl()
443 ? New->getLexicalDeclContext()
444 : New->getDeclContext();
445
446 // Find the previous declaration for the purpose of default arguments.
447 FunctionDecl *PrevForDefaultArgs = Old;
448 for (/**/; PrevForDefaultArgs;
449 // Don't bother looking back past the latest decl if this is a local
450 // extern declaration; nothing else could work.
451 PrevForDefaultArgs = New->isLocalExternDecl()
452 ? nullptr
453 : PrevForDefaultArgs->getPreviousDecl()) {
454 // Ignore hidden declarations.
455 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
456 continue;
457
458 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
459 !New->isCXXClassMember()) {
460 // Ignore default arguments of old decl if they are not in
461 // the same scope and this is not an out-of-line definition of
462 // a member function.
463 continue;
464 }
465
466 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
467 // If only one of these is a local function declaration, then they are
468 // declared in different scopes, even though isDeclInScope may think
469 // they're in the same scope. (If both are local, the scope check is
470 // sufficent, and if neither is local, then they are in the same scope.)
471 continue;
472 }
473
474 // We found our guy.
475 break;
476 }
477
Chris Lattner199abbc2008-04-08 05:04:30 +0000478 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000479 // For non-template functions, default arguments can be added in
480 // later declarations of a function in the same
481 // scope. Declarations in different scopes have completely
482 // distinct sets of default arguments. That is, declarations in
483 // inner scopes do not acquire default arguments from
484 // declarations in outer scopes, and vice versa. In a given
485 // function declaration, all parameters subsequent to a
486 // parameter with a default argument shall have default
487 // arguments supplied in this or previous declarations. A
488 // default argument shall not be redefined by a later
489 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000490 //
491 // C++ [dcl.fct.default]p6:
Richard Smith541b38b2013-09-20 01:15:31 +0000492 // Except for member functions of class templates, the default arguments
493 // in a member function definition that appears outside of the class
494 // definition are added to the set of default arguments provided by the
Douglas Gregorc732aba2009-09-11 18:44:32 +0000495 // member function declaration in the class definition.
Richard Smithc7d48d12015-05-20 17:50:35 +0000496 for (unsigned p = 0, NumParams = PrevForDefaultArgs
497 ? PrevForDefaultArgs->getNumParams()
498 : 0;
499 p < NumParams; ++p) {
500 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
Chris Lattner199abbc2008-04-08 05:04:30 +0000501 ParmVarDecl *NewParam = New->getParamDecl(p);
502
Richard Smithc7d48d12015-05-20 17:50:35 +0000503 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
James Molloye9430032012-03-13 08:55:35 +0000504 bool NewParamHasDfl = NewParam->hasDefaultArg();
505
James Molloye9430032012-03-13 08:55:35 +0000506 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000507 unsigned DiagDefaultParamID =
508 diag::err_param_default_argument_redefinition;
509
510 // MSVC accepts that default parameters be redefined for member functions
511 // of template class. The new default parameter's value is ignored.
512 Invalid = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000513 if (getLangOpts().MicrosoftExt) {
Richard Smithc7d48d12015-05-20 17:50:35 +0000514 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000515 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000516 // Merge the old default argument into the new parameter.
517 NewParam->setHasInheritedDefaultArg();
518 if (OldParam->hasUninstantiatedDefaultArg())
519 NewParam->setUninstantiatedDefaultArg(
520 OldParam->getUninstantiatedDefaultArg());
521 else
522 NewParam->setDefaultArg(OldParam->getInit());
Richard Smith1b98ccc2014-07-19 01:39:17 +0000523 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000524 Invalid = false;
525 }
526 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000527
Francois Pichet8cb243a2011-04-10 04:58:30 +0000528 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
529 // hint here. Alternatively, we could walk the type-source information
530 // for NewParam to find the last source location in the type... but it
531 // isn't worth the effort right now. This is the kind of test case that
532 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000533 // int f(int);
534 // void g(int (*fp)(int) = f);
535 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000536 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000537 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000538
539 // Look for the function declaration where the default argument was
540 // actually written, which may be a declaration prior to Old.
Richard Smithc7d48d12015-05-20 17:50:35 +0000541 for (auto Older = PrevForDefaultArgs;
542 OldParam->hasInheritedDefaultArg(); /**/) {
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000543 Older = Older->getPreviousDecl();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000544 OldParam = Older->getParamDecl(p);
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000545 }
546
Douglas Gregorc732aba2009-09-11 18:44:32 +0000547 Diag(OldParam->getLocation(), diag::note_previous_definition)
548 << OldParam->getDefaultArgRange();
James Molloye9430032012-03-13 08:55:35 +0000549 } else if (OldParamHasDfl) {
John McCalle61b02b2010-05-04 01:53:42 +0000550 // Merge the old default argument into the new parameter.
551 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000552 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000553 NewParam->setHasInheritedDefaultArg();
Nathan Sidwell5bb231c2015-02-19 14:03:22 +0000554 if (OldParam->hasUnparsedDefaultArg())
555 NewParam->setUnparsedDefaultArg();
556 else if (OldParam->hasUninstantiatedDefaultArg())
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000557 NewParam->setUninstantiatedDefaultArg(
558 OldParam->getUninstantiatedDefaultArg());
559 else
John McCalle61b02b2010-05-04 01:53:42 +0000560 NewParam->setDefaultArg(OldParam->getInit());
James Molloye9430032012-03-13 08:55:35 +0000561 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000562 if (New->getDescribedFunctionTemplate()) {
563 // Paragraph 4, quoted above, only applies to non-template functions.
564 Diag(NewParam->getLocation(),
565 diag::err_param_default_argument_template_redecl)
566 << NewParam->getDefaultArgRange();
Richard Smithc7d48d12015-05-20 17:50:35 +0000567 Diag(PrevForDefaultArgs->getLocation(),
568 diag::note_template_prev_declaration)
569 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000570 } else if (New->getTemplateSpecializationKind()
571 != TSK_ImplicitInstantiation &&
572 New->getTemplateSpecializationKind() != TSK_Undeclared) {
573 // C++ [temp.expr.spec]p21:
574 // Default function arguments shall not be specified in a declaration
575 // or a definition for one of the following explicit specializations:
576 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000577 // - the explicit specialization of a member function template;
578 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000579 // template where the class template specialization to which the
580 // member function specialization belongs is implicitly
581 // instantiated.
582 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
583 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
584 << New->getDeclName()
585 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000586 } else if (New->getDeclContext()->isDependentContext()) {
587 // C++ [dcl.fct.default]p6 (DR217):
588 // Default arguments for a member function of a class template shall
589 // be specified on the initial declaration of the member function
590 // within the class template.
591 //
592 // Reading the tea leaves a bit in DR217 and its reference to DR205
593 // leads me to the conclusion that one cannot add default function
594 // arguments for an out-of-line definition of a member function of a
595 // dependent type.
596 int WhichKind = 2;
597 if (CXXRecordDecl *Record
598 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
599 if (Record->getDescribedClassTemplate())
600 WhichKind = 0;
601 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
602 WhichKind = 1;
603 else
604 WhichKind = 2;
605 }
606
607 Diag(NewParam->getLocation(),
608 diag::err_param_default_argument_member_template_redecl)
609 << WhichKind
610 << NewParam->getDefaultArgRange();
611 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000612 }
613 }
614
Richard Smith58c3cc12012-11-28 03:45:24 +0000615 // DR1344: If a default argument is added outside a class definition and that
616 // default argument makes the function a special member function, the program
617 // is ill-formed. This can only happen for constructors.
618 if (isa<CXXConstructorDecl>(New) &&
619 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
620 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
621 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
622 if (NewSM != OldSM) {
623 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
624 assert(NewParam->hasDefaultArg());
625 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
626 << NewParam->getDefaultArgRange() << NewSM;
627 Diag(Old->getLocation(), diag::note_previous_declaration);
628 }
629 }
630
David Majnemeree4f4022014-03-30 06:44:54 +0000631 const FunctionDecl *Def;
Richard Smith5b8b3db2012-02-20 23:28:05 +0000632 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000633 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000634 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000635 if (New->isConstexpr() != Old->isConstexpr()) {
636 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
637 << New << New->isConstexpr();
638 Diag(Old->getLocation(), diag::note_previous_declaration);
639 Invalid = true;
Reid Kleckner93864172015-04-08 00:04:47 +0000640 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
641 Old->isDefined(Def)) {
David Majnemeree4f4022014-03-30 06:44:54 +0000642 // C++11 [dcl.fcn.spec]p4:
643 // If the definition of a function appears in a translation unit before its
644 // first declaration as inline, the program is ill-formed.
645 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
646 Diag(Def->getLocation(), diag::note_previous_definition);
647 Invalid = true;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000648 }
649
David Majnemer502b0ed2013-06-25 23:09:30 +0000650 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000651 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000652 // the only declaration of the function or function template in the
653 // translation unit.
654 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
655 functionDeclHasDefaultArgument(Old)) {
656 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
657 Diag(Old->getLocation(), diag::note_previous_declaration);
658 Invalid = true;
659 }
660
Douglas Gregorf40863c2010-02-12 07:32:17 +0000661 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000662 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000663
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000664 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000665}
666
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000667/// \brief Merge the exception specifications of two variable declarations.
668///
669/// This is called when there's a redeclaration of a VarDecl. The function
670/// checks if the redeclaration might have an exception specification and
671/// validates compatibility and merges the specs if necessary.
672void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
673 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000674 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000675 return;
676
677 assert(Context.hasSameType(New->getType(), Old->getType()) &&
678 "Should only be called if types are otherwise the same.");
679
680 QualType NewType = New->getType();
681 QualType OldType = Old->getType();
682
683 // We're only interested in pointers and references to functions, as well
684 // as pointers to member functions.
685 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
686 NewType = R->getPointeeType();
687 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
688 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
689 NewType = P->getPointeeType();
690 OldType = OldType->getAs<PointerType>()->getPointeeType();
691 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
692 NewType = M->getPointeeType();
693 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
694 }
695
696 if (!NewType->isFunctionProtoType())
697 return;
698
699 // There's lots of special cases for functions. For function pointers, system
700 // libraries are hopefully not as broken so that we don't need these
701 // workarounds.
702 if (CheckEquivalentExceptionSpec(
703 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
704 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
705 New->setInvalidDecl();
706 }
707}
708
Chris Lattner199abbc2008-04-08 05:04:30 +0000709/// CheckCXXDefaultArguments - Verify that the default arguments for a
710/// function declaration are well-formed according to C++
711/// [dcl.fct.default].
712void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
713 unsigned NumParams = FD->getNumParams();
714 unsigned p;
715
716 // Find first parameter with a default argument
717 for (p = 0; p < NumParams; ++p) {
718 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +0000719 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000720 break;
721 }
722
Benjamin Kramerfe257592015-03-27 13:58:41 +0000723 // C++11 [dcl.fct.default]p4:
724 // In a given function declaration, each parameter subsequent to a parameter
725 // with a default argument shall have a default argument supplied in this or
726 // a previous declaration or shall be a function parameter pack. A default
727 // argument shall not be redefined by a later declaration (not even to the
728 // same value).
Chris Lattner199abbc2008-04-08 05:04:30 +0000729 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000730 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000731 ParmVarDecl *Param = FD->getParamDecl(p);
Benjamin Kramerfe257592015-03-27 13:58:41 +0000732 if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000733 if (Param->isInvalidDecl())
734 /* We already complained about this parameter. */;
735 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000736 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000737 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000738 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000739 else
Mike Stump11289f42009-09-09 15:08:12 +0000740 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000741 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000742
Chris Lattner199abbc2008-04-08 05:04:30 +0000743 LastMissingDefaultArg = p;
744 }
745 }
746
747 if (LastMissingDefaultArg > 0) {
748 // Some default arguments were missing. Clear out all of the
749 // default arguments up to (and including) the last missing
750 // default argument, so that we leave the function parameters
751 // in a semantically valid state.
752 for (p = 0; p <= LastMissingDefaultArg; ++p) {
753 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000754 if (Param->hasDefaultArg()) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000755 Param->setDefaultArg(nullptr);
Chris Lattner199abbc2008-04-08 05:04:30 +0000756 }
757 }
758 }
759}
Douglas Gregor556877c2008-04-13 21:30:24 +0000760
Richard Smitheb3c10c2011-10-01 02:31:28 +0000761// CheckConstexprParameterTypes - Check whether a function's parameter types
762// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +0000763// diagnostic and return false.
764static bool CheckConstexprParameterTypes(Sema &SemaRef,
765 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000766 unsigned ArgIndex = 0;
767 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +0000768 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
769 e = FT->param_type_end();
770 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000771 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
772 SourceLocation ParamLoc = PD->getLocation();
773 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000774 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000775 diag::err_constexpr_non_literal_param,
776 ArgIndex+1, PD->getSourceRange(),
777 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000778 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000779 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000780 return true;
781}
782
783/// \brief Get diagnostic %select index for tag kind for
784/// record diagnostic message.
785/// WARNING: Indexes apply to particular diagnostics only!
786///
787/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +0000788static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +0000789 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +0000790 case TTK_Struct: return 0;
791 case TTK_Interface: return 1;
792 case TTK_Class: return 2;
793 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +0000794 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000795}
796
797// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
798// the requirements of a constexpr function definition or a constexpr
799// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +0000800// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000801//
Richard Smith3607ffe2012-02-13 03:54:03 +0000802// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
803bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +0000804 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
805 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000806 // C++11 [dcl.constexpr]p4:
807 // The definition of a constexpr constructor shall satisfy the following
808 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000809 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +0000810 const CXXRecordDecl *RD = MD->getParent();
811 if (RD->getNumVBases()) {
812 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
813 << isa<CXXConstructorDecl>(NewFD)
814 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Aaron Ballman445a9392014-03-13 16:15:17 +0000815 for (const auto &I : RD->vbases())
816 Diag(I.getLocStart(),
817 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000818 return false;
819 }
Richard Smith7971b692012-01-13 04:54:00 +0000820 }
821
822 if (!isa<CXXConstructorDecl>(NewFD)) {
823 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000824 // The definition of a constexpr function shall satisfy the following
825 // constraints:
826 // - it shall not be virtual;
827 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
828 if (Method && Method->isVirtual()) {
David Majnemerab6607a2015-05-22 05:49:41 +0000829 Method = Method->getCanonicalDecl();
830 Diag(Method->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000831
Richard Smith3607ffe2012-02-13 03:54:03 +0000832 // If it's not obvious why this function is virtual, find an overridden
833 // function which uses the 'virtual' keyword.
834 const CXXMethodDecl *WrittenVirtual = Method;
835 while (!WrittenVirtual->isVirtualAsWritten())
836 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
837 if (WrittenVirtual != Method)
838 Diag(WrittenVirtual->getLocation(),
839 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000840 return false;
841 }
842
843 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +0000844 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000845 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000846 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000847 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000848 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000849 }
850
Richard Smith7971b692012-01-13 04:54:00 +0000851 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +0000852 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +0000853 return false;
854
Richard Smitheb3c10c2011-10-01 02:31:28 +0000855 return true;
856}
857
858/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +0000859/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000860///
Richard Smithd9f663b2013-04-22 15:31:51 +0000861/// \return true if the body is OK (maybe only as an extension), false if we
862/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000863static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +0000864 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
865 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000866 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
867 // contain only
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000868 for (const auto *DclIt : DS->decls()) {
869 switch (DclIt->getKind()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000870 case Decl::StaticAssert:
871 case Decl::Using:
872 case Decl::UsingShadow:
873 case Decl::UsingDirective:
874 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +0000875 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000876 // - static_assert-declarations
877 // - using-declarations,
878 // - using-directives,
879 continue;
880
881 case Decl::Typedef:
882 case Decl::TypeAlias: {
883 // - typedef declarations and alias-declarations that do not define
884 // classes or enumerations,
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000885 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000886 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
887 // Don't allow variably-modified types in constexpr functions.
888 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
889 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
890 << TL.getSourceRange() << TL.getType()
891 << isa<CXXConstructorDecl>(Dcl);
892 return false;
893 }
894 continue;
895 }
896
897 case Decl::Enum:
898 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +0000899 // C++1y allows types to be defined, not just declared.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000900 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smithd9f663b2013-04-22 15:31:51 +0000901 SemaRef.Diag(DS->getLocStart(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000902 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +0000903 ? diag::warn_cxx11_compat_constexpr_type_definition
904 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000905 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000906 continue;
907
Richard Smithd9f663b2013-04-22 15:31:51 +0000908 case Decl::EnumConstant:
909 case Decl::IndirectField:
910 case Decl::ParmVar:
911 // These can only appear with other declarations which are banned in
912 // C++11 and permitted in C++1y, so ignore them.
913 continue;
914
915 case Decl::Var: {
916 // C++1y [dcl.constexpr]p3 allows anything except:
917 // a definition of a variable of non-literal type or of static or
918 // thread storage duration or for which no initialization is performed.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000919 const auto *VD = cast<VarDecl>(DclIt);
Richard Smithd9f663b2013-04-22 15:31:51 +0000920 if (VD->isThisDeclarationADefinition()) {
921 if (VD->isStaticLocal()) {
922 SemaRef.Diag(VD->getLocation(),
923 diag::err_constexpr_local_var_static)
924 << isa<CXXConstructorDecl>(Dcl)
925 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
926 return false;
927 }
Richard Smith3da88fa2013-04-26 14:36:30 +0000928 if (!VD->getType()->isDependentType() &&
929 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +0000930 VD->getLocation(), VD->getType(),
931 diag::err_constexpr_local_var_non_literal_type,
932 isa<CXXConstructorDecl>(Dcl)))
933 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +0000934 if (!VD->getType()->isDependentType() &&
935 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000936 SemaRef.Diag(VD->getLocation(),
937 diag::err_constexpr_local_var_no_init)
938 << isa<CXXConstructorDecl>(Dcl);
939 return false;
940 }
941 }
942 SemaRef.Diag(VD->getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000943 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +0000944 ? diag::warn_cxx11_compat_constexpr_local_var
945 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000946 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +0000947 continue;
948 }
949
950 case Decl::NamespaceAlias:
951 case Decl::Function:
952 // These are disallowed in C++11 and permitted in C++1y. Allow them
953 // everywhere as an extension.
954 if (!Cxx1yLoc.isValid())
955 Cxx1yLoc = DS->getLocStart();
956 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000957
958 default:
959 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
960 << isa<CXXConstructorDecl>(Dcl);
961 return false;
962 }
963 }
964
965 return true;
966}
967
968/// Check that the given field is initialized within a constexpr constructor.
969///
970/// \param Dcl The constexpr constructor being checked.
971/// \param Field The field being checked. This may be a member of an anonymous
972/// struct or union nested within the class being checked.
973/// \param Inits All declarations, including anonymous struct/union members and
974/// indirect members, for which any initialization was provided.
975/// \param Diagnosed Set to true if an error is produced.
976static void CheckConstexprCtorInitializer(Sema &SemaRef,
977 const FunctionDecl *Dcl,
978 FieldDecl *Field,
979 llvm::SmallSet<Decl*, 16> &Inits,
980 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +0000981 if (Field->isInvalidDecl())
982 return;
983
Douglas Gregor556e5862011-10-10 17:22:13 +0000984 if (Field->isUnnamedBitfield())
985 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +0000986
Richard Smithab44d5b2013-12-10 08:25:00 +0000987 // Anonymous unions with no variant members and empty anonymous structs do not
988 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
989 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +0000990 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +0000991 (Field->getType()->isUnionType()
992 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
993 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +0000994 return;
995
Richard Smitheb3c10c2011-10-01 02:31:28 +0000996 if (!Inits.count(Field)) {
997 if (!Diagnosed) {
998 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
999 Diagnosed = true;
1000 }
1001 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1002 } else if (Field->isAnonymousStructOrUnion()) {
1003 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001004 for (auto *I : RD->fields())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001005 // If an anonymous union contains an anonymous struct of which any member
1006 // is initialized, all members must be initialized.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001007 if (!RD->isUnion() || Inits.count(I))
1008 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001009 }
1010}
1011
Richard Smithd9f663b2013-04-22 15:31:51 +00001012/// Check the provided statement is allowed in a constexpr function
1013/// definition.
1014static bool
1015CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00001016 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001017 SourceLocation &Cxx1yLoc) {
1018 // - its function-body shall be [...] a compound-statement that contains only
1019 switch (S->getStmtClass()) {
1020 case Stmt::NullStmtClass:
1021 // - null statements,
1022 return true;
1023
1024 case Stmt::DeclStmtClass:
1025 // - static_assert-declarations
1026 // - using-declarations,
1027 // - using-directives,
1028 // - typedef declarations and alias-declarations that do not define
1029 // classes or enumerations,
1030 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1031 return false;
1032 return true;
1033
1034 case Stmt::ReturnStmtClass:
1035 // - and exactly one return statement;
1036 if (isa<CXXConstructorDecl>(Dcl)) {
1037 // C++1y allows return statements in constexpr constructors.
1038 if (!Cxx1yLoc.isValid())
1039 Cxx1yLoc = S->getLocStart();
1040 return true;
1041 }
1042
1043 ReturnStmts.push_back(S->getLocStart());
1044 return true;
1045
1046 case Stmt::CompoundStmtClass: {
1047 // C++1y allows compound-statements.
1048 if (!Cxx1yLoc.isValid())
1049 Cxx1yLoc = S->getLocStart();
1050
1051 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001052 for (auto *BodyIt : CompStmt->body()) {
1053 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001054 Cxx1yLoc))
1055 return false;
1056 }
1057 return true;
1058 }
1059
1060 case Stmt::AttributedStmtClass:
1061 if (!Cxx1yLoc.isValid())
1062 Cxx1yLoc = S->getLocStart();
1063 return true;
1064
1065 case Stmt::IfStmtClass: {
1066 // C++1y allows if-statements.
1067 if (!Cxx1yLoc.isValid())
1068 Cxx1yLoc = S->getLocStart();
1069
1070 IfStmt *If = cast<IfStmt>(S);
1071 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1072 Cxx1yLoc))
1073 return false;
1074 if (If->getElse() &&
1075 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1076 Cxx1yLoc))
1077 return false;
1078 return true;
1079 }
1080
1081 case Stmt::WhileStmtClass:
1082 case Stmt::DoStmtClass:
1083 case Stmt::ForStmtClass:
1084 case Stmt::CXXForRangeStmtClass:
1085 case Stmt::ContinueStmtClass:
1086 // C++1y allows all of these. We don't allow them as extensions in C++11,
1087 // because they don't make sense without variable mutation.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001088 if (!SemaRef.getLangOpts().CPlusPlus14)
Richard Smithd9f663b2013-04-22 15:31:51 +00001089 break;
1090 if (!Cxx1yLoc.isValid())
1091 Cxx1yLoc = S->getLocStart();
Benjamin Kramer642f1732015-07-02 21:03:14 +00001092 for (Stmt *SubStmt : S->children())
1093 if (SubStmt &&
1094 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001095 Cxx1yLoc))
1096 return false;
1097 return true;
1098
1099 case Stmt::SwitchStmtClass:
1100 case Stmt::CaseStmtClass:
1101 case Stmt::DefaultStmtClass:
1102 case Stmt::BreakStmtClass:
1103 // C++1y allows switch-statements, and since they don't need variable
1104 // mutation, we can reasonably allow them in C++11 as an extension.
1105 if (!Cxx1yLoc.isValid())
1106 Cxx1yLoc = S->getLocStart();
Benjamin Kramer642f1732015-07-02 21:03:14 +00001107 for (Stmt *SubStmt : S->children())
1108 if (SubStmt &&
1109 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001110 Cxx1yLoc))
1111 return false;
1112 return true;
1113
1114 default:
1115 if (!isa<Expr>(S))
1116 break;
1117
1118 // C++1y allows expression-statements.
1119 if (!Cxx1yLoc.isValid())
1120 Cxx1yLoc = S->getLocStart();
1121 return true;
1122 }
1123
1124 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1125 << isa<CXXConstructorDecl>(Dcl);
1126 return false;
1127}
1128
Richard Smitheb3c10c2011-10-01 02:31:28 +00001129/// Check the body for the given constexpr function declaration only contains
1130/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1131///
1132/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001133bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001134 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001135 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001136 // The definition of a constexpr function shall satisfy the following
1137 // constraints: [...]
1138 // - its function-body shall be = delete, = default, or a
1139 // compound-statement
1140 //
Richard Smith74388b42012-02-04 00:33:54 +00001141 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001142 // In the definition of a constexpr constructor, [...]
1143 // - its function-body shall not be a function-try-block;
1144 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1145 << isa<CXXConstructorDecl>(Dcl);
1146 return false;
1147 }
1148
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001149 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001150
1151 // - its function-body shall be [...] a compound-statement that contains only
1152 // [... list of cases ...]
1153 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1154 SourceLocation Cxx1yLoc;
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001155 for (auto *BodyIt : CompBody->body()) {
1156 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smithd9f663b2013-04-22 15:31:51 +00001157 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001158 }
1159
Richard Smithd9f663b2013-04-22 15:31:51 +00001160 if (Cxx1yLoc.isValid())
1161 Diag(Cxx1yLoc,
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001162 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001163 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1164 : diag::ext_constexpr_body_invalid_stmt)
1165 << isa<CXXConstructorDecl>(Dcl);
1166
Richard Smitheb3c10c2011-10-01 02:31:28 +00001167 if (const CXXConstructorDecl *Constructor
1168 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1169 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001170 // DR1359:
1171 // - every non-variant non-static data member and base class sub-object
1172 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001173 // DR1460:
1174 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001175 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001176 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001177 if (Constructor->getNumCtorInitializers() == 0 &&
1178 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001179 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1180 return false;
1181 }
Richard Smithf368fb42011-10-10 16:38:04 +00001182 } else if (!Constructor->isDependentContext() &&
1183 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001184 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1185
1186 // Skip detailed checking if we have enough initializers, and we would
1187 // allow at most one initializer per member.
1188 bool AnyAnonStructUnionMembers = false;
1189 unsigned Fields = 0;
1190 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1191 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001192 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001193 AnyAnonStructUnionMembers = true;
1194 break;
1195 }
1196 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001197 // DR1460:
1198 // - if the class is a union-like class, but is not a union, for each of
1199 // its anonymous union members having variant members, exactly one of
1200 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001201 if (AnyAnonStructUnionMembers ||
1202 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1203 // Check initialization of non-static data members. Base classes are
1204 // always initialized so do not need to be checked. Dependent bases
1205 // might not have initializers in the member initializer list.
1206 llvm::SmallSet<Decl*, 16> Inits;
Aaron Ballman0ad78302014-03-13 17:34:31 +00001207 for (const auto *I: Constructor->inits()) {
1208 if (FieldDecl *FD = I->getMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001209 Inits.insert(FD);
Aaron Ballman0ad78302014-03-13 17:34:31 +00001210 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001211 Inits.insert(ID->chain_begin(), ID->chain_end());
1212 }
1213
1214 bool Diagnosed = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001215 for (auto *I : RD->fields())
1216 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001217 if (Diagnosed)
1218 return false;
1219 }
1220 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001221 } else {
1222 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001223 // C++1y doesn't require constexpr functions to contain a 'return'
Richard Smith06ffb452014-04-22 23:14:23 +00001224 // statement. We still do, unless the return type might be void, because
Richard Smithd9f663b2013-04-22 15:31:51 +00001225 // otherwise if there's no return statement, the function cannot
1226 // be used in a core constant expression.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001227 bool OK = getLangOpts().CPlusPlus14 &&
Richard Smith06ffb452014-04-22 23:14:23 +00001228 (Dcl->getReturnType()->isVoidType() ||
1229 Dcl->getReturnType()->isDependentType());
Richard Smithd9f663b2013-04-22 15:31:51 +00001230 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00001231 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1232 : diag::err_constexpr_body_no_return);
1233 return OK;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001234 }
1235 if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001236 Diag(ReturnStmts.back(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001237 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001238 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1239 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001240 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1241 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001242 }
1243 }
1244
Richard Smith74388b42012-02-04 00:33:54 +00001245 // C++11 [dcl.constexpr]p5:
1246 // if no function argument values exist such that the function invocation
1247 // substitution would produce a constant expression, the program is
1248 // ill-formed; no diagnostic required.
1249 // C++11 [dcl.constexpr]p3:
1250 // - every constructor call and implicit conversion used in initializing the
1251 // return value shall be one of those allowed in a constant expression.
1252 // C++11 [dcl.constexpr]p4:
1253 // - every constructor involved in initializing non-static data members and
1254 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001255 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00001256 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00001257 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00001258 << isa<CXXConstructorDecl>(Dcl);
1259 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1260 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00001261 // Don't return false here: we allow this for compatibility in
1262 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00001263 }
1264
Richard Smitheb3c10c2011-10-01 02:31:28 +00001265 return true;
1266}
1267
Douglas Gregor61956c42008-10-31 09:07:45 +00001268/// isCurrentClassName - Determine whether the identifier II is the
1269/// name of the class type currently being defined. In the case of
1270/// nested classes, this will only return true if II is the name of
1271/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001272bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1273 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001274 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00001275
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001276 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00001277 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00001278 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001279 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1280 } else
1281 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1282
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00001283 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00001284 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00001285 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00001286}
1287
Richard Smithfb8b7b92013-10-15 00:00:26 +00001288/// \brief Determine whether the identifier II is a typo for the name of
1289/// the class type currently being defined. If so, update it to the identifier
1290/// that should have been used.
1291bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1292 assert(getLangOpts().CPlusPlus && "No class names in C!");
1293
1294 if (!getLangOpts().SpellChecking)
1295 return false;
1296
1297 CXXRecordDecl *CurDecl;
1298 if (SS && SS->isSet() && !SS->isInvalid()) {
1299 DeclContext *DC = computeDeclContext(*SS, true);
1300 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1301 } else
1302 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1303
1304 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1305 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1306 < II->getLength()) {
1307 II = CurDecl->getIdentifier();
1308 return true;
1309 }
1310
1311 return false;
1312}
1313
Douglas Gregordc974572012-11-10 07:24:09 +00001314/// \brief Determine whether the given class is a base class of the given
1315/// class, including looking at dependent bases.
1316static bool findCircularInheritance(const CXXRecordDecl *Class,
1317 const CXXRecordDecl *Current) {
1318 SmallVector<const CXXRecordDecl*, 8> Queue;
1319
1320 Class = Class->getCanonicalDecl();
1321 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001322 for (const auto &I : Current->bases()) {
1323 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregordc974572012-11-10 07:24:09 +00001324 if (!Base)
1325 continue;
1326
1327 Base = Base->getDefinition();
1328 if (!Base)
1329 continue;
1330
1331 if (Base->getCanonicalDecl() == Class)
1332 return true;
1333
1334 Queue.push_back(Base);
1335 }
1336
1337 if (Queue.empty())
1338 return false;
1339
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001340 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00001341 }
1342
1343 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00001344}
1345
Mike Stump11289f42009-09-09 15:08:12 +00001346/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001347///
1348/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1349/// and returns NULL otherwise.
1350CXXBaseSpecifier *
1351Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1352 SourceRange SpecifierRange,
1353 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001354 TypeSourceInfo *TInfo,
1355 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001356 QualType BaseType = TInfo->getType();
1357
Douglas Gregor463421d2009-03-03 04:44:36 +00001358 // C++ [class.union]p1:
1359 // A union shall not have base classes.
1360 if (Class->isUnion()) {
1361 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1362 << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001363 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001364 }
1365
Douglas Gregor752a5952011-01-03 22:36:02 +00001366 if (EllipsisLoc.isValid() &&
1367 !TInfo->getType()->containsUnexpandedParameterPack()) {
1368 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1369 << TInfo->getTypeLoc().getSourceRange();
1370 EllipsisLoc = SourceLocation();
1371 }
Douglas Gregor62004702012-11-10 01:18:17 +00001372
1373 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1374
1375 if (BaseType->isDependentType()) {
1376 // Make sure that we don't have circular inheritance among our dependent
1377 // bases. For non-dependent bases, the check for completeness below handles
1378 // this.
1379 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1380 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1381 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00001382 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00001383 Diag(BaseLoc, diag::err_circular_inheritance)
1384 << BaseType << Context.getTypeDeclType(Class);
1385
1386 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1387 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1388 << BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00001389
1390 return nullptr;
Douglas Gregor62004702012-11-10 01:18:17 +00001391 }
1392 }
1393
Mike Stump11289f42009-09-09 15:08:12 +00001394 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001395 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001396 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00001397 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001398
1399 // Base specifiers must be record types.
1400 if (!BaseType->isRecordType()) {
1401 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001402 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001403 }
1404
1405 // C++ [class.union]p1:
1406 // A union shall not be used as a base class.
1407 if (BaseType->isUnionType()) {
1408 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001409 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001410 }
1411
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00001412 // For the MS ABI, propagate DLL attributes to base class templates.
1413 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1414 if (Attr *ClassAttr = getDLLAttr(Class)) {
1415 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1416 BaseType->getAsCXXRecordDecl())) {
Hans Wennborgfce87ca2015-06-09 00:39:09 +00001417 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
1418 BaseLoc);
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00001419 }
1420 }
1421 }
1422
Douglas Gregor463421d2009-03-03 04:44:36 +00001423 // C++ [class.derived]p2:
1424 // The class-name in a base-specifier shall not be an incompletely
1425 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001426 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001427 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00001428 Class->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00001429 return nullptr;
John McCall3696dcb2010-08-17 07:23:57 +00001430 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001431
Eli Friedmanc96d4962009-08-15 21:55:26 +00001432 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001433 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001434 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001435 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001436 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00001437 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00001438 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001439
David Majnemer9b1754d2013-11-02 12:00:36 +00001440 // A class which contains a flexible array member is not suitable for use as a
1441 // base class:
1442 // - If the layout determines that a base comes before another base,
1443 // the flexible array member would index into the subsequent base.
1444 // - If the layout determines that base comes before the derived class,
1445 // the flexible array member would index into the derived class.
1446 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1447 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1448 << CXXBaseDecl->getDeclName();
Craig Topperc3ec1492014-05-26 06:22:03 +00001449 return nullptr;
David Majnemer9b1754d2013-11-02 12:00:36 +00001450 }
1451
Anders Carlsson65c76d32011-03-25 14:55:14 +00001452 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00001453 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00001454 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00001455 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00001456 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00001457 << CXXBaseDecl->getDeclName()
1458 << FA->isSpelledAsSealed();
Alp Toker2afa8782014-05-28 12:20:14 +00001459 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1460 << CXXBaseDecl->getDeclName() << FA->getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00001461 return nullptr;
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001462 }
1463
John McCall3696dcb2010-08-17 07:23:57 +00001464 if (BaseDecl->isInvalidDecl())
1465 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00001466
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001467 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001468 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001469 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001470 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001471}
1472
Douglas Gregor556877c2008-04-13 21:30:24 +00001473/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1474/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001475/// example:
1476/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001477/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001478BaseResult
John McCall48871652010-08-21 09:40:31 +00001479Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00001480 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00001481 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001482 ParsedType basetype, SourceLocation BaseLoc,
1483 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001484 if (!classdecl)
1485 return true;
1486
Douglas Gregorc40290e2009-03-09 23:48:35 +00001487 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001488 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001489 if (!Class)
1490 return true;
1491
David Majnemer5ef4fe72014-06-13 06:43:46 +00001492 // We haven't yet attached the base specifiers.
1493 Class->setIsParsingBaseSpecifiers();
1494
Richard Smith4c96e992013-02-19 23:47:15 +00001495 // We do not support any C++11 attributes on base-specifiers yet.
1496 // Diagnose any attributes we see.
1497 if (!Attributes.empty()) {
1498 for (AttributeList *Attr = Attributes.getList(); Attr;
1499 Attr = Attr->getNext()) {
1500 if (Attr->isInvalid() ||
1501 Attr->getKind() == AttributeList::IgnoredAttribute)
1502 continue;
1503 Diag(Attr->getLoc(),
1504 Attr->getKind() == AttributeList::UnknownAttribute
1505 ? diag::warn_unknown_attribute_ignored
1506 : diag::err_base_specifier_attribute)
1507 << Attr->getName();
1508 }
1509 }
1510
Craig Topperc3ec1492014-05-26 06:22:03 +00001511 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001512 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001513
Douglas Gregor752a5952011-01-03 22:36:02 +00001514 if (EllipsisLoc.isInvalid() &&
1515 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001516 UPPC_BaseType))
1517 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001518
Douglas Gregor463421d2009-03-03 04:44:36 +00001519 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001520 Virtual, Access, TInfo,
1521 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001522 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001523 else
1524 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001525
Douglas Gregor463421d2009-03-03 04:44:36 +00001526 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001527}
Douglas Gregor556877c2008-04-13 21:30:24 +00001528
Nathan Sidwell44b21742015-01-19 01:44:02 +00001529/// Use small set to collect indirect bases. As this is only used
1530/// locally, there's no need to abstract the small size parameter.
1531typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
1532
1533/// \brief Recursively add the bases of Type. Don't add Type itself.
1534static void
1535NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
1536 const QualType &Type)
1537{
1538 // Even though the incoming type is a base, it might not be
1539 // a class -- it could be a template parm, for instance.
1540 if (auto Rec = Type->getAs<RecordType>()) {
1541 auto Decl = Rec->getAsCXXRecordDecl();
1542
1543 // Iterate over its bases.
1544 for (const auto &BaseSpec : Decl->bases()) {
1545 QualType Base = Context.getCanonicalType(BaseSpec.getType())
1546 .getUnqualifiedType();
1547 if (Set.insert(Base).second)
1548 // If we've not already seen it, recurse.
1549 NoteIndirectBases(Context, Set, Base);
1550 }
1551 }
1552}
1553
Douglas Gregor463421d2009-03-03 04:44:36 +00001554/// \brief Performs the actual work of attaching the given base class
1555/// specifiers to a C++ class.
1556bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1557 unsigned NumBases) {
1558 if (NumBases == 0)
1559 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001560
1561 // Used to keep track of which base types we have already seen, so
1562 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001563 // that the key is always the unqualified canonical type of the base
1564 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001565 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1566
Nathan Sidwell44b21742015-01-19 01:44:02 +00001567 // Used to track indirect bases so we can see if a direct base is
1568 // ambiguous.
1569 IndirectBaseSet IndirectBaseTypes;
1570
Douglas Gregor29a92472008-10-22 17:49:05 +00001571 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001572 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001573 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001574 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001575 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001576 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001577 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001578
1579 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1580 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00001581 // C++ [class.mi]p3:
1582 // A class shall not be specified as a direct base class of a
1583 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001584 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001585 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001586 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001587 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001588
1589 // Delete the duplicate base class specifier; we're going to
1590 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001591 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001592
1593 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001594 } else {
1595 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001596 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00001597 Bases[NumGoodBases++] = Bases[idx];
Nathan Sidwell44b21742015-01-19 01:44:02 +00001598
1599 // Note this base's direct & indirect bases, if there could be ambiguity.
1600 if (NumBases > 1)
1601 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
1602
John McCalldb632ac2012-09-25 07:32:39 +00001603 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1604 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1605 if (Class->isInterface() &&
1606 (!RD->isInterface() ||
1607 KnownBase->getAccessSpecifier() != AS_public)) {
1608 // The Microsoft extension __interface does not permit bases that
1609 // are not themselves public interfaces.
1610 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1611 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1612 << RD->getSourceRange();
1613 Invalid = true;
1614 }
1615 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00001616 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00001617 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001618 }
1619 }
1620
1621 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001622 Class->setBases(Bases, NumGoodBases);
Nathan Sidwell44b21742015-01-19 01:44:02 +00001623
1624 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
1625 // Check whether this direct base is inaccessible due to ambiguity.
1626 QualType BaseType = Bases[idx]->getType();
1627 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
1628 .getUnqualifiedType();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001629
Nathan Sidwell44b21742015-01-19 01:44:02 +00001630 if (IndirectBaseTypes.count(CanonicalBase)) {
1631 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1632 /*DetectVirtual=*/true);
1633 bool found
1634 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
1635 assert(found);
NAKAMURA Takumi6a1565c2015-01-19 09:49:59 +00001636 (void)found;
Nathan Sidwell44b21742015-01-19 01:44:02 +00001637
1638 if (Paths.isAmbiguous(CanonicalBase))
1639 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
1640 << BaseType << getAmbiguousPathsDisplayString(Paths)
1641 << Bases[idx]->getSourceRange();
1642 else
1643 assert(Bases[idx]->isVirtual());
1644 }
1645
1646 // Delete the base class specifier, since its data has been copied
1647 // into the CXXRecordDecl.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001648 Context.Deallocate(Bases[idx]);
Nathan Sidwell44b21742015-01-19 01:44:02 +00001649 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001650
1651 return Invalid;
1652}
1653
1654/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1655/// class, after checking whether there are any duplicate base
1656/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001657void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001658 unsigned NumBases) {
1659 if (!ClassDecl || !Bases || !NumBases)
1660 return;
1661
1662 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelme3cea802013-07-22 05:04:01 +00001663 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001664}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001665
Douglas Gregor36d1b142009-10-06 17:59:45 +00001666/// \brief Determine whether the type \p Derived is a C++ class that is
1667/// derived from the type \p Base.
1668bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001669 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001670 return false;
John McCalle78aac42010-03-10 03:28:59 +00001671
Douglas Gregor45bb4832013-03-26 23:36:30 +00001672 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001673 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001674 return false;
1675
Douglas Gregor45bb4832013-03-26 23:36:30 +00001676 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001677 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001678 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00001679
1680 // If either the base or the derived type is invalid, don't try to
1681 // check whether one is derived from the other.
1682 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1683 return false;
1684
John McCall67da35c2010-02-04 22:26:26 +00001685 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1686 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001687}
1688
1689/// \brief Determine whether the type \p Derived is a C++ class that is
1690/// derived from the type \p Base.
1691bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001692 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001693 return false;
1694
Douglas Gregor45bb4832013-03-26 23:36:30 +00001695 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001696 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001697 return false;
1698
Douglas Gregor45bb4832013-03-26 23:36:30 +00001699 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001700 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001701 return false;
1702
Douglas Gregor36d1b142009-10-06 17:59:45 +00001703 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1704}
1705
Anders Carlssona70cff62010-04-24 19:06:50 +00001706void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001707 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001708 assert(BasePathArray.empty() && "Base path array must be empty!");
1709 assert(Paths.isRecordingPaths() && "Must record paths!");
1710
1711 const CXXBasePath &Path = Paths.front();
1712
1713 // We first go backward and check if we have a virtual base.
1714 // FIXME: It would be better if CXXBasePath had the base specifier for
1715 // the nearest virtual base.
1716 unsigned Start = 0;
1717 for (unsigned I = Path.size(); I != 0; --I) {
1718 if (Path[I - 1].Base->isVirtual()) {
1719 Start = I - 1;
1720 break;
1721 }
1722 }
1723
1724 // Now add all bases.
1725 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001726 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001727}
1728
Douglas Gregor36d1b142009-10-06 17:59:45 +00001729/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1730/// conversion (where Derived and Base are class types) is
1731/// well-formed, meaning that the conversion is unambiguous (and
1732/// that all of the base classes are accessible). Returns true
1733/// and emits a diagnostic if the code is ill-formed, returns false
1734/// otherwise. Loc is the location where this routine should point to
1735/// if there is an error, and Range is the source range to highlight
1736/// if there is an error.
1737bool
1738Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001739 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001740 unsigned AmbigiousBaseConvID,
1741 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001742 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001743 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001744 // First, determine whether the path from Derived to Base is
1745 // ambiguous. This is slightly more expensive than checking whether
1746 // the Derived to Base conversion exists, because here we need to
1747 // explore multiple paths to determine if there is an ambiguity.
1748 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1749 /*DetectVirtual=*/false);
1750 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1751 assert(DerivationOkay &&
1752 "Can only be used with a derived-to-base conversion");
1753 (void)DerivationOkay;
1754
1755 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001756 if (InaccessibleBaseID) {
1757 // Check that the base class can be accessed.
1758 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1759 InaccessibleBaseID)) {
1760 case AR_inaccessible:
1761 return true;
1762 case AR_accessible:
1763 case AR_dependent:
1764 case AR_delayed:
1765 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001766 }
John McCall5b0829a2010-02-10 09:31:12 +00001767 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001768
1769 // Build a base path if necessary.
1770 if (BasePath)
1771 BuildBasePathArray(Paths, *BasePath);
1772 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001773 }
1774
David Majnemer626032f2013-06-22 06:43:58 +00001775 if (AmbigiousBaseConvID) {
1776 // We know that the derived-to-base conversion is ambiguous, and
1777 // we're going to produce a diagnostic. Perform the derived-to-base
1778 // search just one more time to compute all of the possible paths so
1779 // that we can print them out. This is more expensive than any of
1780 // the previous derived-to-base checks we've done, but at this point
1781 // performance isn't as much of an issue.
1782 Paths.clear();
1783 Paths.setRecordingPaths(true);
1784 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1785 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1786 (void)StillOkay;
1787
1788 // Build up a textual representation of the ambiguous paths, e.g.,
1789 // D -> B -> A, that will be used to illustrate the ambiguous
1790 // conversions in the diagnostic. We only print one of the paths
1791 // to each base class subobject.
1792 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1793
1794 Diag(Loc, AmbigiousBaseConvID)
1795 << Derived << Base << PathDisplayStr << Range << Name;
1796 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00001797 return true;
1798}
1799
1800bool
1801Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001802 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001803 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001804 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001805 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001806 IgnoreAccess ? 0
1807 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001808 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001809 Loc, Range, DeclarationName(),
1810 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001811}
1812
1813
1814/// @brief Builds a string representing ambiguous paths from a
1815/// specific derived class to different subobjects of the same base
1816/// class.
1817///
1818/// This function builds a string that can be used in error messages
1819/// to show the different paths that one can take through the
1820/// inheritance hierarchy to go from the derived class to different
1821/// subobjects of a base class. The result looks something like this:
1822/// @code
1823/// struct D -> struct B -> struct A
1824/// struct D -> struct C -> struct A
1825/// @endcode
1826std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1827 std::string PathDisplayStr;
1828 std::set<unsigned> DisplayedPaths;
1829 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1830 Path != Paths.end(); ++Path) {
1831 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1832 // We haven't displayed a path to this particular base
1833 // class subobject yet.
1834 PathDisplayStr += "\n ";
1835 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1836 for (CXXBasePath::const_iterator Element = Path->begin();
1837 Element != Path->end(); ++Element)
1838 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1839 }
1840 }
1841
1842 return PathDisplayStr;
1843}
1844
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001845//===----------------------------------------------------------------------===//
1846// C++ class member Handling
1847//===----------------------------------------------------------------------===//
1848
Abramo Bagnarad7340582010-06-05 05:09:32 +00001849/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001850bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1851 SourceLocation ASLoc,
1852 SourceLocation ColonLoc,
1853 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001854 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001855 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001856 ASLoc, ColonLoc);
1857 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001858 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001859}
1860
Richard Smith18f07db2012-08-06 03:25:17 +00001861/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001862void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00001863 if (D->isInvalidDecl())
1864 return;
1865
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001866 // We only care about "override" and "final" declarations.
1867 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1868 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00001869
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001870 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001871
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001872 // We can't check dependent instance methods.
1873 if (MD && MD->isInstance() &&
1874 (MD->getParent()->hasAnyDependentBases() ||
1875 MD->getType()->isDependentType()))
1876 return;
1877
1878 if (MD && !MD->isVirtual()) {
1879 // If we have a non-virtual method, check if if hides a virtual method.
1880 // (In that case, it's most likely the method has the wrong type.)
1881 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1882 FindHiddenVirtualMethods(MD, OverloadedMethods);
1883
1884 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001885 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1886 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001887 diag::override_keyword_hides_virtual_member_function)
1888 << "override" << (OverloadedMethods.size() > 1);
1889 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001890 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001891 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00001892 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1893 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00001894 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001895 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1896 MD->setInvalidDecl();
1897 return;
1898 }
1899 // Fall through into the general case diagnostic.
1900 // FIXME: We might want to attempt typo correction here.
1901 }
1902
1903 if (!MD || !MD->isVirtual()) {
1904 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1905 Diag(OA->getLocation(),
1906 diag::override_keyword_only_allowed_on_virtual_member_functions)
1907 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1908 D->dropAttr<OverrideAttr>();
1909 }
1910 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1911 Diag(FA->getLocation(),
1912 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00001913 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1914 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001915 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00001916 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001917 return;
1918 }
Richard Smith18f07db2012-08-06 03:25:17 +00001919
Richard Smith18f07db2012-08-06 03:25:17 +00001920 // C++11 [class.virtual]p5:
David Blaikie1cbb9712014-11-14 19:09:44 +00001921 // If a function is marked with the virt-specifier override and
Richard Smith18f07db2012-08-06 03:25:17 +00001922 // does not override a member function of a base class, the program is
1923 // ill-formed.
1924 bool HasOverriddenMethods =
1925 MD->begin_overridden_methods() != MD->end_overridden_methods();
1926 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1927 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1928 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00001929}
1930
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00001931void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
1932 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
1933 return;
1934 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1935 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
1936 isa<CXXDestructorDecl>(MD))
1937 return;
1938
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00001939 SourceLocation Loc = MD->getLocation();
1940 SourceLocation SpellingLoc = Loc;
1941 if (getSourceManager().isMacroArgExpansion(Loc))
1942 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
1943 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
1944 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
Fariborz Jahanian6e213382014-10-31 19:56:27 +00001945 return;
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00001946
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00001947 if (MD->size_overridden_methods() > 0) {
1948 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
1949 << MD->getDeclName();
1950 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
1951 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
1952 }
1953}
1954
Richard Smith18f07db2012-08-06 03:25:17 +00001955/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00001956/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00001957/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00001958bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1959 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00001960 FinalAttr *FA = Old->getAttr<FinalAttr>();
1961 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00001962 return false;
1963
1964 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00001965 << New->getDeclName()
1966 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00001967 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1968 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001969}
1970
Daniel Jasper0baec5492012-06-06 08:32:04 +00001971static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00001972 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1973 // FIXME: Destruction of ObjC lifetime types has side-effects.
1974 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1975 return !RD->isCompleteDefinition() ||
1976 !RD->hasTrivialDefaultConstructor() ||
1977 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00001978 return false;
1979}
1980
John McCall5e77d762013-04-16 07:28:30 +00001981static AttributeList *getMSPropertyAttr(AttributeList *list) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001982 for (AttributeList *it = list; it != nullptr; it = it->getNext())
John McCall5e77d762013-04-16 07:28:30 +00001983 if (it->isDeclspecPropertyAttribute())
1984 return it;
Craig Topperc3ec1492014-05-26 06:22:03 +00001985 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +00001986}
1987
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001988/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1989/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001990/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00001991/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1992/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001993NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001994Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001995 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001996 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00001997 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001998 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001999 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2000 DeclarationName Name = NameInfo.getName();
2001 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00002002
2003 // For anonymous bitfields, the location should point to the type.
2004 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002005 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00002006
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002007 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002008
John McCallb1cd7da2010-06-04 08:34:12 +00002009 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00002010 assert(!DS.isFriendSpecified());
2011
Richard Smithcfcdf3a2011-06-25 02:28:38 +00002012 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00002013
John McCalldb632ac2012-09-25 07:32:39 +00002014 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2015 // The Microsoft extension __interface only permits public member functions
2016 // and prohibits constructors, destructors, operators, non-public member
2017 // functions, static methods and data members.
2018 unsigned InvalidDecl;
2019 bool ShowDeclName = true;
2020 if (!isFunc)
2021 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2022 else if (AS != AS_public)
2023 InvalidDecl = 2;
2024 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2025 InvalidDecl = 3;
2026 else switch (Name.getNameKind()) {
2027 case DeclarationName::CXXConstructorName:
2028 InvalidDecl = 4;
2029 ShowDeclName = false;
2030 break;
2031
2032 case DeclarationName::CXXDestructorName:
2033 InvalidDecl = 5;
2034 ShowDeclName = false;
2035 break;
2036
2037 case DeclarationName::CXXOperatorName:
2038 case DeclarationName::CXXConversionFunctionName:
2039 InvalidDecl = 6;
2040 break;
2041
2042 default:
2043 InvalidDecl = 0;
2044 break;
2045 }
2046
2047 if (InvalidDecl) {
2048 if (ShowDeclName)
2049 Diag(Loc, diag::err_invalid_member_in_interface)
2050 << (InvalidDecl-1) << Name;
2051 else
2052 Diag(Loc, diag::err_invalid_member_in_interface)
2053 << (InvalidDecl-1) << "";
Craig Topperc3ec1492014-05-26 06:22:03 +00002054 return nullptr;
John McCalldb632ac2012-09-25 07:32:39 +00002055 }
2056 }
2057
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002058 // C++ 9.2p6: A member shall not be declared to have automatic storage
2059 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002060 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2061 // data members and cannot be applied to names declared const or static,
2062 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002063 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00002064 case DeclSpec::SCS_unspecified:
2065 case DeclSpec::SCS_typedef:
2066 case DeclSpec::SCS_static:
2067 break;
2068 case DeclSpec::SCS_mutable:
2069 if (isFunc) {
2070 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00002071
Richard Smithb4a9e862013-04-12 22:46:28 +00002072 // FIXME: It would be nicer if the keyword was ignored only for this
2073 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002074 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00002075 }
2076 break;
2077 default:
2078 Diag(DS.getStorageClassSpecLoc(),
2079 diag::err_storageclass_invalid_for_member);
2080 D.getMutableDeclSpec().ClearStorageClassSpecs();
2081 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002082 }
2083
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002084 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2085 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00002086 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002087
David Blaikie35506f82013-01-30 01:22:18 +00002088 if (DS.isConstexprSpecified() && isInstField) {
2089 SemaDiagnosticBuilder B =
2090 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2091 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2092 if (InitStyle == ICIS_NoInit) {
Richard Smith82dce552014-04-14 21:00:40 +00002093 B << 0 << 0;
2094 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2095 B << FixItHint::CreateRemoval(ConstexprLoc);
2096 else {
2097 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2098 D.getMutableDeclSpec().ClearConstexprSpec();
2099 const char *PrevSpec;
2100 unsigned DiagID;
2101 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2102 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2103 (void)Failed;
2104 assert(!Failed && "Making a constexpr member const shouldn't fail");
2105 }
David Blaikie35506f82013-01-30 01:22:18 +00002106 } else {
2107 B << 1;
2108 const char *PrevSpec;
2109 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00002110 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002111 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2112 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00002113 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00002114 "This is the only DeclSpec that should fail to be applied");
2115 B << 1;
2116 } else {
2117 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2118 isInstField = false;
2119 }
2120 }
2121 }
2122
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002123 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00002124 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00002125 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002126
2127 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00002128 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002129 Diag(Loc, diag::err_bad_variable_name)
2130 << Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002131 return nullptr;
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002132 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002133
Benjamin Kramer365082d2012-05-19 16:34:46 +00002134 IdentifierInfo *II = Name.getAsIdentifierInfo();
2135
Douglas Gregor7c26c042011-09-21 14:40:46 +00002136 // Member field could not be with "template" keyword.
2137 // So TemplateParameterLists should be empty in this case.
2138 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002139 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002140 if (TemplateParams->size()) {
2141 // There is no such thing as a member field template.
2142 Diag(D.getIdentifierLoc(), diag::err_template_member)
2143 << II
2144 << SourceRange(TemplateParams->getTemplateLoc(),
2145 TemplateParams->getRAngleLoc());
2146 } else {
2147 // There is an extraneous 'template<>' for this member.
2148 Diag(TemplateParams->getTemplateLoc(),
2149 diag::err_template_member_noparams)
2150 << II
2151 << SourceRange(TemplateParams->getTemplateLoc(),
2152 TemplateParams->getRAngleLoc());
2153 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002154 return nullptr;
Douglas Gregor7c26c042011-09-21 14:40:46 +00002155 }
2156
Douglas Gregora007d362010-10-13 22:19:53 +00002157 if (SS.isSet() && !SS.isInvalid()) {
2158 // The user provided a superfluous scope specifier inside a class
2159 // definition:
2160 //
2161 // class X {
2162 // int X::member;
2163 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002164 if (DeclContext *DC = computeDeclContext(SS, false))
2165 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002166 else
2167 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2168 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002169
Douglas Gregora007d362010-10-13 22:19:53 +00002170 SS.clear();
2171 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002172
John McCall5e77d762013-04-16 07:28:30 +00002173 AttributeList *MSPropertyAttr =
2174 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002175 if (MSPropertyAttr) {
2176 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2177 BitWidth, InitStyle, AS, MSPropertyAttr);
2178 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002179 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002180 isInstField = false;
2181 } else {
2182 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2183 BitWidth, InitStyle, AS);
2184 assert(Member && "HandleField never returns null");
2185 }
2186 } else {
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002187 Member = HandleDeclarator(S, D, TemplateParameterLists);
2188 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002189 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002190
2191 // Non-instance-fields can't have a bitfield.
2192 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002193 if (Member->isInvalidDecl()) {
2194 // don't emit another diagnostic.
David Majnemer380443a2014-12-28 22:51:45 +00002195 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002196 // C++ 9.6p3: A bit-field shall not be a static member.
2197 // "static member 'A' cannot be a bit-field"
2198 Diag(Loc, diag::err_static_not_bitfield)
2199 << Name << BitWidth->getSourceRange();
2200 } else if (isa<TypedefDecl>(Member)) {
2201 // "typedef member 'x' cannot be a bit-field"
2202 Diag(Loc, diag::err_typedef_not_bitfield)
2203 << Name << BitWidth->getSourceRange();
2204 } else {
2205 // A function typedef ("typedef int f(); f a;").
2206 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2207 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002208 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002209 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002210 }
Mike Stump11289f42009-09-09 15:08:12 +00002211
Craig Topperc3ec1492014-05-26 06:22:03 +00002212 BitWidth = nullptr;
Chris Lattnerd26760a2009-03-05 23:01:03 +00002213 Member->setInvalidDecl();
2214 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002215
2216 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002217
Larisse Voufo39a1e502013-08-06 01:03:05 +00002218 // If we have declared a member function template or static data member
2219 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002220 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2221 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002222 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2223 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00002224 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002225
Richard Smith18f07db2012-08-06 03:25:17 +00002226 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00002227 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00002228 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00002229 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2230 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00002231
Douglas Gregorf2f08062011-03-08 17:10:18 +00002232 if (VS.getLastLocation().isValid()) {
2233 // Update the end location of a method that has a virt-specifiers.
2234 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2235 MD->setRangeEnd(VS.getLastLocation());
2236 }
Richard Smith18f07db2012-08-06 03:25:17 +00002237
Anders Carlssonc87f8612011-01-20 06:29:02 +00002238 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00002239
Douglas Gregor92751d42008-11-17 22:58:34 +00002240 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002241
Daniel Jasper0baec5492012-06-06 08:32:04 +00002242 if (isInstField) {
2243 FieldDecl *FD = cast<FieldDecl>(Member);
2244 FieldCollector->Add(FD);
2245
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002246 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
Daniel Jasper0baec5492012-06-06 08:32:04 +00002247 // Remember all explicit private FieldDecls that have a name, no side
2248 // effects and are not part of a dependent type declaration.
2249 if (!FD->isImplicit() && FD->getDeclName() &&
2250 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00002251 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00002252 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00002253 !InitializationHasSideEffects(*FD))
2254 UnusedPrivateFields.insert(FD);
2255 }
2256 }
2257
John McCall48871652010-08-21 09:40:31 +00002258 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002259}
2260
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002261namespace {
2262 class UninitializedFieldVisitor
2263 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2264 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00002265 // List of Decls to generate a warning on. Also remove Decls that become
2266 // initialized.
Craig Topper4dd9b432014-08-17 23:49:53 +00002267 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
Richard Trieu3630c392014-11-21 03:10:30 +00002268 // List of base classes of the record. Classes are removed after their
2269 // initializers.
2270 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
Richard Trieu8d08a272014-08-28 03:23:47 +00002271 // Vector of decls to be removed from the Decl set prior to visiting the
2272 // nodes. These Decls may have been initialized in the prior initializer.
2273 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
Richard Trieu406e65c2013-09-20 03:03:06 +00002274 // If non-null, add a note to the warning pointing back to the constructor.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00002275 const CXXConstructorDecl *Constructor;
Nick Lewycky314a4492014-10-17 22:45:44 +00002276 // Variables to hold state when processing an initializer list. When
Richard Trieufa1d0a72014-10-17 20:56:10 +00002277 // InitList is true, special case initialization of FieldDecls matching
2278 // InitListFieldDecl.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00002279 bool InitList;
2280 FieldDecl *InitListFieldDecl;
Richard Trieufa1d0a72014-10-17 20:56:10 +00002281 llvm::SmallVector<unsigned, 4> InitFieldIndex;
2282
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002283 public:
2284 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00002285 UninitializedFieldVisitor(Sema &S,
Richard Trieu3630c392014-11-21 03:10:30 +00002286 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
2287 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
2288 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
2289 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002290
Richard Trieufa1d0a72014-10-17 20:56:10 +00002291 // Returns true if the use of ME is not an uninitialized use.
2292 bool IsInitListMemberExprInitialized(MemberExpr *ME,
2293 bool CheckReferenceOnly) {
2294 llvm::SmallVector<FieldDecl*, 4> Fields;
2295 bool ReferenceField = false;
2296 while (ME) {
2297 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
2298 if (!FD)
2299 return false;
2300 Fields.push_back(FD);
2301 if (FD->getType()->isReferenceType())
2302 ReferenceField = true;
2303 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
2304 }
2305
2306 // Binding a reference to an unintialized field is not an
2307 // uninitialized use.
2308 if (CheckReferenceOnly && !ReferenceField)
2309 return true;
2310
2311 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
2312 // Discard the first field since it is the field decl that is being
2313 // initialized.
2314 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
2315 UsedFieldIndex.push_back((*I)->getFieldIndex());
2316 }
2317
2318 for (auto UsedIter = UsedFieldIndex.begin(),
2319 UsedEnd = UsedFieldIndex.end(),
2320 OrigIter = InitFieldIndex.begin(),
2321 OrigEnd = InitFieldIndex.end();
2322 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
2323 if (*UsedIter < *OrigIter)
2324 return true;
2325 if (*UsedIter > *OrigIter)
2326 break;
2327 }
2328
2329 return false;
2330 }
2331
Richard Trieu2d779b92014-10-01 03:44:58 +00002332 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
2333 bool AddressOf) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002334 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2335 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002336
Richard Trieu1bc22c12013-09-13 03:20:53 +00002337 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2338 // or union.
2339 MemberExpr *FieldME = ME;
2340
Richard Trieu2d779b92014-10-01 03:44:58 +00002341 bool AllPODFields = FieldME->getType().isPODType(S.Context);
2342
Richard Trieu1bc22c12013-09-13 03:20:53 +00002343 Expr *Base = ME;
Richard Trieu3630c392014-11-21 03:10:30 +00002344 while (MemberExpr *SubME =
2345 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002346
Richard Trieufa1d0a72014-10-17 20:56:10 +00002347 if (isa<VarDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00002348 return;
2349
Richard Trieufa1d0a72014-10-17 20:56:10 +00002350 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00002351 if (!FD->isAnonymousStructOrUnion())
Richard Trieufa1d0a72014-10-17 20:56:10 +00002352 FieldME = SubME;
Richard Trieu1bc22c12013-09-13 03:20:53 +00002353
Richard Trieu2d779b92014-10-01 03:44:58 +00002354 if (!FieldME->getType().isPODType(S.Context))
2355 AllPODFields = false;
2356
Richard Trieu3630c392014-11-21 03:10:30 +00002357 Base = SubME->getBase();
Richard Trieu1bc22c12013-09-13 03:20:53 +00002358 }
2359
Richard Trieu3630c392014-11-21 03:10:30 +00002360 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
Richard Trieufd687772013-09-16 20:46:50 +00002361 return;
2362
Richard Trieu2d779b92014-10-01 03:44:58 +00002363 if (AddressOf && AllPODFields)
2364 return;
2365
Richard Trieu406e65c2013-09-20 03:03:06 +00002366 ValueDecl* FoundVD = FieldME->getMemberDecl();
2367
Richard Trieu3630c392014-11-21 03:10:30 +00002368 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
2369 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
2370 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
2371 }
2372
2373 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
2374 QualType T = BaseCast->getType();
2375 if (T->isPointerType() &&
2376 BaseClasses.count(T->getPointeeType())) {
2377 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
2378 << T->getPointeeType() << FoundVD;
2379 }
2380 }
2381 }
2382
Richard Trieuef64e942013-10-25 00:56:00 +00002383 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00002384 return;
2385
Richard Trieuef64e942013-10-25 00:56:00 +00002386 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00002387
Richard Trieufa1d0a72014-10-17 20:56:10 +00002388 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
2389 // Special checking for initializer lists.
2390 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
2391 return;
2392 }
2393 } else {
2394 // Prevent double warnings on use of unbounded references.
2395 if (CheckReferenceOnly && !IsReference)
2396 return;
2397 }
Richard Trieuef64e942013-10-25 00:56:00 +00002398
2399 unsigned diag = IsReference
2400 ? diag::warn_reference_field_is_uninit
2401 : diag::warn_field_is_uninit;
2402 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2403 if (Constructor)
2404 S.Diag(Constructor->getLocation(),
2405 diag::note_uninit_in_this_constructor)
2406 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2407
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002408 }
2409
Richard Trieu2d779b92014-10-01 03:44:58 +00002410 void HandleValue(Expr *E, bool AddressOf) {
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002411 E = E->IgnoreParens();
2412
2413 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002414 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
2415 AddressOf /*AddressOf*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002416 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002417 }
2418
2419 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002420 Visit(CO->getCond());
2421 HandleValue(CO->getTrueExpr(), AddressOf);
2422 HandleValue(CO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002423 return;
2424 }
2425
2426 if (BinaryConditionalOperator *BCO =
2427 dyn_cast<BinaryConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002428 Visit(BCO->getCond());
2429 HandleValue(BCO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002430 return;
2431 }
2432
Richard Trieuabf6ec42014-08-27 22:15:10 +00002433 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002434 HandleValue(OVE->getSourceExpr(), AddressOf);
Richard Trieuabf6ec42014-08-27 22:15:10 +00002435 return;
2436 }
2437
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002438 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2439 switch (BO->getOpcode()) {
2440 default:
Richard Trieu2d779b92014-10-01 03:44:58 +00002441 break;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002442 case(BO_PtrMemD):
2443 case(BO_PtrMemI):
Richard Trieu2d779b92014-10-01 03:44:58 +00002444 HandleValue(BO->getLHS(), AddressOf);
2445 Visit(BO->getRHS());
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002446 return;
2447 case(BO_Comma):
Richard Trieu2d779b92014-10-01 03:44:58 +00002448 Visit(BO->getLHS());
2449 HandleValue(BO->getRHS(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002450 return;
2451 }
2452 }
Richard Trieu2d779b92014-10-01 03:44:58 +00002453
2454 Visit(E);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002455 }
2456
Richard Trieufa1d0a72014-10-17 20:56:10 +00002457 void CheckInitListExpr(InitListExpr *ILE) {
2458 InitFieldIndex.push_back(0);
2459 for (auto Child : ILE->children()) {
2460 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
2461 CheckInitListExpr(SubList);
2462 } else {
2463 Visit(Child);
2464 }
2465 ++InitFieldIndex.back();
2466 }
2467 InitFieldIndex.pop_back();
2468 }
2469
Richard Trieu8d08a272014-08-28 03:23:47 +00002470 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
Richard Trieu3630c392014-11-21 03:10:30 +00002471 FieldDecl *Field, const Type *BaseClass) {
Richard Trieu8d08a272014-08-28 03:23:47 +00002472 // Remove Decls that may have been initialized in the previous
2473 // initializer.
2474 for (ValueDecl* VD : DeclsToRemove)
2475 Decls.erase(VD);
Richard Trieu8d08a272014-08-28 03:23:47 +00002476 DeclsToRemove.clear();
Richard Trieufa1d0a72014-10-17 20:56:10 +00002477
Richard Trieu8d08a272014-08-28 03:23:47 +00002478 Constructor = FieldConstructor;
Richard Trieufa1d0a72014-10-17 20:56:10 +00002479 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
2480
2481 if (ILE && Field) {
2482 InitList = true;
2483 InitListFieldDecl = Field;
2484 InitFieldIndex.clear();
2485 CheckInitListExpr(ILE);
2486 } else {
2487 InitList = false;
2488 Visit(E);
2489 }
2490
Richard Trieu8d08a272014-08-28 03:23:47 +00002491 if (Field)
2492 Decls.erase(Field);
Richard Trieu3630c392014-11-21 03:10:30 +00002493 if (BaseClass)
2494 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
Richard Trieu8d08a272014-08-28 03:23:47 +00002495 }
2496
Richard Trieu1bc22c12013-09-13 03:20:53 +00002497 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00002498 // All uses of unbounded reference fields will warn.
Richard Trieu2d779b92014-10-01 03:44:58 +00002499 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002500 }
2501
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002502 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002503 if (E->getCastKind() == CK_LValueToRValue) {
2504 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2505 return;
2506 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002507
2508 Inherited::VisitImplicitCastExpr(E);
2509 }
2510
Richard Trieu1bc22c12013-09-13 03:20:53 +00002511 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu4834ad22014-08-12 21:05:04 +00002512 if (E->getConstructor()->isCopyConstructor()) {
2513 Expr *ArgExpr = E->getArg(0);
Richard Trieu2d779b92014-10-01 03:44:58 +00002514 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
2515 if (ILE->getNumInits() == 1)
2516 ArgExpr = ILE->getInit(0);
2517 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
2518 if (ICE->getCastKind() == CK_NoOp)
Richard Trieu4834ad22014-08-12 21:05:04 +00002519 ArgExpr = ICE->getSubExpr();
Richard Trieu2d779b92014-10-01 03:44:58 +00002520 HandleValue(ArgExpr, false /*AddressOf*/);
2521 return;
Richard Trieu4834ad22014-08-12 21:05:04 +00002522 }
Richard Trieu1bc22c12013-09-13 03:20:53 +00002523 Inherited::VisitCXXConstructExpr(E);
2524 }
2525
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002526 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2527 Expr *Callee = E->getCallee();
Richard Trieu2d779b92014-10-01 03:44:58 +00002528 if (isa<MemberExpr>(Callee)) {
2529 HandleValue(Callee, false /*AddressOf*/);
Richard Trieu46847422014-11-01 00:46:54 +00002530 for (auto Arg : E->arguments())
2531 Visit(Arg);
Richard Trieu2d779b92014-10-01 03:44:58 +00002532 return;
2533 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002534
2535 Inherited::VisitCXXMemberCallExpr(E);
2536 }
Richard Trieu406e65c2013-09-20 03:03:06 +00002537
Richard Trieu11fd0792014-08-26 04:30:55 +00002538 void VisitCallExpr(CallExpr *E) {
2539 // Treat std::move as a use.
2540 if (E->getNumArgs() == 1) {
2541 if (FunctionDecl *FD = E->getDirectCallee()) {
Richard Trieuc321b932014-11-27 01:29:32 +00002542 if (FD->isInStdNamespace() && FD->getIdentifier() &&
2543 FD->getIdentifier()->isStr("move")) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002544 HandleValue(E->getArg(0), false /*AddressOf*/);
2545 return;
Richard Trieu11fd0792014-08-26 04:30:55 +00002546 }
2547 }
2548 }
2549
2550 Inherited::VisitCallExpr(E);
2551 }
2552
Richard Trieud4a01362014-10-31 21:10:22 +00002553 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
2554 Expr *Callee = E->getCallee();
2555
2556 if (isa<UnresolvedLookupExpr>(Callee))
2557 return Inherited::VisitCXXOperatorCallExpr(E);
2558
2559 Visit(Callee);
2560 for (auto Arg : E->arguments())
2561 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
2562 }
2563
Richard Trieu406e65c2013-09-20 03:03:06 +00002564 void VisitBinaryOperator(BinaryOperator *E) {
2565 // If a field assignment is detected, remove the field from the
2566 // uninitiailized field set.
2567 if (E->getOpcode() == BO_Assign)
2568 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2569 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00002570 if (!FD->getType()->isReferenceType())
Richard Trieu8d08a272014-08-28 03:23:47 +00002571 DeclsToRemove.push_back(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00002572
Richard Trieu52b8b602014-09-25 01:15:40 +00002573 if (E->isCompoundAssignmentOp()) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002574 HandleValue(E->getLHS(), false /*AddressOf*/);
2575 Visit(E->getRHS());
2576 return;
Richard Trieu52b8b602014-09-25 01:15:40 +00002577 }
2578
Richard Trieu406e65c2013-09-20 03:03:06 +00002579 Inherited::VisitBinaryOperator(E);
2580 }
Richard Trieu52b8b602014-09-25 01:15:40 +00002581
2582 void VisitUnaryOperator(UnaryOperator *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002583 if (E->isIncrementDecrementOp()) {
2584 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2585 return;
2586 }
2587 if (E->getOpcode() == UO_AddrOf) {
2588 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
2589 HandleValue(ME->getBase(), true /*AddressOf*/);
2590 return;
2591 }
2592 }
Richard Trieu52b8b602014-09-25 01:15:40 +00002593
2594 Inherited::VisitUnaryOperator(E);
2595 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002596 };
Richard Trieuef64e942013-10-25 00:56:00 +00002597
2598 // Diagnose value-uses of fields to initialize themselves, e.g.
2599 // foo(foo)
2600 // where foo is not also a parameter to the constructor.
2601 // Also diagnose across field uninitialized use such as
2602 // x(y), y(x)
2603 // TODO: implement -Wuninitialized and fold this into that framework.
2604 static void DiagnoseUninitializedFields(
2605 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2606
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002607 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2608 Constructor->getLocation())) {
Richard Trieuef64e942013-10-25 00:56:00 +00002609 return;
2610 }
2611
2612 if (Constructor->isInvalidDecl())
2613 return;
2614
2615 const CXXRecordDecl *RD = Constructor->getParent();
2616
Richard Trieu353a4b42014-10-22 05:21:59 +00002617 if (RD->getDescribedClassTemplate())
Richard Trieu277ace02014-10-22 02:52:00 +00002618 return;
2619
Richard Trieuef64e942013-10-25 00:56:00 +00002620 // Holds fields that are uninitialized.
2621 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2622
2623 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00002624 for (auto *I : RD->decls()) {
2625 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002626 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00002627 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002628 UninitializedFields.insert(IFD->getAnonField());
2629 }
2630 }
2631
Richard Trieu3630c392014-11-21 03:10:30 +00002632 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
2633 for (auto I : RD->bases())
2634 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
2635
2636 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00002637 return;
2638
2639 UninitializedFieldVisitor UninitializedChecker(SemaRef,
Richard Trieu3630c392014-11-21 03:10:30 +00002640 UninitializedFields,
2641 UninitializedBaseClasses);
Richard Trieu8d08a272014-08-28 03:23:47 +00002642
Aaron Ballman0ad78302014-03-13 17:34:31 +00002643 for (const auto *FieldInit : Constructor->inits()) {
Richard Trieu3630c392014-11-21 03:10:30 +00002644 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00002645 break;
2646
Aaron Ballman0ad78302014-03-13 17:34:31 +00002647 Expr *InitExpr = FieldInit->getInit();
Richard Trieu8d08a272014-08-28 03:23:47 +00002648 if (!InitExpr)
2649 continue;
Richard Trieuef64e942013-10-25 00:56:00 +00002650
Richard Trieu8d08a272014-08-28 03:23:47 +00002651 if (CXXDefaultInitExpr *Default =
2652 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
2653 InitExpr = Default->getExpr();
2654 if (!InitExpr)
2655 continue;
2656 // In class initializers will point to the constructor.
2657 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
Richard Trieu3630c392014-11-21 03:10:30 +00002658 FieldInit->getAnyMember(),
2659 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00002660 } else {
2661 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
Richard Trieu3630c392014-11-21 03:10:30 +00002662 FieldInit->getAnyMember(),
2663 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00002664 }
Richard Trieuef64e942013-10-25 00:56:00 +00002665 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002666 }
2667} // namespace
2668
Richard Smith74108172014-01-17 03:11:34 +00002669/// \brief Enter a new C++ default initializer scope. After calling this, the
2670/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2671/// parsing or instantiating the initializer failed.
2672void Sema::ActOnStartCXXInClassMemberInitializer() {
2673 // Create a synthetic function scope to represent the call to the constructor
2674 // that notionally surrounds a use of this initializer.
2675 PushFunctionScope();
2676}
2677
2678/// \brief This is invoked after parsing an in-class initializer for a
2679/// non-static C++ class member, and after instantiating an in-class initializer
2680/// in a class template. Such actions are deferred until the class is complete.
2681void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2682 SourceLocation InitLoc,
2683 Expr *InitExpr) {
2684 // Pop the notional constructor scope we created earlier.
Craig Topperc3ec1492014-05-26 06:22:03 +00002685 PopFunctionScopeInfo(nullptr, D);
Richard Smith74108172014-01-17 03:11:34 +00002686
David Majnemer87ff66c2014-12-13 11:34:16 +00002687 FieldDecl *FD = dyn_cast<FieldDecl>(D);
2688 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
Richard Smith2b013182012-06-10 03:12:00 +00002689 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00002690
2691 if (!InitExpr) {
David Majnemer87ff66c2014-12-13 11:34:16 +00002692 D->setInvalidDecl();
2693 if (FD)
2694 FD->removeInClassInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00002695 return;
2696 }
2697
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002698 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2699 FD->setInvalidDecl();
2700 FD->removeInClassInitializer();
2701 return;
2702 }
2703
Richard Smith938f40b2011-06-11 17:19:42 +00002704 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00002705 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002706 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00002707 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00002708 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00002709 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002710 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2711 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00002712 if (Init.isInvalid()) {
2713 FD->setInvalidDecl();
2714 return;
2715 }
Richard Smith938f40b2011-06-11 17:19:42 +00002716 }
2717
Richard Smith945f8d32013-01-14 22:39:08 +00002718 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00002719 // The initialization of each base and member constitutes a
2720 // full-expression.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002721 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00002722 if (Init.isInvalid()) {
2723 FD->setInvalidDecl();
2724 return;
2725 }
2726
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002727 InitExpr = Init.get();
Richard Smith938f40b2011-06-11 17:19:42 +00002728
2729 FD->setInClassInitializer(InitExpr);
2730}
2731
Douglas Gregor15e77a22009-12-31 09:10:24 +00002732/// \brief Find the direct and/or virtual base specifiers that
2733/// correspond to the given base type, for use in base initialization
2734/// within a constructor.
2735static bool FindBaseInitializer(Sema &SemaRef,
2736 CXXRecordDecl *ClassDecl,
2737 QualType BaseType,
2738 const CXXBaseSpecifier *&DirectBaseSpec,
2739 const CXXBaseSpecifier *&VirtualBaseSpec) {
2740 // First, check for a direct base class.
Craig Topperc3ec1492014-05-26 06:22:03 +00002741 DirectBaseSpec = nullptr;
Aaron Ballman574705e2014-03-13 15:41:46 +00002742 for (const auto &Base : ClassDecl->bases()) {
2743 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002744 // We found a direct base of this type. That's what we're
2745 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00002746 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002747 break;
2748 }
2749 }
2750
2751 // Check for a virtual base class.
2752 // FIXME: We might be able to short-circuit this if we know in advance that
2753 // there are no virtual bases.
Craig Topperc3ec1492014-05-26 06:22:03 +00002754 VirtualBaseSpec = nullptr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002755 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2756 // We haven't found a base yet; search the class hierarchy for a
2757 // virtual base class.
2758 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2759 /*DetectVirtual=*/false);
2760 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2761 BaseType, Paths)) {
2762 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2763 Path != Paths.end(); ++Path) {
2764 if (Path->back().Base->isVirtual()) {
2765 VirtualBaseSpec = Path->back().Base;
2766 break;
2767 }
2768 }
2769 }
2770 }
2771
2772 return DirectBaseSpec || VirtualBaseSpec;
2773}
2774
Sebastian Redla74948d2011-09-24 17:48:25 +00002775/// \brief Handle a C++ member initializer using braced-init-list syntax.
2776MemInitResult
2777Sema::ActOnMemInitializer(Decl *ConstructorD,
2778 Scope *S,
2779 CXXScopeSpec &SS,
2780 IdentifierInfo *MemberOrBase,
2781 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002782 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002783 SourceLocation IdLoc,
2784 Expr *InitList,
2785 SourceLocation EllipsisLoc) {
2786 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002787 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00002788 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002789}
2790
2791/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00002792MemInitResult
John McCall48871652010-08-21 09:40:31 +00002793Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00002794 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002795 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002796 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00002797 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002798 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002799 SourceLocation IdLoc,
2800 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002801 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002802 SourceLocation RParenLoc,
2803 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00002804 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002805 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002806 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002807 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002808}
2809
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002810namespace {
2811
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00002812// Callback to only accept typo corrections that can be a valid C++ member
2813// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002814class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002815public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002816 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2817 : ClassDecl(ClassDecl) {}
2818
Craig Toppera798a9d2014-03-02 09:32:10 +00002819 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002820 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2821 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2822 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002823 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002824 }
2825 return false;
2826 }
2827
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002828private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002829 CXXRecordDecl *ClassDecl;
2830};
2831
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002832}
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002833
Sebastian Redla74948d2011-09-24 17:48:25 +00002834/// \brief Handle a C++ member initializer.
2835MemInitResult
2836Sema::BuildMemInitializer(Decl *ConstructorD,
2837 Scope *S,
2838 CXXScopeSpec &SS,
2839 IdentifierInfo *MemberOrBase,
2840 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002841 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002842 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00002843 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002844 SourceLocation EllipsisLoc) {
Kaelyn Takataa15a6dc2014-12-08 22:41:42 +00002845 ExprResult Res = CorrectDelayedTyposInExpr(Init);
2846 if (!Res.isUsable())
2847 return true;
2848 Init = Res.get();
2849
Douglas Gregor71a57182009-06-22 23:20:33 +00002850 if (!ConstructorD)
2851 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002852
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002853 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00002854
2855 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002856 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00002857 if (!Constructor) {
2858 // The user wrote a constructor initializer on a function that is
2859 // not a C++ constructor. Ignore the error for now, because we may
2860 // have more member initializers coming; we'll diagnose it just
2861 // once in ActOnMemInitializers.
2862 return true;
2863 }
2864
2865 CXXRecordDecl *ClassDecl = Constructor->getParent();
2866
2867 // C++ [class.base.init]p2:
2868 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00002869 // constructor's class and, if not found in that scope, are looked
2870 // up in the scope containing the constructor's definition.
2871 // [Note: if the constructor's class contains a member with the
2872 // same name as a direct or virtual base class of the class, a
2873 // mem-initializer-id naming the member or base class and composed
2874 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00002875 // mem-initializer-id for the hidden base class may be specified
2876 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00002877 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002878 // Look for a member, first.
Nico Weberaa0117c2014-11-12 03:44:43 +00002879 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00002880 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00002881 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00002882 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2883 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00002884 if (EllipsisLoc.isValid())
2885 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00002886 << MemberOrBase
2887 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002888
Sebastian Redla9351792012-02-11 23:51:47 +00002889 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00002890 }
Francois Pichetd583da02010-12-04 09:14:42 +00002891 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002892 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002893 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002894 QualType BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002895 TypeSourceInfo *TInfo = nullptr;
John McCallb5a0d312009-12-21 10:41:20 +00002896
2897 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00002898 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00002899 } else if (DS.getTypeSpecType() == TST_decltype) {
2900 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00002901 } else {
2902 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2903 LookupParsedName(R, S, &SS);
2904
2905 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2906 if (!TyD) {
2907 if (R.isAmbiguous()) return true;
2908
John McCallda6841b2010-04-09 19:01:14 +00002909 // We don't want access-control diagnostics here.
2910 R.suppressDiagnostics();
2911
Douglas Gregora3b624a2010-01-19 06:46:48 +00002912 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2913 bool NotUnknownSpecialization = false;
2914 DeclContext *DC = computeDeclContext(SS, false);
2915 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2916 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2917
2918 if (!NotUnknownSpecialization) {
2919 // When the scope specifier can refer to a member of an unknown
2920 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00002921 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2922 SS.getWithLocInContext(Context),
2923 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00002924 if (BaseType.isNull())
2925 return true;
2926
Douglas Gregora3b624a2010-01-19 06:46:48 +00002927 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002928 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002929 }
2930 }
2931
Douglas Gregor15e77a22009-12-31 09:10:24 +00002932 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002933 TypoCorrection Corr;
Douglas Gregora3b624a2010-01-19 06:46:48 +00002934 if (R.empty() && BaseType.isNull() &&
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002935 (Corr = CorrectTypo(
2936 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2937 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
2938 CTK_ErrorRecovery, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002939 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002940 // We have found a non-static data member with a similar
2941 // name to what was typed; complain and initialize that
2942 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00002943 diagnoseTypo(Corr,
2944 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2945 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00002946 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002947 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002948 const CXXBaseSpecifier *DirectBaseSpec;
2949 const CXXBaseSpecifier *VirtualBaseSpec;
2950 if (FindBaseInitializer(*this, ClassDecl,
2951 Context.getTypeDeclType(Type),
2952 DirectBaseSpec, VirtualBaseSpec)) {
2953 // We have found a direct or virtual base class with a
2954 // similar name to what was typed; complain and initialize
2955 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00002956 diagnoseTypo(Corr,
2957 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2958 << MemberOrBase << false,
2959 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00002960
Richard Smithf9b15102013-08-17 00:46:16 +00002961 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2962 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002963 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00002964 diag::note_base_class_specified_here)
2965 << BaseSpec->getType()
2966 << BaseSpec->getSourceRange();
2967
Douglas Gregor15e77a22009-12-31 09:10:24 +00002968 TyD = Type;
2969 }
2970 }
2971 }
2972
Douglas Gregora3b624a2010-01-19 06:46:48 +00002973 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002974 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00002975 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00002976 return true;
2977 }
John McCallb5a0d312009-12-21 10:41:20 +00002978 }
2979
Douglas Gregora3b624a2010-01-19 06:46:48 +00002980 if (BaseType.isNull()) {
2981 BaseType = Context.getTypeDeclType(TyD);
Nico Weber28309182014-11-12 03:52:25 +00002982 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
Aaron Ballman4a979672014-01-03 13:56:08 +00002983 if (SS.isSet())
Douglas Gregora3b624a2010-01-19 06:46:48 +00002984 // FIXME: preserve source range information
Aaron Ballman4a979672014-01-03 13:56:08 +00002985 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2986 BaseType);
John McCallb5a0d312009-12-21 10:41:20 +00002987 }
2988 }
Mike Stump11289f42009-09-09 15:08:12 +00002989
John McCallbcd03502009-12-07 02:54:59 +00002990 if (!TInfo)
2991 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002992
Sebastian Redla9351792012-02-11 23:51:47 +00002993 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00002994}
2995
Chandler Carruth599deef2011-09-03 01:14:15 +00002996/// Checks a member initializer expression for cases where reference (or
2997/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00002998static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2999 Expr *Init,
3000 SourceLocation IdLoc) {
3001 QualType MemberTy = Member->getType();
3002
3003 // We only handle pointers and references currently.
3004 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3005 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3006 return;
3007
3008 const bool IsPointer = MemberTy->isPointerType();
3009 if (IsPointer) {
3010 if (const UnaryOperator *Op
3011 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3012 // The only case we're worried about with pointers requires taking the
3013 // address.
3014 if (Op->getOpcode() != UO_AddrOf)
3015 return;
3016
3017 Init = Op->getSubExpr();
3018 } else {
3019 // We only handle address-of expression initializers for pointers.
3020 return;
3021 }
3022 }
3023
Richard Smithe3b28bc2013-06-12 21:51:50 +00003024 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003025 // We only warn when referring to a non-reference parameter declaration.
3026 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3027 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00003028 return;
3029
3030 S.Diag(Init->getExprLoc(),
3031 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3032 : diag::warn_bind_ref_member_to_parameter)
3033 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003034 } else {
3035 // Other initializers are fine.
3036 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00003037 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003038
3039 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3040 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00003041}
3042
John McCallfaf5fb42010-08-26 23:41:50 +00003043MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003044Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00003045 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00003046 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3047 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3048 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00003049 "Member must be a FieldDecl or IndirectFieldDecl");
3050
Sebastian Redla9351792012-02-11 23:51:47 +00003051 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00003052 return true;
3053
Douglas Gregor266bb5f2010-11-05 22:21:31 +00003054 if (Member->isInvalidDecl())
3055 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00003056
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003057 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00003058 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003059 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00003060 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003061 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00003062 } else {
3063 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003064 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003065 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00003066
Sebastian Redla9351792012-02-11 23:51:47 +00003067 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00003068
Sebastian Redla9351792012-02-11 23:51:47 +00003069 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003070 // Can't check initialization for a member of dependent type or when
3071 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00003072 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00003073 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00003074 bool InitList = false;
3075 if (isa<InitListExpr>(Init)) {
3076 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003077 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003078 }
3079
Chandler Carruthd44c3102010-12-06 09:23:57 +00003080 // Initialize the member.
3081 InitializedEntity MemberEntity =
Craig Topperc3ec1492014-05-26 06:22:03 +00003082 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3083 : InitializedEntity::InitializeMember(IndirectMember,
3084 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003085 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003086 InitList ? InitializationKind::CreateDirectList(IdLoc)
3087 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3088 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00003089
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003090 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003091 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3092 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003093 if (MemberInit.isInvalid())
3094 return true;
3095
Richard Smith736a9472013-06-12 20:42:33 +00003096 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3097
Richard Smith945f8d32013-01-14 22:39:08 +00003098 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00003099 // The initialization of each base and member constitutes a
3100 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003101 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003102 if (MemberInit.isInvalid())
3103 return true;
3104
Richard Smithd59b8322012-12-19 01:39:02 +00003105 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003106 }
3107
Chandler Carruthd44c3102010-12-06 09:23:57 +00003108 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00003109 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3110 InitRange.getBegin(), Init,
3111 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003112 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00003113 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3114 InitRange.getBegin(), Init,
3115 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003116 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00003117}
3118
John McCallfaf5fb42010-08-26 23:41:50 +00003119MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003120Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00003121 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003122 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003123 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003124 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003125 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003126 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00003127
Sebastian Redl0501c632012-02-12 16:37:36 +00003128 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003129 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003130 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3131 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003132 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00003133 }
3134
Sebastian Redla9351792012-02-11 23:51:47 +00003135 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00003136 // Initialize the object.
3137 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3138 QualType(ClassDecl->getTypeForDecl(), 0));
3139 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003140 InitList ? InitializationKind::CreateDirectList(NameLoc)
3141 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3142 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003143 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00003144 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Craig Topperc3ec1492014-05-26 06:22:03 +00003145 Args, nullptr);
Alexis Huntc5575cc2011-02-26 19:13:13 +00003146 if (DelegationInit.isInvalid())
3147 return true;
3148
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00003149 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3150 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00003151
Richard Smith945f8d32013-01-14 22:39:08 +00003152 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00003153 // The initialization of each base and member constitutes a
3154 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003155 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3156 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00003157 if (DelegationInit.isInvalid())
3158 return true;
3159
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00003160 // If we are in a dependent context, template instantiation will
3161 // perform this type-checking again. Just save the arguments that we
3162 // received in a ParenListExpr.
3163 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3164 // of the information that we have about the base
3165 // initializer. However, deconstructing the ASTs is a dicey process,
3166 // and this approach is far more likely to get the corner cases right.
3167 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003168 DelegationInit = Init;
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00003169
Sebastian Redla9351792012-02-11 23:51:47 +00003170 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003171 DelegationInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003172 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003173}
3174
3175MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00003176Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00003177 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00003178 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003179 SourceLocation BaseLoc
3180 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00003181
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003182 if (!BaseType->isDependentType() && !BaseType->isRecordType())
3183 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3184 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3185
3186 // C++ [class.base.init]p2:
3187 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00003188 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003189 // of that class, the mem-initializer is ill-formed. A
3190 // mem-initializer-list can initialize a base class using any
3191 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00003192 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003193
Sebastian Redla9351792012-02-11 23:51:47 +00003194 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00003195 if (EllipsisLoc.isValid()) {
3196 // This is a pack expansion.
3197 if (!BaseType->containsUnexpandedParameterPack()) {
3198 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00003199 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00003200
Douglas Gregor44e7df62011-01-04 00:32:56 +00003201 EllipsisLoc = SourceLocation();
3202 }
3203 } else {
3204 // Check for any unexpanded parameter packs.
3205 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3206 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00003207
Sebastian Redla9351792012-02-11 23:51:47 +00003208 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00003209 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00003210 }
Sebastian Redla74948d2011-09-24 17:48:25 +00003211
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003212 // Check for direct and virtual base classes.
Craig Topperc3ec1492014-05-26 06:22:03 +00003213 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3214 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003215 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003216 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3217 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00003218 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003219
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003220 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
3221 VirtualBaseSpec);
3222
3223 // C++ [base.class.init]p2:
3224 // Unless the mem-initializer-id names a nonstatic data member of the
3225 // constructor's class or a direct or virtual base of that class, the
3226 // mem-initializer is ill-formed.
3227 if (!DirectBaseSpec && !VirtualBaseSpec) {
3228 // If the class has any dependent bases, then it's possible that
3229 // one of those types will resolve to the same type as
3230 // BaseType. Therefore, just treat this as a dependent base
3231 // class initialization. FIXME: Should we try to check the
3232 // initialization anyway? It seems odd.
3233 if (ClassDecl->hasAnyDependentBases())
3234 Dependent = true;
3235 else
3236 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
3237 << BaseType << Context.getTypeDeclType(ClassDecl)
3238 << BaseTInfo->getTypeLoc().getLocalSourceRange();
3239 }
3240 }
3241
3242 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00003243 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00003244
Sebastian Redla74948d2011-09-24 17:48:25 +00003245 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3246 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00003247 InitRange.getBegin(), Init,
3248 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003249 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003250
3251 // C++ [base.class.init]p2:
3252 // If a mem-initializer-id is ambiguous because it designates both
3253 // a direct non-virtual base class and an inherited virtual base
3254 // class, the mem-initializer is ill-formed.
3255 if (DirectBaseSpec && VirtualBaseSpec)
3256 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00003257 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003258
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003259 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003260 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003261 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003262
3263 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00003264 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003265 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003266 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00003267 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003268 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00003269 }
Sebastian Redl0501c632012-02-12 16:37:36 +00003270
3271 InitializedEntity BaseEntity =
3272 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3273 InitializationKind Kind =
3274 InitList ? InitializationKind::CreateDirectList(BaseLoc)
3275 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3276 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003277 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003278 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003279 if (BaseInit.isInvalid())
3280 return true;
John McCallacf0ee52010-10-08 02:01:28 +00003281
Richard Smith945f8d32013-01-14 22:39:08 +00003282 // C++11 [class.base.init]p7:
3283 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003284 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003285 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003286 if (BaseInit.isInvalid())
3287 return true;
3288
3289 // If we are in a dependent context, template instantiation will
3290 // perform this type-checking again. Just save the arguments that we
3291 // received in a ParenListExpr.
3292 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3293 // of the information that we have about the base
3294 // initializer. However, deconstructing the ASTs is a dicey process,
3295 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00003296 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003297 BaseInit = Init;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003298
Alexis Hunt1d792652011-01-08 20:30:50 +00003299 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00003300 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00003301 InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003302 BaseInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003303 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003304}
3305
Sebastian Redl22653ba2011-08-30 19:58:05 +00003306// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00003307static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3308 if (T.isNull()) T = E->getType();
3309 QualType TargetType = SemaRef.BuildReferenceType(
3310 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003311 SourceLocation ExprLoc = E->getLocStart();
3312 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3313 TargetType, ExprLoc);
3314
3315 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3316 SourceRange(ExprLoc, ExprLoc),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003317 E->getSourceRange()).get();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003318}
3319
Anders Carlsson1b00e242010-04-23 03:10:23 +00003320/// ImplicitInitializerKind - How an implicit base or member initializer should
3321/// initialize its base or member.
3322enum ImplicitInitializerKind {
3323 IIK_Default,
3324 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00003325 IIK_Move,
3326 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00003327};
3328
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003329static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00003330BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003331 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00003332 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003333 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00003334 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003335 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00003336 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3337 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003338
John McCalldadc5752010-08-24 06:29:42 +00003339 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003340
3341 switch (ImplicitInitKind) {
Richard Smithc2bc61b2013-03-18 21:12:30 +00003342 case IIK_Inherit: {
3343 const CXXRecordDecl *Inherited =
3344 Constructor->getInheritedConstructor()->getParent();
3345 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3346 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3347 // C++11 [class.inhctor]p8:
3348 // Each expression in the expression-list is of the form
3349 // static_cast<T&&>(p), where p is the name of the corresponding
3350 // constructor parameter and T is the declared type of p.
3351 SmallVector<Expr*, 16> Args;
3352 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3353 ParmVarDecl *PD = Constructor->getParamDecl(I);
3354 ExprResult ArgExpr =
3355 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3356 VK_LValue, SourceLocation());
3357 if (ArgExpr.isInvalid())
3358 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003359 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
Richard Smithc2bc61b2013-03-18 21:12:30 +00003360 }
3361
3362 InitializationKind InitKind = InitializationKind::CreateDirect(
3363 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003364 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smithc2bc61b2013-03-18 21:12:30 +00003365 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3366 break;
3367 }
3368 }
3369 // Fall through.
Anders Carlsson1b00e242010-04-23 03:10:23 +00003370 case IIK_Default: {
3371 InitializationKind InitKind
3372 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003373 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3374 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003375 break;
3376 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003377
Sebastian Redl22653ba2011-08-30 19:58:05 +00003378 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00003379 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003380 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003381 ParmVarDecl *Param = Constructor->getParamDecl(0);
3382 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00003383
Anders Carlsson1b00e242010-04-23 03:10:23 +00003384 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003385 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003386 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003387 Constructor->getLocation(), ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003388 VK_LValue, nullptr);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003389
Eli Friedmanfa0df832012-02-02 03:46:19 +00003390 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3391
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003392 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00003393 QualType ArgTy =
3394 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3395 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00003396
Sebastian Redl22653ba2011-08-30 19:58:05 +00003397 if (Moving) {
3398 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3399 }
3400
John McCallcf142162010-08-07 06:22:56 +00003401 CXXCastPath BasePath;
3402 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00003403 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3404 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003405 Moving ? VK_XValue : VK_LValue,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003406 &BasePath).get();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003407
Anders Carlsson1b00e242010-04-23 03:10:23 +00003408 InitializationKind InitKind
3409 = InitializationKind::CreateDirect(Constructor->getLocation(),
3410 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003411 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3412 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003413 break;
3414 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00003415 }
John McCallb268a282010-08-23 23:25:46 +00003416
Douglas Gregora40433a2010-12-07 00:41:46 +00003417 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003418 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003419 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003420
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003421 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00003422 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003423 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3424 SourceLocation()),
3425 BaseSpec->isVirtual(),
3426 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003427 BaseInit.getAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003428 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003429 SourceLocation());
3430
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003431 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003432}
3433
Sebastian Redl22653ba2011-08-30 19:58:05 +00003434static bool RefersToRValueRef(Expr *MemRef) {
3435 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3436 return Referenced->getType()->isRValueReferenceType();
3437}
3438
Anders Carlsson3c1db572010-04-23 02:15:47 +00003439static bool
3440BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003441 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00003442 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00003443 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003444 if (Field->isInvalidDecl())
3445 return true;
3446
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003447 SourceLocation Loc = Constructor->getLocation();
3448
Sebastian Redl22653ba2011-08-30 19:58:05 +00003449 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3450 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00003451 ParmVarDecl *Param = Constructor->getParamDecl(0);
3452 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00003453
3454 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00003455 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3456 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003457
Anders Carlsson423f5d82010-04-23 16:04:08 +00003458 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003459 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003460 SourceLocation(), Param, false,
Craig Topperc3ec1492014-05-26 06:22:03 +00003461 Loc, ParamType, VK_LValue, nullptr);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003462
Eli Friedmanfa0df832012-02-02 03:46:19 +00003463 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3464
Sebastian Redl22653ba2011-08-30 19:58:05 +00003465 if (Moving) {
3466 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3467 }
3468
Douglas Gregor94f9a482010-05-05 05:51:00 +00003469 // Build a reference to this field within the parameter.
3470 CXXScopeSpec SS;
3471 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3472 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003473 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3474 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003475 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00003476 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00003477 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003478 ParamType, Loc,
3479 /*IsArrow=*/false,
3480 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003481 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003482 /*FirstQualifierInScope=*/nullptr,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003483 MemberLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00003484 /*TemplateArgs=*/nullptr);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003485 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00003486 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003487
3488 // C++11 [class.copy]p15:
3489 // - if a member m has rvalue reference type T&&, it is direct-initialized
3490 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003491 if (RefersToRValueRef(CtorArg.get())) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003492 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003493 }
3494
Douglas Gregor94f9a482010-05-05 05:51:00 +00003495 // When the field we are copying is an array, create index variables for
3496 // each dimension of the array. We use these index variables to subscript
3497 // the source array, and other clients (e.g., CodeGen) will perform the
3498 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003499 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003500 QualType BaseType = Field->getType();
3501 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003502 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003503 while (const ConstantArrayType *Array
3504 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003505 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003506 // Create the iteration variable for this array index.
Craig Topperc3ec1492014-05-26 06:22:03 +00003507 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003508 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003509 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003510 llvm::raw_svector_ostream OS(Str);
3511 OS << "__i" << IndexVariables.size();
3512 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3513 }
3514 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00003515 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003516 IterationVarName, SizeType,
3517 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003518 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003519 IndexVariables.push_back(IterationVar);
3520
3521 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00003522 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00003523 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003524 assert(!IterationVarRef.isInvalid() &&
3525 "Reference to invented variable cannot fail!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003526 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
Eli Friedman844f9452012-01-23 02:35:22 +00003527 assert(!IterationVarRef.isInvalid() &&
3528 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00003529
Douglas Gregor94f9a482010-05-05 05:51:00 +00003530 // Subscript the array with this iteration variable.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003531 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3532 IterationVarRef.get(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00003533 Loc);
3534 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00003535 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003536
Douglas Gregor94f9a482010-05-05 05:51:00 +00003537 BaseType = Array->getElementType();
3538 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00003539
3540 // The array subscript expression is an lvalue, which is wrong for moving.
3541 if (Moving && InitializingArray)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003542 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003543
Douglas Gregor94f9a482010-05-05 05:51:00 +00003544 // Construct the entity that we will be initializing. For an array, this
3545 // will be first element in the array, which may require several levels
3546 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003547 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003548 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00003549 if (Indirect)
3550 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3551 else
3552 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00003553 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3554 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3555 0,
3556 Entities.back()));
3557
3558 // Direct-initialize to use the copy constructor.
3559 InitializationKind InitKind =
3560 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3561
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003562 Expr *CtorArgE = CtorArg.getAs<Expr>();
Nico Weber3b00fdc2015-03-07 19:52:39 +00003563 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
3564 CtorArgE);
3565
John McCalldadc5752010-08-24 06:29:42 +00003566 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00003567 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003568 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00003569 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003570 if (MemberInit.isInvalid())
3571 return true;
3572
Douglas Gregor493627b2011-08-10 15:22:55 +00003573 if (Indirect) {
3574 assert(IndexVariables.size() == 0 &&
3575 "Indirect field improperly initialized");
3576 CXXMemberInit
3577 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3578 Loc, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003579 MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003580 Loc);
3581 } else
3582 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003583 Loc, MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003584 Loc,
3585 IndexVariables.data(),
3586 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00003587 return false;
3588 }
3589
Richard Smithc2bc61b2013-03-18 21:12:30 +00003590 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3591 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00003592
Anders Carlsson3c1db572010-04-23 02:15:47 +00003593 QualType FieldBaseElementType =
3594 SemaRef.Context.getBaseElementType(Field->getType());
3595
Anders Carlsson3c1db572010-04-23 02:15:47 +00003596 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003597 InitializedEntity InitEntity
3598 = Indirect? InitializedEntity::InitializeMember(Indirect)
3599 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00003600 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003601 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003602
3603 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3604 ExprResult MemberInit =
3605 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00003606
Douglas Gregora40433a2010-12-07 00:41:46 +00003607 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003608 if (MemberInit.isInvalid())
3609 return true;
3610
Douglas Gregor493627b2011-08-10 15:22:55 +00003611 if (Indirect)
3612 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3613 Indirect, Loc,
3614 Loc,
3615 MemberInit.get(),
3616 Loc);
3617 else
3618 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3619 Field, Loc, Loc,
3620 MemberInit.get(),
3621 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003622 return false;
3623 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003624
Alexis Hunt8b455182011-05-17 00:19:05 +00003625 if (!Field->getParent()->isUnion()) {
3626 if (FieldBaseElementType->isReferenceType()) {
3627 SemaRef.Diag(Constructor->getLocation(),
3628 diag::err_uninitialized_member_in_ctor)
3629 << (int)Constructor->isImplicit()
3630 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3631 << 0 << Field->getDeclName();
3632 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3633 return true;
3634 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003635
Alexis Hunt8b455182011-05-17 00:19:05 +00003636 if (FieldBaseElementType.isConstQualified()) {
3637 SemaRef.Diag(Constructor->getLocation(),
3638 diag::err_uninitialized_member_in_ctor)
3639 << (int)Constructor->isImplicit()
3640 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3641 << 1 << Field->getDeclName();
3642 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3643 return true;
3644 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003645 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00003646
David Blaikiebbafb8a2012-03-11 07:00:24 +00003647 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003648 FieldBaseElementType->isObjCRetainableType() &&
3649 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3650 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00003651 // ARC:
John McCall31168b02011-06-15 23:02:42 +00003652 // Default-initialize Objective-C pointers to NULL.
3653 CXXMemberInit
3654 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3655 Loc, Loc,
3656 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3657 Loc);
3658 return false;
3659 }
3660
Anders Carlsson3c1db572010-04-23 02:15:47 +00003661 // Nothing to initialize.
Craig Topperc3ec1492014-05-26 06:22:03 +00003662 CXXMemberInit = nullptr;
Anders Carlsson3c1db572010-04-23 02:15:47 +00003663 return false;
3664}
John McCallbc83b3f2010-05-20 23:23:51 +00003665
3666namespace {
3667struct BaseAndFieldInfo {
3668 Sema &S;
3669 CXXConstructorDecl *Ctor;
3670 bool AnyErrorsInInits;
3671 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00003672 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003673 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00003674 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00003675
3676 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3677 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003678 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3679 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00003680 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003681 else if (Generated && Ctor->isMoveConstructor())
3682 IIK = IIK_Move;
Richard Smithc2bc61b2013-03-18 21:12:30 +00003683 else if (Ctor->getInheritedConstructor())
3684 IIK = IIK_Inherit;
John McCallbc83b3f2010-05-20 23:23:51 +00003685 else
3686 IIK = IIK_Default;
3687 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00003688
3689 bool isImplicitCopyOrMove() const {
3690 switch (IIK) {
3691 case IIK_Copy:
3692 case IIK_Move:
3693 return true;
3694
3695 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00003696 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00003697 return false;
3698 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003699
3700 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00003701 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00003702
3703 bool addFieldInitializer(CXXCtorInitializer *Init) {
3704 AllToInit.push_back(Init);
3705
3706 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00003707 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003708 S.UnusedPrivateFields.remove(Init->getAnyMember());
3709
3710 return false;
3711 }
John McCallbc83b3f2010-05-20 23:23:51 +00003712
Richard Smithab44d5b2013-12-10 08:25:00 +00003713 bool isInactiveUnionMember(FieldDecl *Field) {
3714 RecordDecl *Record = Field->getParent();
3715 if (!Record->isUnion())
3716 return false;
3717
Richard Smith8d183852013-12-10 20:56:03 +00003718 if (FieldDecl *Active =
3719 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00003720 return Active != Field->getCanonicalDecl();
3721
3722 // In an implicit copy or move constructor, ignore any in-class initializer.
3723 if (isImplicitCopyOrMove())
3724 return true;
3725
3726 // If there's no explicit initialization, the field is active only if it
3727 // has an in-class initializer...
3728 if (Field->hasInClassInitializer())
3729 return false;
3730 // ... or it's an anonymous struct or union whose class has an in-class
3731 // initializer.
3732 if (!Field->isAnonymousStructOrUnion())
3733 return true;
3734 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3735 return !FieldRD->hasInClassInitializer();
3736 }
3737
3738 /// \brief Determine whether the given field is, or is within, a union member
3739 /// that is inactive (because there was an initializer given for a different
3740 /// member of the union, or because the union was not initialized at all).
3741 bool isWithinInactiveUnionMember(FieldDecl *Field,
3742 IndirectFieldDecl *Indirect) {
3743 if (!Indirect)
3744 return isInactiveUnionMember(Field);
3745
Aaron Ballman29c94602014-03-07 18:36:15 +00003746 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003747 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003748 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00003749 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00003750 }
3751 return false;
3752 }
3753};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003754}
Richard Smithc94ec842011-09-19 13:34:43 +00003755
Douglas Gregor10f939c2011-11-02 23:04:16 +00003756/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3757/// array type.
3758static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3759 if (T->isIncompleteArrayType())
3760 return true;
3761
3762 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3763 if (!ArrayT->getSize())
3764 return true;
3765
3766 T = ArrayT->getElementType();
3767 }
3768
3769 return false;
3770}
3771
Richard Smith938f40b2011-06-11 17:19:42 +00003772static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00003773 FieldDecl *Field,
Craig Topperc3ec1492014-05-26 06:22:03 +00003774 IndirectFieldDecl *Indirect = nullptr) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003775 if (Field->isInvalidDecl())
3776 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00003777
Chandler Carruth139e9622010-06-30 02:59:29 +00003778 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smithcd45dbc2014-04-19 03:48:30 +00003779 if (CXXCtorInitializer *Init =
3780 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003781 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003782
Richard Smithab44d5b2013-12-10 08:25:00 +00003783 // C++11 [class.base.init]p8:
3784 // if the entity is a non-static data member that has a
3785 // brace-or-equal-initializer and either
3786 // -- the constructor's class is a union and no other variant member of that
3787 // union is designated by a mem-initializer-id or
3788 // -- the constructor's class is not a union, and, if the entity is a member
3789 // of an anonymous union, no other member of that union is designated by
3790 // a mem-initializer-id,
3791 // the entity is initialized as specified in [dcl.init].
3792 //
3793 // We also apply the same rules to handle anonymous structs within anonymous
3794 // unions.
3795 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3796 return false;
3797
Douglas Gregor7db3e952011-11-28 20:03:15 +00003798 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003799 ExprResult DIE =
3800 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
3801 if (DIE.isInvalid())
3802 return true;
Douglas Gregor493627b2011-08-10 15:22:55 +00003803 CXXCtorInitializer *Init;
3804 if (Indirect)
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003805 Init = new (SemaRef.Context)
3806 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
3807 SourceLocation(), DIE.get(), SourceLocation());
Douglas Gregor493627b2011-08-10 15:22:55 +00003808 else
Reid Klecknerd60b82f2014-11-17 23:36:45 +00003809 Init = new (SemaRef.Context)
3810 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
3811 SourceLocation(), DIE.get(), SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00003812 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003813 }
3814
Douglas Gregor10f939c2011-11-02 23:04:16 +00003815 // Don't initialize incomplete or zero-length arrays.
3816 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3817 return false;
3818
John McCallbc83b3f2010-05-20 23:23:51 +00003819 // Don't try to build an implicit initializer if there were semantic
3820 // errors in any of the initializers (and therefore we might be
3821 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003822 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00003823 return false;
3824
Craig Topperc3ec1492014-05-26 06:22:03 +00003825 CXXCtorInitializer *Init = nullptr;
Douglas Gregor493627b2011-08-10 15:22:55 +00003826 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3827 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00003828 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00003829
Richard Smith0a8cfc72012-08-07 21:30:42 +00003830 if (!Init)
3831 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00003832
Richard Smith0a8cfc72012-08-07 21:30:42 +00003833 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003834}
Alexis Hunt61bc1732011-05-01 07:04:31 +00003835
3836bool
3837Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3838 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00003839 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00003840 Constructor->setNumCtorInitializers(1);
3841 CXXCtorInitializer **initializer =
3842 new (Context) CXXCtorInitializer*[1];
3843 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3844 Constructor->setCtorInitializers(initializer);
3845
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003846 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003847 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003848 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3849 }
3850
Alexis Hunte2622992011-05-05 00:05:47 +00003851 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00003852
Richard Trieu8a0c9e62014-09-12 22:47:58 +00003853 DiagnoseUninitializedFields(*this, Constructor);
3854
Alexis Hunt61bc1732011-05-01 07:04:31 +00003855 return false;
3856}
Douglas Gregor493627b2011-08-10 15:22:55 +00003857
David Blaikie3fc2f912013-01-17 05:26:25 +00003858bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3859 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00003860 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003861 // Just store the initializers as written, they will be checked during
3862 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00003863 if (!Initializers.empty()) {
3864 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00003865 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00003866 new (Context) CXXCtorInitializer*[Initializers.size()];
3867 memcpy(baseOrMemberInitializers, Initializers.data(),
3868 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00003869 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003870 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00003871
3872 // Let template instantiation know whether we had errors.
3873 if (AnyErrors)
3874 Constructor->setInvalidDecl();
3875
Anders Carlssondb0a9652010-04-02 06:26:44 +00003876 return false;
3877 }
3878
John McCallbc83b3f2010-05-20 23:23:51 +00003879 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003880
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003881 // We need to build the initializer AST according to order of construction
3882 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003883 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00003884 if (!ClassDecl)
3885 return true;
3886
Eli Friedman9cf6b592009-11-09 19:20:36 +00003887 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00003888
David Blaikie3fc2f912013-01-17 05:26:25 +00003889 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003890 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00003891
Anders Carlssondb0a9652010-04-02 06:26:44 +00003892 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00003893 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003894 else {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003895 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003896
3897 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00003898 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003899 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003900 if (FD && FD->getParent()->isUnion())
3901 Info.ActiveUnionMember.insert(std::make_pair(
3902 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3903 }
3904 } else if (FieldDecl *FD = Member->getMember()) {
3905 if (FD->getParent()->isUnion())
3906 Info.ActiveUnionMember.insert(std::make_pair(
3907 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3908 }
3909 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00003910 }
3911
Anders Carlsson43c64af2010-04-21 19:52:01 +00003912 // Keep track of the direct virtual bases.
3913 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00003914 for (auto &I : ClassDecl->bases()) {
3915 if (I.isVirtual())
3916 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00003917 }
3918
Anders Carlssondb0a9652010-04-02 06:26:44 +00003919 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00003920 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003921 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00003922 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00003923 // [class.base.init]p7, per DR257:
3924 // A mem-initializer where the mem-initializer-id names a virtual base
3925 // class is ignored during execution of a constructor of any class that
3926 // is not the most derived class.
3927 if (ClassDecl->isAbstract()) {
3928 // FIXME: Provide a fixit to remove the base specifier. This requires
3929 // tracking the location of the associated comma for a base specifier.
3930 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00003931 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00003932 DiagnoseAbstractType(ClassDecl);
3933 }
3934
John McCallbc83b3f2010-05-20 23:23:51 +00003935 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00003936 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3937 // [class.base.init]p8, per DR257:
3938 // If a given [...] base class is not named by a mem-initializer-id
3939 // [...] and the entity is not a virtual base class of an abstract
3940 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00003941 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00003942 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003943 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00003944 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003945 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003946 HadError = true;
3947 continue;
3948 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003949
John McCallbc83b3f2010-05-20 23:23:51 +00003950 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003951 }
3952 }
Mike Stump11289f42009-09-09 15:08:12 +00003953
John McCallbc83b3f2010-05-20 23:23:51 +00003954 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003955 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003956 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00003957 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00003958 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003959
Alexis Hunt1d792652011-01-08 20:30:50 +00003960 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00003961 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00003962 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003963 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003964 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003965 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00003966 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003967 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003968 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003969 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003970 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00003971
John McCallbc83b3f2010-05-20 23:23:51 +00003972 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003973 }
3974 }
Mike Stump11289f42009-09-09 15:08:12 +00003975
John McCallbc83b3f2010-05-20 23:23:51 +00003976 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00003977 for (auto *Mem : ClassDecl->decls()) {
3978 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003979 // C++ [class.bit]p2:
3980 // A declaration for a bit-field that omits the identifier declares an
3981 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3982 // initialized.
3983 if (F->isUnnamedBitfield())
3984 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003985
Sebastian Redl22653ba2011-08-30 19:58:05 +00003986 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00003987 // handle anonymous struct/union fields based on their individual
3988 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003989 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003990 continue;
3991
3992 if (CollectFieldInitializer(*this, Info, F))
3993 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003994 continue;
3995 }
Douglas Gregor493627b2011-08-10 15:22:55 +00003996
3997 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003998 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003999 continue;
4000
Aaron Ballman629afae2014-03-07 19:56:05 +00004001 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00004002 if (F->getType()->isIncompleteArrayType()) {
4003 assert(ClassDecl->hasFlexibleArrayMember() &&
4004 "Incomplete array type is not valid");
4005 continue;
4006 }
4007
Douglas Gregor493627b2011-08-10 15:22:55 +00004008 // Initialize each field of an anonymous struct individually.
4009 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4010 HadError = true;
4011
4012 continue;
4013 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004014 }
Mike Stump11289f42009-09-09 15:08:12 +00004015
David Blaikie3fc2f912013-01-17 05:26:25 +00004016 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004017 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004018 Constructor->setNumCtorInitializers(NumInitializers);
4019 CXXCtorInitializer **baseOrMemberInitializers =
4020 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00004021 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00004022 NumInitializers * sizeof(CXXCtorInitializer*));
4023 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00004024
John McCalla6309952010-03-16 21:39:52 +00004025 // Constructors implicitly reference the base and member
4026 // destructors.
4027 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4028 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004029 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00004030
4031 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004032}
4033
David Blaikieb61b8152013-01-17 08:49:22 +00004034static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004035 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00004036 const RecordDecl *RD = RT->getDecl();
4037 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004038 for (auto *Field : RD->fields())
4039 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00004040 return;
4041 }
Eli Friedman952c15d2009-07-21 19:28:10 +00004042 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00004043 IdealInits.push_back(Field->getCanonicalDecl());
Eli Friedman952c15d2009-07-21 19:28:10 +00004044}
4045
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004046static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4047 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00004048}
4049
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004050static const void *GetKeyForMember(ASTContext &Context,
4051 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00004052 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004053 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00004054
Richard Smithcd45dbc2014-04-19 03:48:30 +00004055 return Member->getAnyMember()->getCanonicalDecl();
Eli Friedman952c15d2009-07-21 19:28:10 +00004056}
4057
David Blaikie3fc2f912013-01-17 05:26:25 +00004058static void DiagnoseBaseOrMemInitializerOrder(
4059 Sema &SemaRef, const CXXConstructorDecl *Constructor,
4060 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00004061 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00004062 return;
Mike Stump11289f42009-09-09 15:08:12 +00004063
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004064 // Don't check initializers order unless the warning is enabled at the
4065 // location of at least one initializer.
4066 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004067 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004068 CXXCtorInitializer *Init = Inits[InitIndex];
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004069 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4070 Init->getSourceLocation())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004071 ShouldCheckOrder = true;
4072 break;
4073 }
4074 }
4075 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00004076 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004077
John McCallbb7b6582010-04-10 07:37:23 +00004078 // Build the list of bases and members in the order that they'll
4079 // actually be initialized. The explicit initializers should be in
4080 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004081 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00004082
Anders Carlsson96b8fc62010-04-02 03:38:04 +00004083 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4084
John McCallbb7b6582010-04-10 07:37:23 +00004085 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004086 for (const auto &VBase : ClassDecl->vbases())
4087 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00004088
John McCallbb7b6582010-04-10 07:37:23 +00004089 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004090 for (const auto &Base : ClassDecl->bases()) {
4091 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00004092 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00004093 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00004094 }
Mike Stump11289f42009-09-09 15:08:12 +00004095
John McCallbb7b6582010-04-10 07:37:23 +00004096 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004097 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004098 if (Field->isUnnamedBitfield())
4099 continue;
4100
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004101 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00004102 }
4103
John McCallbb7b6582010-04-10 07:37:23 +00004104 unsigned NumIdealInits = IdealInitKeys.size();
4105 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00004106
Craig Topperc3ec1492014-05-26 06:22:03 +00004107 CXXCtorInitializer *PrevInit = nullptr;
David Blaikie3fc2f912013-01-17 05:26:25 +00004108 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004109 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004110 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00004111
4112 // Scan forward to try to find this initializer in the idealized
4113 // initializers list.
4114 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4115 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004116 break;
John McCallbb7b6582010-04-10 07:37:23 +00004117
4118 // If we didn't find this initializer, it must be because we
4119 // scanned past it on a previous iteration. That can only
4120 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00004121 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00004122 Sema::SemaDiagnosticBuilder D =
4123 SemaRef.Diag(PrevInit->getSourceLocation(),
4124 diag::warn_initializer_out_of_order);
4125
Francois Pichetd583da02010-12-04 09:14:42 +00004126 if (PrevInit->isAnyMemberInitializer())
4127 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004128 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004129 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004130
Francois Pichetd583da02010-12-04 09:14:42 +00004131 if (Init->isAnyMemberInitializer())
4132 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004133 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004134 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004135
4136 // Move back to the initializer's location in the ideal list.
4137 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4138 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004139 break;
John McCallbb7b6582010-04-10 07:37:23 +00004140
Davide Italiano838838f2015-07-19 22:07:14 +00004141 assert(IdealIndex >= 0 && IdealIndex < NumIdealInits &&
John McCallbb7b6582010-04-10 07:37:23 +00004142 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004143 }
John McCallbb7b6582010-04-10 07:37:23 +00004144
4145 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004146 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00004147}
4148
John McCall23eebd92010-04-10 09:28:51 +00004149namespace {
4150bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004151 CXXCtorInitializer *Init,
4152 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00004153 if (!PrevInit) {
4154 PrevInit = Init;
4155 return false;
4156 }
4157
Douglas Gregorea306a12013-03-25 23:28:23 +00004158 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00004159 S.Diag(Init->getSourceLocation(),
4160 diag::err_multiple_mem_initialization)
4161 << Field->getDeclName()
4162 << Init->getSourceRange();
4163 else {
John McCall424cec92011-01-19 06:33:43 +00004164 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00004165 assert(BaseClass && "neither field nor base");
4166 S.Diag(Init->getSourceLocation(),
4167 diag::err_multiple_base_initialization)
4168 << QualType(BaseClass, 0)
4169 << Init->getSourceRange();
4170 }
4171 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4172 << 0 << PrevInit->getSourceRange();
4173
4174 return true;
4175}
4176
Alexis Hunt1d792652011-01-08 20:30:50 +00004177typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00004178typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4179
4180bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004181 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00004182 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00004183 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00004184 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00004185 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00004186
4187 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00004188 if (Parent->isUnion()) {
4189 UnionEntry &En = Unions[Parent];
4190 if (En.first && En.first != Child) {
4191 S.Diag(Init->getSourceLocation(),
4192 diag::err_multiple_mem_union_initialization)
4193 << Field->getDeclName()
4194 << Init->getSourceRange();
4195 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4196 << 0 << En.second->getSourceRange();
4197 return true;
David Blaikie256ee192011-11-12 20:54:14 +00004198 }
4199 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00004200 En.first = Child;
4201 En.second = Init;
4202 }
David Blaikie0f65d592011-11-17 06:01:57 +00004203 if (!Parent->isAnonymousStructOrUnion())
4204 return false;
John McCall23eebd92010-04-10 09:28:51 +00004205 }
4206
4207 Child = Parent;
4208 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00004209 }
John McCall23eebd92010-04-10 09:28:51 +00004210
4211 return false;
4212}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004213}
John McCall23eebd92010-04-10 09:28:51 +00004214
Anders Carlssone857b292010-04-02 03:37:03 +00004215/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00004216void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00004217 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00004218 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00004219 bool AnyErrors) {
4220 if (!ConstructorDecl)
4221 return;
4222
4223 AdjustDeclIfTemplate(ConstructorDecl);
4224
4225 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00004226 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00004227
4228 if (!Constructor) {
4229 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4230 return;
4231 }
4232
John McCall23eebd92010-04-10 09:28:51 +00004233 // Mapping for the duplicate initializers check.
4234 // For member initializers, this is keyed with a FieldDecl*.
4235 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004236 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00004237
4238 // Mapping for the inconsistent anonymous-union initializers check.
4239 RedundantUnionMap MemberUnions;
4240
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004241 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004242 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004243 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00004244
Abramo Bagnara341d7832010-05-26 18:09:23 +00004245 // Set the source order index.
4246 Init->setSourceOrder(i);
4247
Francois Pichetd583da02010-12-04 09:14:42 +00004248 if (Init->isAnyMemberInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004249 const void *Key = GetKeyForMember(Context, Init);
4250 if (CheckRedundantInit(*this, Init, Members[Key]) ||
John McCall23eebd92010-04-10 09:28:51 +00004251 CheckRedundantUnionInit(*this, Init, MemberUnions))
4252 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00004253 } else if (Init->isBaseInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004254 const void *Key = GetKeyForMember(Context, Init);
John McCall23eebd92010-04-10 09:28:51 +00004255 if (CheckRedundantInit(*this, Init, Members[Key]))
4256 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00004257 } else {
4258 assert(Init->isDelegatingInitializer());
4259 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00004260 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00004261 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00004262 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00004263 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00004264 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00004265 }
Alexis Hunt6118d662011-05-04 05:57:24 +00004266 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00004267 // Return immediately as the initializer is set.
4268 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004269 }
Anders Carlssone857b292010-04-02 03:37:03 +00004270 }
4271
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004272 if (HadError)
4273 return;
4274
David Blaikie3fc2f912013-01-17 05:26:25 +00004275 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00004276
David Blaikie3fc2f912013-01-17 05:26:25 +00004277 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00004278
Richard Trieuef64e942013-10-25 00:56:00 +00004279 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00004280}
4281
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004282void
John McCalla6309952010-03-16 21:39:52 +00004283Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4284 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00004285 // Ignore dependent contexts. Also ignore unions, since their members never
4286 // have destructors implicitly called.
4287 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00004288 return;
John McCall1064d7e2010-03-16 05:22:47 +00004289
4290 // FIXME: all the access-control diagnostics are positioned on the
4291 // field/base declaration. That's probably good; that said, the
4292 // user might reasonably want to know why the destructor is being
4293 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00004294
Anders Carlssondee9a302009-11-17 04:44:12 +00004295 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004296 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00004297 if (Field->isInvalidDecl())
4298 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004299
4300 // Don't destroy incomplete or zero-length arrays.
4301 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4302 continue;
4303
Anders Carlssondee9a302009-11-17 04:44:12 +00004304 QualType FieldType = Context.getBaseElementType(Field->getType());
4305
4306 const RecordType* RT = FieldType->getAs<RecordType>();
4307 if (!RT)
4308 continue;
4309
4310 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004311 if (FieldClassDecl->isInvalidDecl())
4312 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004313 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004314 continue;
Richard Smith921bd202012-02-26 09:11:52 +00004315 // The destructor for an implicit anonymous union member is never invoked.
4316 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4317 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00004318
Douglas Gregore71edda2010-07-01 22:47:18 +00004319 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004320 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004321 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004322 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00004323 << Field->getDeclName()
4324 << FieldType);
4325
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004326 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004327 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004328 }
4329
John McCall1064d7e2010-03-16 05:22:47 +00004330 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4331
Anders Carlssondee9a302009-11-17 04:44:12 +00004332 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004333 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004334 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00004335 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004336
4337 // Remember direct virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004338 if (Base.isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00004339 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00004340
John McCall1064d7e2010-03-16 05:22:47 +00004341 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004342 // If our base class is invalid, we probably can't get its dtor anyway.
4343 if (BaseClassDecl->isInvalidDecl())
4344 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004345 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004346 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004347
Douglas Gregore71edda2010-07-01 22:47:18 +00004348 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004349 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004350
4351 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00004352 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004353 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00004354 << Base.getType()
4355 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00004356 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00004357
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004358 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004359 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004360 }
4361
4362 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004363 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004364 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00004365 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004366
4367 // Ignore direct virtual bases.
4368 if (DirectVirtualBases.count(RT))
4369 continue;
4370
John McCall1064d7e2010-03-16 05:22:47 +00004371 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004372 // If our base class is invalid, we probably can't get its dtor anyway.
4373 if (BaseClassDecl->isInvalidDecl())
4374 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004375 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004376 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004377
Douglas Gregore71edda2010-07-01 22:47:18 +00004378 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004379 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00004380 if (CheckDestructorAccess(
4381 ClassDecl->getLocation(), Dtor,
4382 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00004383 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004384 Context.getTypeDeclType(ClassDecl)) ==
4385 AR_accessible) {
4386 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00004387 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004388 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00004389 SourceRange(), DeclarationName(), nullptr);
David Majnemer626032f2013-06-22 06:43:58 +00004390 }
John McCall1064d7e2010-03-16 05:22:47 +00004391
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004392 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004393 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004394 }
4395}
4396
John McCall48871652010-08-21 09:40:31 +00004397void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00004398 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004399 return;
Mike Stump11289f42009-09-09 15:08:12 +00004400
Mike Stump11289f42009-09-09 15:08:12 +00004401 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00004402 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00004403 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00004404 DiagnoseUninitializedFields(*this, Constructor);
4405 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004406}
4407
Mike Stump11289f42009-09-09 15:08:12 +00004408bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00004409 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregorae298422012-05-04 17:09:59 +00004410 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4411 unsigned DiagID;
4412 AbstractDiagSelID SelID;
4413
4414 public:
4415 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4416 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004417
Craig Toppera798a9d2014-03-02 09:32:10 +00004418 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004419 if (Suppressed) return;
Douglas Gregorae298422012-05-04 17:09:59 +00004420 if (SelID == -1)
4421 S.Diag(Loc, DiagID) << T;
4422 else
4423 S.Diag(Loc, DiagID) << SelID << T;
4424 }
4425 } Diagnoser(DiagID, SelID);
4426
4427 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004428}
4429
Anders Carlssoneabf7702009-08-27 00:13:57 +00004430bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregorae298422012-05-04 17:09:59 +00004431 TypeDiagnoser &Diagnoser) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004432 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004433 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004434
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004435 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregorae298422012-05-04 17:09:59 +00004436 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004437
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004438 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004439 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004440 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004441 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00004442
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004443 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregorae298422012-05-04 17:09:59 +00004444 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004445 }
Mike Stump11289f42009-09-09 15:08:12 +00004446
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004447 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004448 if (!RT)
4449 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004450
John McCall67da35c2010-02-04 22:26:26 +00004451 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004452
John McCall02db245d2010-08-18 09:41:07 +00004453 // We can't answer whether something is abstract until it has a
4454 // definition. If it's currently being defined, we'll walk back
4455 // over all the declarations when we have a full definition.
4456 const CXXRecordDecl *Def = RD->getDefinition();
4457 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00004458 return false;
4459
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004460 if (!RD->isAbstract())
4461 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004462
Douglas Gregorae298422012-05-04 17:09:59 +00004463 Diagnoser.diagnose(*this, Loc, T);
John McCall02db245d2010-08-18 09:41:07 +00004464 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00004465
John McCall02db245d2010-08-18 09:41:07 +00004466 return true;
4467}
4468
4469void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4470 // Check if we've already emitted the list of pure virtual functions
4471 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004472 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00004473 return;
Mike Stump11289f42009-09-09 15:08:12 +00004474
Richard Smithbc46e432013-07-22 02:56:56 +00004475 // If the diagnostic is suppressed, don't emit the notes. We're only
4476 // going to emit them once, so try to attach them to a diagnostic we're
4477 // actually going to show.
4478 if (Diags.isLastDiagnosticIgnored())
4479 return;
4480
Douglas Gregor4165bd62010-03-23 23:47:56 +00004481 CXXFinalOverriderMap FinalOverriders;
4482 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00004483
Anders Carlssona2f74f32010-06-03 01:00:02 +00004484 // Keep a set of seen pure methods so we won't diagnose the same method
4485 // more than once.
4486 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4487
Douglas Gregor4165bd62010-03-23 23:47:56 +00004488 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4489 MEnd = FinalOverriders.end();
4490 M != MEnd;
4491 ++M) {
4492 for (OverridingMethods::iterator SO = M->second.begin(),
4493 SOEnd = M->second.end();
4494 SO != SOEnd; ++SO) {
4495 // C++ [class.abstract]p4:
4496 // A class is abstract if it contains or inherits at least one
4497 // pure virtual function for which the final overrider is pure
4498 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00004499
Douglas Gregor4165bd62010-03-23 23:47:56 +00004500 //
4501 if (SO->second.size() != 1)
4502 continue;
4503
4504 if (!SO->second.front().Method->isPure())
4505 continue;
4506
David Blaikie82e95a32014-11-19 07:49:47 +00004507 if (!SeenPureMethods.insert(SO->second.front().Method).second)
Anders Carlssona2f74f32010-06-03 01:00:02 +00004508 continue;
4509
Douglas Gregor4165bd62010-03-23 23:47:56 +00004510 Diag(SO->second.front().Method->getLocation(),
4511 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00004512 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00004513 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004514 }
4515
4516 if (!PureVirtualClassDiagSet)
4517 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4518 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004519}
4520
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004521namespace {
John McCall02db245d2010-08-18 09:41:07 +00004522struct AbstractUsageInfo {
4523 Sema &S;
4524 CXXRecordDecl *Record;
4525 CanQualType AbstractType;
4526 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00004527
John McCall02db245d2010-08-18 09:41:07 +00004528 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4529 : S(S), Record(Record),
4530 AbstractType(S.Context.getCanonicalType(
4531 S.Context.getTypeDeclType(Record))),
4532 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004533
John McCall02db245d2010-08-18 09:41:07 +00004534 void DiagnoseAbstractType() {
4535 if (Invalid) return;
4536 S.DiagnoseAbstractType(Record);
4537 Invalid = true;
4538 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00004539
John McCall02db245d2010-08-18 09:41:07 +00004540 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4541};
4542
4543struct CheckAbstractUsage {
4544 AbstractUsageInfo &Info;
4545 const NamedDecl *Ctx;
4546
4547 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4548 : Info(Info), Ctx(Ctx) {}
4549
4550 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4551 switch (TL.getTypeLocClass()) {
4552#define ABSTRACT_TYPELOC(CLASS, PARENT)
4553#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00004554 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00004555#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004556 }
John McCall02db245d2010-08-18 09:41:07 +00004557 }
Mike Stump11289f42009-09-09 15:08:12 +00004558
John McCall02db245d2010-08-18 09:41:07 +00004559 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00004560 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004561 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4562 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00004563 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004564
4565 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00004566 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004567 }
John McCall02db245d2010-08-18 09:41:07 +00004568 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004569
John McCall02db245d2010-08-18 09:41:07 +00004570 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4571 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4572 }
Mike Stump11289f42009-09-09 15:08:12 +00004573
John McCall02db245d2010-08-18 09:41:07 +00004574 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4575 // Visit the type parameters from a permissive context.
4576 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4577 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4578 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4579 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4580 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4581 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004582 }
John McCall02db245d2010-08-18 09:41:07 +00004583 }
Mike Stump11289f42009-09-09 15:08:12 +00004584
John McCall02db245d2010-08-18 09:41:07 +00004585 // Visit pointee types from a permissive context.
4586#define CheckPolymorphic(Type) \
4587 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4588 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4589 }
4590 CheckPolymorphic(PointerTypeLoc)
4591 CheckPolymorphic(ReferenceTypeLoc)
4592 CheckPolymorphic(MemberPointerTypeLoc)
4593 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00004594 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00004595
John McCall02db245d2010-08-18 09:41:07 +00004596 /// Handle all the types we haven't given a more specific
4597 /// implementation for above.
4598 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4599 // Every other kind of type that we haven't called out already
4600 // that has an inner type is either (1) sugar or (2) contains that
4601 // inner type in some way as a subobject.
4602 if (TypeLoc Next = TL.getNextTypeLoc())
4603 return Visit(Next, Sel);
4604
4605 // If there's no inner type and we're in a permissive context,
4606 // don't diagnose.
4607 if (Sel == Sema::AbstractNone) return;
4608
4609 // Check whether the type matches the abstract type.
4610 QualType T = TL.getType();
4611 if (T->isArrayType()) {
4612 Sel = Sema::AbstractArrayType;
4613 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004614 }
John McCall02db245d2010-08-18 09:41:07 +00004615 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4616 if (CT != Info.AbstractType) return;
4617
4618 // It matched; do some magic.
4619 if (Sel == Sema::AbstractArrayType) {
4620 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4621 << T << TL.getSourceRange();
4622 } else {
4623 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4624 << Sel << T << TL.getSourceRange();
4625 }
4626 Info.DiagnoseAbstractType();
4627 }
4628};
4629
4630void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4631 Sema::AbstractDiagSelID Sel) {
4632 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4633}
4634
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004635}
John McCall02db245d2010-08-18 09:41:07 +00004636
4637/// Check for invalid uses of an abstract type in a method declaration.
4638static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4639 CXXMethodDecl *MD) {
4640 // No need to do the check on definitions, which require that
4641 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004642 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00004643 return;
4644
4645 // For safety's sake, just ignore it if we don't have type source
4646 // information. This should never happen for non-implicit methods,
4647 // but...
4648 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4649 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4650}
4651
4652/// Check for invalid uses of an abstract type within a class definition.
4653static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4654 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00004655 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00004656 if (D->isImplicit()) continue;
4657
4658 // Methods and method templates.
4659 if (isa<CXXMethodDecl>(D)) {
4660 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4661 } else if (isa<FunctionTemplateDecl>(D)) {
4662 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4663 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4664
4665 // Fields and static variables.
4666 } else if (isa<FieldDecl>(D)) {
4667 FieldDecl *FD = cast<FieldDecl>(D);
4668 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4669 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4670 } else if (isa<VarDecl>(D)) {
4671 VarDecl *VD = cast<VarDecl>(D);
4672 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4673 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4674
4675 // Nested classes and class templates.
4676 } else if (isa<CXXRecordDecl>(D)) {
4677 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4678 } else if (isa<ClassTemplateDecl>(D)) {
4679 CheckAbstractClassUsage(Info,
4680 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4681 }
4682 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004683}
4684
Hans Wennborg853ae942014-05-30 16:59:42 +00004685/// \brief Check class-level dllimport/dllexport attribute.
Hans Wennborg17f9b442015-05-27 00:06:45 +00004686void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
Hans Wennborg853ae942014-05-30 16:59:42 +00004687 Attr *ClassAttr = getDLLAttr(Class);
Hans Wennborg205c39b2014-08-23 22:34:43 +00004688
4689 // MSVC inherits DLL attributes to partial class template specializations.
Hans Wennborg17f9b442015-05-27 00:06:45 +00004690 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
Hans Wennborg205c39b2014-08-23 22:34:43 +00004691 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4692 if (Attr *TemplateAttr =
4693 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
Hans Wennborg17f9b442015-05-27 00:06:45 +00004694 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
Hans Wennborg205c39b2014-08-23 22:34:43 +00004695 A->setInherited(true);
4696 ClassAttr = A;
4697 }
4698 }
4699 }
4700
Hans Wennborg853ae942014-05-30 16:59:42 +00004701 if (!ClassAttr)
4702 return;
4703
Hans Wennborg8313c762014-11-03 16:09:16 +00004704 if (!Class->isExternallyVisible()) {
Hans Wennborg17f9b442015-05-27 00:06:45 +00004705 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
Hans Wennborg8313c762014-11-03 16:09:16 +00004706 << Class << ClassAttr;
4707 return;
4708 }
4709
Hans Wennborg17f9b442015-05-27 00:06:45 +00004710 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004711 !ClassAttr->isInherited()) {
4712 // Diagnose dll attributes on members of class with dll attribute.
4713 for (Decl *Member : Class->decls()) {
4714 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4715 continue;
4716 InheritableAttr *MemberAttr = getDLLAttr(Member);
4717 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4718 continue;
4719
Hans Wennborg17f9b442015-05-27 00:06:45 +00004720 Diag(MemberAttr->getLocation(),
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004721 diag::err_attribute_dll_member_of_dll_class)
4722 << MemberAttr << ClassAttr;
Hans Wennborg17f9b442015-05-27 00:06:45 +00004723 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004724 Member->setInvalidDecl();
4725 }
4726 }
4727
4728 if (Class->getDescribedClassTemplate())
4729 // Don't inherit dll attribute until the template is instantiated.
4730 return;
4731
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004732 // The class is either imported or exported.
4733 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4734 const bool ClassImported = !ClassExported;
Hans Wennborg853ae942014-05-30 16:59:42 +00004735
Hans Wennborgfd76d912015-01-15 21:18:30 +00004736 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
4737
Hans Wennborgbb1983c2015-06-09 00:39:03 +00004738 // Ignore explicit dllexport on explicit class template instantiation declarations.
4739 if (ClassExported && !ClassAttr->isInherited() &&
4740 TSK == TSK_ExplicitInstantiationDeclaration) {
Hans Wennborgfd76d912015-01-15 21:18:30 +00004741 Class->dropAttr<DLLExportAttr>();
4742 return;
4743 }
4744
Hans Wennborg853ae942014-05-30 16:59:42 +00004745 // Force declaration of implicit members so they can inherit the attribute.
Hans Wennborg17f9b442015-05-27 00:06:45 +00004746 ForceDeclarationOfImplicitMembers(Class);
Hans Wennborg853ae942014-05-30 16:59:42 +00004747
4748 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4749 // seem to be true in practice?
4750
Hans Wennborg853ae942014-05-30 16:59:42 +00004751 for (Decl *Member : Class->decls()) {
Hans Wennborge8ad3832014-06-11 22:44:39 +00004752 VarDecl *VD = dyn_cast<VarDecl>(Member);
4753 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4754
4755 // Only methods and static fields inherit the attributes.
4756 if (!VD && !MD)
Hans Wennborg853ae942014-05-30 16:59:42 +00004757 continue;
Hans Wennborge8ad3832014-06-11 22:44:39 +00004758
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004759 if (MD) {
4760 // Don't process deleted methods.
4761 if (MD->isDeleted())
4762 continue;
Hans Wennborg853ae942014-05-30 16:59:42 +00004763
David Majnemer30f058a2015-05-11 03:00:22 +00004764 if (MD->isInlined()) {
Hans Wennborg97cbed42015-02-19 22:39:24 +00004765 // MinGW does not import or export inline methods.
Hans Wennborg17f9b442015-05-27 00:06:45 +00004766 if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
David Majnemer30f058a2015-05-11 03:00:22 +00004767 continue;
4768
4769 // MSVC versions before 2015 don't export the move assignment operators,
4770 // so don't attempt to import them if we have a definition.
4771 if (ClassImported && MD->isMoveAssignmentOperator() &&
Hans Wennborg17f9b442015-05-27 00:06:45 +00004772 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
David Majnemer30f058a2015-05-11 03:00:22 +00004773 continue;
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004774 }
Hans Wennborge8ad3832014-06-11 22:44:39 +00004775 }
4776
Hans Wennborg287231c2015-04-22 04:05:17 +00004777 if (!cast<NamedDecl>(Member)->isExternallyVisible())
4778 continue;
4779
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004780 if (!getDLLAttr(Member)) {
Hans Wennborg496524b2014-05-31 02:08:49 +00004781 auto *NewAttr =
Hans Wennborg17f9b442015-05-27 00:06:45 +00004782 cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
Hans Wennborg496524b2014-05-31 02:08:49 +00004783 NewAttr->setInherited(true);
4784 Member->addAttr(NewAttr);
4785 }
Hans Wennborg853ae942014-05-30 16:59:42 +00004786
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004787 if (MD && ClassExported) {
Hans Wennborgbb1983c2015-06-09 00:39:03 +00004788 if (TSK == TSK_ExplicitInstantiationDeclaration)
4789 // Don't go any further if this is just an explicit instantiation
4790 // declaration.
4791 continue;
4792
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004793 if (MD->isUserProvided()) {
Hans Wennborg45810b42014-12-16 01:15:01 +00004794 // Instantiate non-default class member functions ...
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004795
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004796 // .. except for certain kinds of template specializations.
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004797 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4798 continue;
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004799
Hans Wennborg17f9b442015-05-27 00:06:45 +00004800 MarkFunctionReferenced(Class->getLocation(), MD);
Hans Wennborg45810b42014-12-16 01:15:01 +00004801
4802 // The function will be passed to the consumer when its definition is
4803 // encountered.
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004804 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4805 MD->isCopyAssignmentOperator() ||
4806 MD->isMoveAssignmentOperator()) {
Hans Wennborg45810b42014-12-16 01:15:01 +00004807 // Synthesize and instantiate non-trivial implicit methods, explicitly
4808 // defaulted methods, and the copy and move assignment operators. The
4809 // latter are exported even if they are trivial, because the address of
4810 // an operator can be taken and should compare equal accross libraries.
Hans Wennborg17f9b442015-05-27 00:06:45 +00004811 DiagnosticErrorTrap Trap(Diags);
4812 MarkFunctionReferenced(Class->getLocation(), MD);
Hans Wennborg58703732015-02-21 01:07:24 +00004813 if (Trap.hasErrorOccurred()) {
Hans Wennborg17f9b442015-05-27 00:06:45 +00004814 Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
4815 << Class->getName() << !getLangOpts().CPlusPlus11;
Hans Wennborg58703732015-02-21 01:07:24 +00004816 break;
4817 }
Hans Wennborg45810b42014-12-16 01:15:01 +00004818
4819 // There is no later point when we will see the definition of this
4820 // function, so pass it to the consumer now.
Hans Wennborg17f9b442015-05-27 00:06:45 +00004821 Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
Hans Wennborg853ae942014-05-30 16:59:42 +00004822 }
4823 }
4824 }
4825}
4826
Hans Wennborgfce87ca2015-06-09 00:39:09 +00004827/// \brief Perform propagation of DLL attributes from a derived class to a
4828/// templated base class for MS compatibility.
4829void Sema::propagateDLLAttrToBaseClassTemplate(
4830 CXXRecordDecl *Class, Attr *ClassAttr,
4831 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
4832 if (getDLLAttr(
4833 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
4834 // If the base class template has a DLL attribute, don't try to change it.
4835 return;
4836 }
4837
4838 auto TSK = BaseTemplateSpec->getSpecializationKind();
4839 if (!getDLLAttr(BaseTemplateSpec) &&
4840 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
4841 TSK == TSK_ImplicitInstantiation)) {
4842 // The template hasn't been instantiated yet (or it has, but only as an
4843 // explicit instantiation declaration or implicit instantiation, which means
4844 // we haven't codegenned any members yet), so propagate the attribute.
4845 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
4846 NewAttr->setInherited(true);
4847 BaseTemplateSpec->addAttr(NewAttr);
4848
4849 // If the template is already instantiated, checkDLLAttributeRedeclaration()
4850 // needs to be run again to work see the new attribute. Otherwise this will
4851 // get run whenever the template is instantiated.
4852 if (TSK != TSK_Undeclared)
4853 checkClassLevelDLLAttribute(BaseTemplateSpec);
4854
4855 return;
4856 }
4857
4858 if (getDLLAttr(BaseTemplateSpec)) {
4859 // The template has already been specialized or instantiated with an
4860 // attribute, explicitly or through propagation. We should not try to change
4861 // it.
4862 return;
4863 }
4864
4865 // The template was previously instantiated or explicitly specialized without
4866 // a dll attribute, It's too late for us to add an attribute, so warn that
4867 // this is unsupported.
4868 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
4869 << BaseTemplateSpec->isExplicitSpecialization();
4870 Diag(ClassAttr->getLocation(), diag::note_attribute);
4871 if (BaseTemplateSpec->isExplicitSpecialization()) {
4872 Diag(BaseTemplateSpec->getLocation(),
4873 diag::note_template_class_explicit_specialization_was_here)
4874 << BaseTemplateSpec;
4875 } else {
4876 Diag(BaseTemplateSpec->getPointOfInstantiation(),
4877 diag::note_template_class_instantiation_was_here)
4878 << BaseTemplateSpec;
4879 }
4880}
4881
Douglas Gregorc99f1552009-12-03 18:33:45 +00004882/// \brief Perform semantic checks on a class definition that has been
4883/// completing, introducing implicitly-declared members, checking for
4884/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004885void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00004886 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00004887 return;
4888
John McCall02db245d2010-08-18 09:41:07 +00004889 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4890 AbstractUsageInfo Info(*this, Record);
4891 CheckAbstractClassUsage(Info, Record);
4892 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00004893
4894 // If this is not an aggregate type and has no user-declared constructor,
4895 // complain about any non-static data members of reference or const scalar
4896 // type, since they will never get initializers.
4897 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00004898 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4899 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004900 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004901 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004902 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004903 continue;
4904
Douglas Gregor454a5b62010-04-15 00:00:53 +00004905 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00004906 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004907 if (!Complained) {
4908 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4909 << Record->getTagKind() << Record;
4910 Complained = true;
4911 }
4912
4913 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4914 << F->getType()->isReferenceType()
4915 << F->getDeclName();
4916 }
4917 }
4918 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004919
Douglas Gregor36c22a22010-10-15 13:21:21 +00004920 if (Record->getIdentifier()) {
4921 // C++ [class.mem]p13:
4922 // If T is the name of a class, then each of the following shall have a
4923 // name different from T:
4924 // - every member of every anonymous union that is a member of class T.
4925 //
4926 // C++ [class.mem]p14:
4927 // In addition, if class T has a user-declared constructor (12.1), every
4928 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00004929 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4930 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4931 ++I) {
4932 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004933 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4934 isa<IndirectFieldDecl>(D)) {
4935 Diag(D->getLocation(), diag::err_member_name_of_class)
4936 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00004937 break;
4938 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00004939 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00004940 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004941
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004942 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00004943 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004944 CXXDestructorDecl *dtor = Record->getDestructor();
David Blaikie04e2e662014-05-09 22:02:28 +00004945 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4946 !Record->hasAttr<FinalAttr>())
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004947 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4948 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4949 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004950
David Majnemera5433082013-10-18 00:33:31 +00004951 if (Record->isAbstract()) {
4952 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4953 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4954 << FA->isSpelledAsSealed();
4955 DiagnoseAbstractType(Record);
4956 }
David Blaikie348df502012-09-21 03:21:07 +00004957 }
4958
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004959 bool HasMethodWithOverrideControl = false,
4960 HasOverridingMethodWithoutOverrideControl = false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004961 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004962 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00004963 // See if a method overloads virtual methods in a base
4964 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004965 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004966 DiagnoseHiddenVirtualMethods(M);
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004967 if (M->hasAttr<OverrideAttr>())
4968 HasMethodWithOverrideControl = true;
4969 else if (M->size_overridden_methods() > 0)
4970 HasOverridingMethodWithoutOverrideControl = true;
Richard Smithbd305122012-12-11 01:14:52 +00004971 // Check whether the explicitly-defaulted special members are valid.
4972 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004973 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004974
4975 // For an explicitly defaulted or deleted special member, we defer
4976 // determining triviality until the class is complete. That time is now!
4977 if (!M->isImplicit() && !M->isUserProvided()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004978 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004979 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004980 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00004981
4982 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00004983 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004984 }
4985 }
4986 }
4987 }
4988
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004989 if (HasMethodWithOverrideControl &&
4990 HasOverridingMethodWithoutOverrideControl) {
4991 // At least one method has the 'override' control declared.
4992 // Diagnose all other overridden methods which do not have 'override' specified on them.
4993 for (auto *M : Record->methods())
4994 DiagnoseAbsenceOfOverrideControl(M);
4995 }
Sebastian Redl08905022011-02-05 19:23:19 +00004996
John McCall95833f32014-02-27 20:30:49 +00004997 // ms_struct is a request to use the same ABI rules as MSVC. Check
4998 // whether this class uses any C++ features that are implemented
4999 // completely differently in MSVC, and if so, emit a diagnostic.
5000 // That diagnostic defaults to an error, but we allow projects to
5001 // map it down to a warning (or ignore it). It's a fairly common
5002 // practice among users of the ms_struct pragma to mass-annotate
5003 // headers, sweeping up a bunch of types that the project doesn't
5004 // really rely on MSVC-compatible layout for. We must therefore
5005 // support "ms_struct except for C++ stuff" as a secondary ABI.
5006 if (Record->isMsStruct(Context) &&
5007 (Record->isPolymorphic() || Record->getNumBases())) {
5008 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00005009 }
5010
Richard Smithc2bc61b2013-03-18 21:12:30 +00005011 // Declare inheriting constructors. We do this eagerly here because:
5012 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redl08905022011-02-05 19:23:19 +00005013 // constructors from different classes.
5014 // - The lazy declaration of the other implicit constructors is so as to not
5015 // waste space and performance on classes that are not meant to be
5016 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smithc2bc61b2013-03-18 21:12:30 +00005017 // have inheriting constructors.
5018 DeclareInheritingConstructors(Record);
Hans Wennborg853ae942014-05-30 16:59:42 +00005019
Hans Wennborg17f9b442015-05-27 00:06:45 +00005020 checkClassLevelDLLAttribute(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005021}
5022
Richard Smith41c35d62013-11-27 03:39:20 +00005023/// Look up the special member function that would be called by a special
5024/// member function for a subobject of class type.
5025///
5026/// \param Class The class type of the subobject.
5027/// \param CSM The kind of special member function.
5028/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5029/// \param ConstRHS True if this is a copy operation with a const object
5030/// on its RHS, that is, if the argument to the outer special member
5031/// function is 'const' and this is not a field marked 'mutable'.
5032static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
5033 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5034 unsigned FieldQuals, bool ConstRHS) {
5035 unsigned LHSQuals = 0;
5036 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5037 LHSQuals = FieldQuals;
5038
5039 unsigned RHSQuals = FieldQuals;
5040 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5041 RHSQuals = 0;
5042 else if (ConstRHS)
5043 RHSQuals |= Qualifiers::Const;
5044
5045 return S.LookupSpecialMember(Class, CSM,
5046 RHSQuals & Qualifiers::Const,
5047 RHSQuals & Qualifiers::Volatile,
5048 false,
5049 LHSQuals & Qualifiers::Const,
5050 LHSQuals & Qualifiers::Volatile);
5051}
5052
Richard Smithb5800092012-06-10 05:43:50 +00005053/// Is the special member function which would be selected to perform the
5054/// specified operation on the specified class type a constexpr constructor?
5055static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5056 Sema::CXXSpecialMember CSM,
Richard Smith41c35d62013-11-27 03:39:20 +00005057 unsigned Quals, bool ConstRHS) {
Richard Smithb5800092012-06-10 05:43:50 +00005058 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005059 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00005060 if (!SMOR || !SMOR->getMethod())
5061 // A constructor we wouldn't select can't be "involved in initializing"
5062 // anything.
5063 return true;
5064 return SMOR->getMethod()->isConstexpr();
5065}
5066
5067/// Determine whether the specified special member function would be constexpr
5068/// if it were implicitly defined.
5069static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5070 Sema::CXXSpecialMember CSM,
5071 bool ConstArg) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005072 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00005073 return false;
5074
5075 // C++11 [dcl.constexpr]p4:
5076 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00005077 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00005078 switch (CSM) {
5079 case Sema::CXXDefaultConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00005080 // Since default constructor lookup is essentially trivial (and cannot
5081 // involve, for instance, template instantiation), we compute whether a
5082 // defaulted default constructor is constexpr directly within CXXRecordDecl.
5083 //
5084 // This is important for performance; we need to know whether the default
5085 // constructor is constexpr to determine whether the type is a literal type.
5086 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
5087
Richard Smithb5800092012-06-10 05:43:50 +00005088 case Sema::CXXCopyConstructor:
5089 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00005090 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00005091 break;
5092
5093 case Sema::CXXCopyAssignment:
5094 case Sema::CXXMoveAssignment:
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005095 if (!S.getLangOpts().CPlusPlus14)
Richard Smith99005e62013-05-07 03:19:20 +00005096 return false;
5097 // In C++1y, we need to perform overload resolution.
5098 Ctor = false;
5099 break;
5100
Richard Smithb5800092012-06-10 05:43:50 +00005101 case Sema::CXXDestructor:
5102 case Sema::CXXInvalid:
5103 return false;
5104 }
5105
5106 // -- if the class is a non-empty union, or for each non-empty anonymous
5107 // union member of a non-union class, exactly one non-static data member
5108 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00005109 //
5110 // If we squint, this is guaranteed, since exactly one non-static data member
5111 // will be initialized (if the constructor isn't deleted), we just don't know
5112 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00005113 if (Ctor && ClassDecl->isUnion())
Richard Smith4086a132012-06-10 07:07:24 +00005114 return true;
Richard Smithb5800092012-06-10 05:43:50 +00005115
5116 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00005117 if (Ctor && ClassDecl->getNumVBases())
5118 return false;
5119
5120 // C++1y [class.copy]p26:
5121 // -- [the class] is a literal type, and
5122 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00005123 return false;
5124
5125 // -- every constructor involved in initializing [...] base class
5126 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00005127 // -- the assignment operator selected to copy/move each direct base
5128 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00005129 for (const auto &B : ClassDecl->bases()) {
5130 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00005131 if (!BaseType) continue;
5132
5133 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00005134 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smithb5800092012-06-10 05:43:50 +00005135 return false;
5136 }
5137
5138 // -- every constructor involved in initializing non-static data members
5139 // [...] shall be a constexpr constructor;
5140 // -- every non-static data member and base class sub-object shall be
5141 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00005142 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00005143 // thereof), the assignment operator selected to copy/move that member is
5144 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005145 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00005146 if (F->isInvalidDecl())
5147 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00005148 QualType BaseType = S.Context.getBaseElementType(F->getType());
5149 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00005150 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00005151 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
5152 BaseType.getCVRQualifiers(),
5153 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00005154 return false;
Richard Smithb5800092012-06-10 05:43:50 +00005155 }
5156 }
5157
5158 // All OK, it's constexpr!
5159 return true;
5160}
5161
Richard Smithd3b5c9082012-07-27 04:22:15 +00005162static Sema::ImplicitExceptionSpecification
5163computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
5164 switch (S.getSpecialMember(MD)) {
5165 case Sema::CXXDefaultConstructor:
5166 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
5167 case Sema::CXXCopyConstructor:
5168 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
5169 case Sema::CXXCopyAssignment:
5170 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
5171 case Sema::CXXMoveConstructor:
5172 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
5173 case Sema::CXXMoveAssignment:
5174 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
5175 case Sema::CXXDestructor:
5176 return S.ComputeDefaultedDtorExceptionSpec(MD);
5177 case Sema::CXXInvalid:
5178 break;
5179 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00005180 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
5181 "only special members have implicit exception specs");
5182 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00005183}
5184
Reid Kleckner78af0702013-08-27 23:08:25 +00005185static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
5186 CXXMethodDecl *MD) {
5187 FunctionProtoType::ExtProtoInfo EPI;
5188
5189 // Build an exception specification pointing back at this member.
Richard Smith8acb4282014-07-31 21:57:55 +00005190 EPI.ExceptionSpec.Type = EST_Unevaluated;
5191 EPI.ExceptionSpec.SourceDecl = MD;
Reid Kleckner78af0702013-08-27 23:08:25 +00005192
5193 // Set the calling convention to the default for C++ instance methods.
5194 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
5195 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5196 /*IsCXXMethod=*/true));
5197 return EPI;
5198}
5199
Richard Smithd3b5c9082012-07-27 04:22:15 +00005200void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
5201 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
5202 if (FPT->getExceptionSpecType() != EST_Unevaluated)
5203 return;
5204
Richard Smith7f782272012-07-30 23:48:14 +00005205 // Evaluate the exception specification.
Richard Smith8acb4282014-07-31 21:57:55 +00005206 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
Richard Smith564417a2014-03-20 21:47:22 +00005207
Richard Smith7f782272012-07-30 23:48:14 +00005208 // Update the type of the special member to use it.
Richard Smith8acb4282014-07-31 21:57:55 +00005209 UpdateExceptionSpec(MD, ESI);
Richard Smith7f782272012-07-30 23:48:14 +00005210
5211 // A user-provided destructor can be defined outside the class. When that
5212 // happens, be sure to update the exception specification on both
5213 // declarations.
5214 const FunctionProtoType *CanonicalFPT =
5215 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
5216 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smith8acb4282014-07-31 21:57:55 +00005217 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00005218}
5219
Richard Smithb9e90b12012-05-15 04:39:51 +00005220void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
5221 CXXRecordDecl *RD = MD->getParent();
5222 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005223
Richard Smithb9e90b12012-05-15 04:39:51 +00005224 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
5225 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00005226
5227 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00005228 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00005229 bool First = MD == MD->getCanonicalDecl();
5230
5231 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00005232
5233 // C++11 [dcl.fct.def.default]p1:
5234 // A function that is explicitly defaulted shall
5235 // -- be a special member function (checked elsewhere),
5236 // -- have the same type (except for ref-qualifiers, and except that a
5237 // copy operation can take a non-const reference) as an implicit
5238 // declaration, and
5239 // -- not have default arguments.
5240 unsigned ExpectedParams = 1;
5241 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
5242 ExpectedParams = 0;
5243 if (MD->getNumParams() != ExpectedParams) {
5244 // This also checks for default arguments: a copy or move constructor with a
5245 // default argument is classified as a default constructor, and assignment
5246 // operations and destructors can't have default arguments.
5247 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
5248 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00005249 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00005250 } else if (MD->isVariadic()) {
5251 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
5252 << CSM << MD->getSourceRange();
5253 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00005254 }
5255
Richard Smithb9e90b12012-05-15 04:39:51 +00005256 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00005257
Richard Smithb5800092012-06-10 05:43:50 +00005258 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00005259 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00005260 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00005261 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00005262 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00005263
Richard Smithb9e90b12012-05-15 04:39:51 +00005264 QualType ReturnType = Context.VoidTy;
5265 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
5266 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00005267 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00005268 QualType ExpectedReturnType =
5269 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
5270 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
5271 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
5272 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
5273 HadError = true;
5274 }
5275
5276 // A defaulted special member cannot have cv-qualifiers.
5277 if (Type->getTypeQuals()) {
5278 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005279 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
Richard Smithb9e90b12012-05-15 04:39:51 +00005280 HadError = true;
5281 }
5282 }
5283
5284 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00005285 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00005286 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00005287 if (ExpectedParams && ArgType->isReferenceType()) {
5288 // Argument must be reference to possibly-const T.
5289 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00005290 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00005291
5292 if (ReferentType.isVolatileQualified()) {
5293 Diag(MD->getLocation(),
5294 diag::err_defaulted_special_member_volatile_param) << CSM;
5295 HadError = true;
5296 }
5297
Richard Smithb5800092012-06-10 05:43:50 +00005298 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00005299 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
5300 Diag(MD->getLocation(),
5301 diag::err_defaulted_special_member_copy_const_param)
5302 << (CSM == CXXCopyAssignment);
5303 // FIXME: Explain why this special member can't be const.
5304 } else {
5305 Diag(MD->getLocation(),
5306 diag::err_defaulted_special_member_move_const_param)
5307 << (CSM == CXXMoveAssignment);
5308 }
5309 HadError = true;
5310 }
Richard Smithb9e90b12012-05-15 04:39:51 +00005311 } else if (ExpectedParams) {
5312 // A copy assignment operator can take its argument by value, but a
5313 // defaulted one cannot.
5314 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00005315 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00005316 HadError = true;
5317 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00005318
Richard Smithcc36f692011-12-22 02:22:31 +00005319 // C++11 [dcl.fct.def.default]p2:
5320 // An explicitly-defaulted function may be declared constexpr only if it
5321 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00005322 // Do not apply this rule to members of class templates, since core issue 1358
5323 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00005324 // functions which cannot be constexpr (for non-constructors in C++11 and for
5325 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00005326 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5327 HasConstParam);
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005328 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
Richard Smith99005e62013-05-07 03:19:20 +00005329 : isa<CXXConstructorDecl>(MD)) &&
5330 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00005331 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5332 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00005333 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00005334 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00005335 }
Richard Smithbd305122012-12-11 01:14:52 +00005336
Richard Smithcc36f692011-12-22 02:22:31 +00005337 // and may have an explicit exception-specification only if it is compatible
5338 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00005339 if (Type->hasExceptionSpec()) {
5340 // Delay the check if this is the first declaration of the special member,
5341 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00005342 if (First) {
5343 // If the exception specification needs to be instantiated, do so now,
5344 // before we clobber it with an EST_Unevaluated specification below.
5345 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5346 InstantiateExceptionSpec(MD->getLocStart(), MD);
5347 Type = MD->getType()->getAs<FunctionProtoType>();
5348 }
Richard Smithbd305122012-12-11 01:14:52 +00005349 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00005350 } else
Richard Smithbd305122012-12-11 01:14:52 +00005351 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5352 }
Richard Smithcc36f692011-12-22 02:22:31 +00005353
5354 // If a function is explicitly defaulted on its first declaration,
5355 if (First) {
5356 // -- it is implicitly considered to be constexpr if the implicit
5357 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00005358 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00005359
Richard Smithb9e90b12012-05-15 04:39:51 +00005360 // -- it is implicitly considered to have the same exception-specification
5361 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00005362 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00005363 EPI.ExceptionSpec.Type = EST_Unevaluated;
5364 EPI.ExceptionSpec.SourceDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00005365 MD->setType(Context.getFunctionType(ReturnType,
Craig Topper5fc8fc22014-08-27 06:28:36 +00005366 llvm::makeArrayRef(&ArgType,
Jordan Rose5c382722013-03-08 21:51:21 +00005367 ExpectedParams),
5368 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00005369 }
5370
Richard Smithb9e90b12012-05-15 04:39:51 +00005371 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00005372 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00005373 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00005374 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00005375 // C++11 [dcl.fct.def.default]p4:
5376 // [For a] user-provided explicitly-defaulted function [...] if such a
5377 // function is implicitly defined as deleted, the program is ill-formed.
5378 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith566184a2014-01-22 20:09:10 +00005379 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00005380 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00005381 }
5382 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00005383
Richard Smithb9e90b12012-05-15 04:39:51 +00005384 if (HadError)
5385 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00005386}
5387
Richard Smithbd305122012-12-11 01:14:52 +00005388/// Check whether the exception specification provided for an
5389/// explicitly-defaulted special member matches the exception specification
5390/// that would have been generated for an implicit special member, per
5391/// C++11 [dcl.fct.def.default]p2.
5392void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5393 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
Richard Smith0b3a4622014-11-13 20:01:57 +00005394 // If the exception specification was explicitly specified but hadn't been
5395 // parsed when the method was defaulted, grab it now.
5396 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
5397 SpecifiedType =
5398 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
5399
Richard Smithbd305122012-12-11 01:14:52 +00005400 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00005401 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5402 /*IsCXXMethod=*/true);
5403 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smith8acb4282014-07-31 21:57:55 +00005404 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5405 .getExceptionSpec();
Richard Smithbd305122012-12-11 01:14:52 +00005406 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005407 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00005408
5409 // Ensure that it matches.
5410 CheckEquivalentExceptionSpec(
5411 PDiag(diag::err_incorrect_defaulted_exception_spec)
5412 << getSpecialMember(MD), PDiag(),
5413 ImplicitType, SourceLocation(),
5414 SpecifiedType, MD->getLocation());
5415}
5416
Alp Tokerae3a9442013-10-18 05:54:19 +00005417void Sema::CheckDelayedMemberExceptionSpecs() {
Richard Smith88f45492014-11-22 03:09:05 +00005418 decltype(DelayedExceptionSpecChecks) Checks;
5419 decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
Richard Smithbd305122012-12-11 01:14:52 +00005420
Richard Smith88f45492014-11-22 03:09:05 +00005421 std::swap(Checks, DelayedExceptionSpecChecks);
Alp Tokerae3a9442013-10-18 05:54:19 +00005422 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5423
5424 // Perform any deferred checking of exception specifications for virtual
5425 // destructors.
Richard Smith88f45492014-11-22 03:09:05 +00005426 for (auto &Check : Checks)
5427 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
Alp Tokerae3a9442013-10-18 05:54:19 +00005428
5429 // Check that any explicitly-defaulted methods have exception specifications
5430 // compatible with their implicit exception specifications.
Richard Smith88f45492014-11-22 03:09:05 +00005431 for (auto &Spec : Specs)
5432 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
Richard Smithbd305122012-12-11 01:14:52 +00005433}
5434
Richard Smithd951a1d2012-02-18 02:02:13 +00005435namespace {
5436struct SpecialMemberDeletionInfo {
5437 Sema &S;
5438 CXXMethodDecl *MD;
5439 Sema::CXXSpecialMember CSM;
Richard Smith852265f2012-03-30 20:53:28 +00005440 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00005441
5442 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00005443 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00005444 SourceLocation Loc;
5445
5446 bool AllFieldsAreConst;
5447
5448 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith852265f2012-03-30 20:53:28 +00005449 Sema::CXXSpecialMember CSM, bool Diagnose)
5450 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smithd951a1d2012-02-18 02:02:13 +00005451 IsConstructor(false), IsAssignment(false), IsMove(false),
Richard Smith41c35d62013-11-27 03:39:20 +00005452 ConstArg(false), Loc(MD->getLocation()),
Richard Smithd951a1d2012-02-18 02:02:13 +00005453 AllFieldsAreConst(true) {
5454 switch (CSM) {
5455 case Sema::CXXDefaultConstructor:
5456 case Sema::CXXCopyConstructor:
5457 IsConstructor = true;
5458 break;
5459 case Sema::CXXMoveConstructor:
5460 IsConstructor = true;
5461 IsMove = true;
5462 break;
5463 case Sema::CXXCopyAssignment:
5464 IsAssignment = true;
5465 break;
5466 case Sema::CXXMoveAssignment:
5467 IsAssignment = true;
5468 IsMove = true;
5469 break;
5470 case Sema::CXXDestructor:
5471 break;
5472 case Sema::CXXInvalid:
5473 llvm_unreachable("invalid special member kind");
5474 }
5475
5476 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00005477 if (const ReferenceType *RT =
5478 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5479 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00005480 }
5481 }
5482
5483 bool inUnion() const { return MD->getParent()->isUnion(); }
5484
5485 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00005486 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00005487 unsigned Quals, bool IsMutable) {
5488 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5489 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00005490 }
5491
Richard Smith852265f2012-03-30 20:53:28 +00005492 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00005493
Richard Smith852265f2012-03-30 20:53:28 +00005494 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00005495 bool shouldDeleteForField(FieldDecl *FD);
5496 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00005497
Richard Smithaf136f82012-07-18 03:51:16 +00005498 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5499 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00005500 bool shouldDeleteForSubobjectCall(Subobject Subobj,
5501 Sema::SpecialMemberOverloadResult *SMOR,
5502 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00005503
5504 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00005505};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005506}
Richard Smithd951a1d2012-02-18 02:02:13 +00005507
John McCalld4274212012-04-09 20:53:23 +00005508/// Is the given special member inaccessible when used on the given
5509/// sub-object.
5510bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5511 CXXMethodDecl *target) {
5512 /// If we're operating on a base class, the object type is the
5513 /// type of this special member.
5514 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005515 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00005516 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5517 objectTy = S.Context.getTypeDeclType(MD->getParent());
5518 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5519
5520 // If we're operating on a field, the object type is the type of the field.
5521 } else {
5522 objectTy = S.Context.getTypeDeclType(target->getParent());
5523 }
5524
5525 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5526}
5527
Richard Smith852265f2012-03-30 20:53:28 +00005528/// Check whether we should delete a special member due to the implicit
5529/// definition containing a call to a special member of a subobject.
5530bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5531 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5532 bool IsDtorCallInCtor) {
5533 CXXMethodDecl *Decl = SMOR->getMethod();
5534 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5535
5536 int DiagKind = -1;
5537
5538 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5539 DiagKind = !Decl ? 0 : 1;
5540 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5541 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00005542 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00005543 DiagKind = 3;
5544 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5545 !Decl->isTrivial()) {
5546 // A member of a union must have a trivial corresponding special member.
5547 // As a weird special case, a destructor call from a union's constructor
5548 // must be accessible and non-deleted, but need not be trivial. Such a
5549 // destructor is never actually called, but is semantically checked as
5550 // if it were.
5551 DiagKind = 4;
5552 }
5553
5554 if (DiagKind == -1)
5555 return false;
5556
5557 if (Diagnose) {
5558 if (Field) {
5559 S.Diag(Field->getLocation(),
5560 diag::note_deleted_special_member_class_subobject)
5561 << CSM << MD->getParent() << /*IsField*/true
5562 << Field << DiagKind << IsDtorCallInCtor;
5563 } else {
5564 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5565 S.Diag(Base->getLocStart(),
5566 diag::note_deleted_special_member_class_subobject)
5567 << CSM << MD->getParent() << /*IsField*/false
5568 << Base->getType() << DiagKind << IsDtorCallInCtor;
5569 }
5570
5571 if (DiagKind == 1)
5572 S.NoteDeletedFunction(Decl);
5573 // FIXME: Explain inaccessibility if DiagKind == 3.
5574 }
5575
5576 return true;
5577}
5578
Richard Smith921bd202012-02-26 09:11:52 +00005579/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00005580/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00005581bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00005582 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00005583 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00005584 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00005585
5586 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00005587 // -- any direct or virtual base class, or non-static data member with no
5588 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00005589 // either M has no default constructor or overload resolution as applied
5590 // to M's default constructor results in an ambiguity or in a function
5591 // that is deleted or inaccessible
5592 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5593 // -- a direct or virtual base class B that cannot be copied/moved because
5594 // overload resolution, as applied to B's corresponding special member,
5595 // results in an ambiguity or a function that is deleted or inaccessible
5596 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00005597 // C++11 [class.dtor]p5:
5598 // -- any direct or virtual base class [...] has a type with a destructor
5599 // that is deleted or inaccessible
5600 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005601 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00005602 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5603 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005604 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005605
Richard Smith852265f2012-03-30 20:53:28 +00005606 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5607 // -- any direct or virtual base class or non-static data member has a
5608 // type with a destructor that is deleted or inaccessible
5609 if (IsConstructor) {
5610 Sema::SpecialMemberOverloadResult *SMOR =
5611 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5612 false, false, false, false, false);
5613 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5614 return true;
5615 }
5616
Richard Smith921bd202012-02-26 09:11:52 +00005617 return false;
5618}
5619
5620/// Check whether we should delete a special member function due to the class
5621/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00005622bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005623 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smithaf136f82012-07-18 03:51:16 +00005624 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00005625}
5626
5627/// Check whether we should delete a special member function due to the class
5628/// having a particular non-static data member.
5629bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5630 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5631 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5632
5633 if (CSM == Sema::CXXDefaultConstructor) {
5634 // For a default constructor, all references must be initialized in-class
5635 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00005636 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5637 if (Diagnose)
5638 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5639 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005640 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005641 }
Richard Smith619ecdc2012-02-27 06:07:25 +00005642 // C++11 [class.ctor]p5: any non-variant non-static data member of
5643 // const-qualified type (or array thereof) with no
5644 // brace-or-equal-initializer does not have a user-provided default
5645 // constructor.
5646 if (!inUnion() && FieldType.isConstQualified() &&
5647 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00005648 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5649 if (Diagnose)
5650 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005651 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00005652 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005653 }
5654
5655 if (inUnion() && !FieldType.isConstQualified())
5656 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005657 } else if (CSM == Sema::CXXCopyConstructor) {
5658 // For a copy constructor, data members must not be of rvalue reference
5659 // type.
Richard Smith852265f2012-03-30 20:53:28 +00005660 if (FieldType->isRValueReferenceType()) {
5661 if (Diagnose)
5662 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5663 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00005664 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005665 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005666 } else if (IsAssignment) {
5667 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00005668 if (FieldType->isReferenceType()) {
5669 if (Diagnose)
5670 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5671 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005672 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005673 }
5674 if (!FieldRecord && FieldType.isConstQualified()) {
5675 // C++11 [class.copy]p23:
5676 // -- a non-static data member of const non-class type (or array thereof)
5677 if (Diagnose)
5678 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005679 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00005680 return true;
5681 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005682 }
5683
5684 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005685 // Some additional restrictions exist on the variant members.
5686 if (!inUnion() && FieldRecord->isUnion() &&
5687 FieldRecord->isAnonymousStructOrUnion()) {
5688 bool AllVariantFieldsAreConst = true;
5689
Richard Smith5704fe82012-03-29 19:00:10 +00005690 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005691 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005692 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00005693
5694 if (!UnionFieldType.isConstQualified())
5695 AllVariantFieldsAreConst = false;
5696
Richard Smith921bd202012-02-26 09:11:52 +00005697 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5698 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005699 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00005700 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00005701 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005702 }
5703
5704 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00005705 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005706 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005707 if (Diagnose)
5708 S.Diag(FieldRecord->getLocation(),
5709 diag::note_deleted_default_ctor_all_const)
5710 << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00005711 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005712 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005713
Richard Smith5704fe82012-03-29 19:00:10 +00005714 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00005715 // This is technically non-conformant, but sanity demands it.
5716 return false;
5717 }
5718
Richard Smithaf136f82012-07-18 03:51:16 +00005719 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5720 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00005721 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005722 }
5723
5724 return false;
5725}
5726
5727/// C++11 [class.ctor] p5:
5728/// A defaulted default constructor for a class X is defined as deleted if
5729/// X is a union and all of its variant members are of const-qualified type.
5730bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00005731 // This is a silly definition, because it gives an empty union a deleted
5732 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00005733 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005734 !MD->getParent()->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005735 if (Diagnose)
5736 S.Diag(MD->getParent()->getLocation(),
5737 diag::note_deleted_default_ctor_all_const)
5738 << MD->getParent() << /*not anonymous union*/0;
5739 return true;
5740 }
5741 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005742}
5743
5744/// Determine whether a defaulted special member function should be defined as
5745/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5746/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00005747bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5748 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00005749 if (MD->isInvalidDecl())
5750 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00005751 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00005752 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005753 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00005754 return false;
5755
Richard Smithd951a1d2012-02-18 02:02:13 +00005756 // C++11 [expr.lambda.prim]p19:
5757 // The closure type associated with a lambda-expression has a
5758 // deleted (8.4.3) default constructor and a deleted copy
5759 // assignment operator.
5760 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00005761 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5762 if (Diagnose)
5763 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00005764 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005765 }
5766
Richard Smith6f1e2c62012-04-02 20:59:25 +00005767 // For an anonymous struct or union, the copy and assignment special members
5768 // will never be used, so skip the check. For an anonymous union declared at
5769 // namespace scope, the constructor and destructor are used.
5770 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5771 RD->isAnonymousStructOrUnion())
5772 return false;
5773
Richard Smith852265f2012-03-30 20:53:28 +00005774 // C++11 [class.copy]p7, p18:
5775 // If the class definition declares a move constructor or move assignment
5776 // operator, an implicitly declared copy constructor or copy assignment
5777 // operator is defined as deleted.
5778 if (MD->isImplicit() &&
5779 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005780 CXXMethodDecl *UserDeclaredMove = nullptr;
Richard Smith852265f2012-03-30 20:53:28 +00005781
5782 // In Microsoft mode, a user-declared move only causes the deletion of the
5783 // corresponding copy operation, not both copy operations.
5784 if (RD->hasUserDeclaredMoveConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005785 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00005786 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005787
5788 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005789 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005790 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005791 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005792 break;
5793 }
5794 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005795 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005796 } else if (RD->hasUserDeclaredMoveAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005797 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00005798 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005799
5800 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005801 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005802 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005803 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005804 break;
5805 }
5806 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005807 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005808 }
5809
5810 if (UserDeclaredMove) {
5811 Diag(UserDeclaredMove->getLocation(),
5812 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00005813 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00005814 << UserDeclaredMove->isMoveAssignmentOperator();
5815 return true;
5816 }
5817 }
Alexis Huntd6da8762011-10-10 06:18:57 +00005818
Richard Smith6f1e2c62012-04-02 20:59:25 +00005819 // Do access control from the special member function
5820 ContextRAII MethodContext(*this, MD);
5821
Richard Smith921bd202012-02-26 09:11:52 +00005822 // C++11 [class.dtor]p5:
5823 // -- for a virtual destructor, lookup of the non-array deallocation function
5824 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00005825 if (CSM == CXXDestructor && MD->isVirtual()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005826 FunctionDecl *OperatorDelete = nullptr;
Richard Smith921bd202012-02-26 09:11:52 +00005827 DeclarationName Name =
5828 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5829 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00005830 OperatorDelete, false)) {
5831 if (Diagnose)
5832 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00005833 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005834 }
Richard Smith921bd202012-02-26 09:11:52 +00005835 }
5836
Richard Smith852265f2012-03-30 20:53:28 +00005837 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00005838
Aaron Ballman574705e2014-03-13 15:41:46 +00005839 for (auto &BI : RD->bases())
5840 if (!BI.isVirtual() &&
5841 SMI.shouldDeleteForBase(&BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005842 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005843
Richard Smithd1627032013-07-22 18:06:23 +00005844 // Per DR1611, do not consider virtual bases of constructors of abstract
5845 // classes, since we are not going to construct them.
Richard Smithbc46e432013-07-22 02:56:56 +00005846 if (!RD->isAbstract() || !SMI.IsConstructor) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005847 for (auto &BI : RD->vbases())
5848 if (SMI.shouldDeleteForBase(&BI))
Richard Smithbc46e432013-07-22 02:56:56 +00005849 return true;
5850 }
Alexis Huntea6f0322011-05-11 22:34:38 +00005851
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005852 for (auto *FI : RD->fields())
Richard Smithd951a1d2012-02-18 02:02:13 +00005853 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005854 SMI.shouldDeleteForField(FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00005855 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005856
Richard Smithd951a1d2012-02-18 02:02:13 +00005857 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00005858 return true;
5859
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005860 if (getLangOpts().CUDA) {
5861 // We should delete the special member in CUDA mode if target inference
5862 // failed.
5863 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
5864 Diagnose);
5865 }
5866
Alexis Huntea6f0322011-05-11 22:34:38 +00005867 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005868}
5869
Richard Smith92f241f2012-12-08 02:53:02 +00005870/// Perform lookup for a special member of the specified kind, and determine
5871/// whether it is trivial. If the triviality can be determined without the
5872/// lookup, skip it. This is intended for use when determining whether a
5873/// special member of a containing object is trivial, and thus does not ever
5874/// perform overload resolution for default constructors.
5875///
5876/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5877/// member that was most likely to be intended to be trivial, if any.
5878static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5879 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00005880 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00005881 if (Selected)
Craig Topperc3ec1492014-05-26 06:22:03 +00005882 *Selected = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005883
5884 switch (CSM) {
5885 case Sema::CXXInvalid:
5886 llvm_unreachable("not a special member");
5887
5888 case Sema::CXXDefaultConstructor:
5889 // C++11 [class.ctor]p5:
5890 // A default constructor is trivial if:
5891 // - all the [direct subobjects] have trivial default constructors
5892 //
5893 // Note, no overload resolution is performed in this case.
5894 if (RD->hasTrivialDefaultConstructor())
5895 return true;
5896
5897 if (Selected) {
5898 // If there's a default constructor which could have been trivial, dig it
5899 // out. Otherwise, if there's any user-provided default constructor, point
5900 // to that as an example of why there's not a trivial one.
Craig Topperc3ec1492014-05-26 06:22:03 +00005901 CXXConstructorDecl *DefCtor = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005902 if (RD->needsImplicitDefaultConstructor())
5903 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005904 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005905 if (!CI->isDefaultConstructor())
5906 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005907 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005908 if (!DefCtor->isUserProvided())
5909 break;
5910 }
5911
5912 *Selected = DefCtor;
5913 }
5914
5915 return false;
5916
5917 case Sema::CXXDestructor:
5918 // C++11 [class.dtor]p5:
5919 // A destructor is trivial if:
5920 // - all the direct [subobjects] have trivial destructors
5921 if (RD->hasTrivialDestructor())
5922 return true;
5923
5924 if (Selected) {
5925 if (RD->needsImplicitDestructor())
5926 S.DeclareImplicitDestructor(RD);
5927 *Selected = RD->getDestructor();
5928 }
5929
5930 return false;
5931
5932 case Sema::CXXCopyConstructor:
5933 // C++11 [class.copy]p12:
5934 // A copy constructor is trivial if:
5935 // - the constructor selected to copy each direct [subobject] is trivial
5936 if (RD->hasTrivialCopyConstructor()) {
5937 if (Quals == Qualifiers::Const)
5938 // We must either select the trivial copy constructor or reach an
5939 // ambiguity; no need to actually perform overload resolution.
5940 return true;
5941 } else if (!Selected) {
5942 return false;
5943 }
5944 // In C++98, we are not supposed to perform overload resolution here, but we
5945 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5946 // cases like B as having a non-trivial copy constructor:
5947 // struct A { template<typename T> A(T&); };
5948 // struct B { mutable A a; };
5949 goto NeedOverloadResolution;
5950
5951 case Sema::CXXCopyAssignment:
5952 // C++11 [class.copy]p25:
5953 // A copy assignment operator is trivial if:
5954 // - the assignment operator selected to copy each direct [subobject] is
5955 // trivial
5956 if (RD->hasTrivialCopyAssignment()) {
5957 if (Quals == Qualifiers::Const)
5958 return true;
5959 } else if (!Selected) {
5960 return false;
5961 }
5962 // In C++98, we are not supposed to perform overload resolution here, but we
5963 // treat that as a language defect.
5964 goto NeedOverloadResolution;
5965
5966 case Sema::CXXMoveConstructor:
5967 case Sema::CXXMoveAssignment:
5968 NeedOverloadResolution:
5969 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005970 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00005971
5972 // The standard doesn't describe how to behave if the lookup is ambiguous.
5973 // We treat it as not making the member non-trivial, just like the standard
5974 // mandates for the default constructor. This should rarely matter, because
5975 // the member will also be deleted.
5976 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5977 return true;
5978
5979 if (!SMOR->getMethod()) {
5980 assert(SMOR->getKind() ==
5981 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5982 return false;
5983 }
5984
5985 // We deliberately don't check if we found a deleted special member. We're
5986 // not supposed to!
5987 if (Selected)
5988 *Selected = SMOR->getMethod();
5989 return SMOR->getMethod()->isTrivial();
5990 }
5991
5992 llvm_unreachable("unknown special method kind");
5993}
5994
Benjamin Kramer3e350262013-02-15 12:30:38 +00005995static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005996 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00005997 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005998 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005999
6000 // Look for constructor templates.
6001 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
6002 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
6003 if (CXXConstructorDecl *CD =
6004 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
6005 return CD;
6006 }
6007
Craig Topperc3ec1492014-05-26 06:22:03 +00006008 return nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00006009}
6010
6011/// The kind of subobject we are checking for triviality. The values of this
6012/// enumeration are used in diagnostics.
6013enum TrivialSubobjectKind {
6014 /// The subobject is a base class.
6015 TSK_BaseClass,
6016 /// The subobject is a non-static data member.
6017 TSK_Field,
6018 /// The object is actually the complete object.
6019 TSK_CompleteObject
6020};
6021
6022/// Check whether the special member selected for a given type would be trivial.
6023static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00006024 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00006025 Sema::CXXSpecialMember CSM,
6026 TrivialSubobjectKind Kind,
6027 bool Diagnose) {
6028 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
6029 if (!SubRD)
6030 return true;
6031
6032 CXXMethodDecl *Selected;
6033 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006034 ConstRHS, Diagnose ? &Selected : nullptr))
Richard Smith92f241f2012-12-08 02:53:02 +00006035 return true;
6036
6037 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00006038 if (ConstRHS)
6039 SubType.addConst();
6040
Richard Smith92f241f2012-12-08 02:53:02 +00006041 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
6042 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
6043 << Kind << SubType.getUnqualifiedType();
6044 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
6045 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
6046 } else if (!Selected)
6047 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
6048 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
6049 else if (Selected->isUserProvided()) {
6050 if (Kind == TSK_CompleteObject)
6051 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
6052 << Kind << SubType.getUnqualifiedType() << CSM;
6053 else {
6054 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
6055 << Kind << SubType.getUnqualifiedType() << CSM;
6056 S.Diag(Selected->getLocation(), diag::note_declared_at);
6057 }
6058 } else {
6059 if (Kind != TSK_CompleteObject)
6060 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
6061 << Kind << SubType.getUnqualifiedType() << CSM;
6062
6063 // Explain why the defaulted or deleted special member isn't trivial.
6064 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
6065 }
6066 }
6067
6068 return false;
6069}
6070
6071/// Check whether the members of a class type allow a special member to be
6072/// trivial.
6073static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
6074 Sema::CXXSpecialMember CSM,
6075 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006076 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00006077 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
6078 continue;
6079
6080 QualType FieldType = S.Context.getBaseElementType(FI->getType());
6081
6082 // Pretend anonymous struct or union members are members of this class.
6083 if (FI->isAnonymousStructOrUnion()) {
6084 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
6085 CSM, ConstArg, Diagnose))
6086 return false;
6087 continue;
6088 }
6089
6090 // C++11 [class.ctor]p5:
6091 // A default constructor is trivial if [...]
6092 // -- no non-static data member of its class has a
6093 // brace-or-equal-initializer
6094 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
6095 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006096 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00006097 return false;
6098 }
6099
6100 // Objective C ARC 4.3.5:
6101 // [...] nontrivally ownership-qualified types are [...] not trivially
6102 // default constructible, copy constructible, move constructible, copy
6103 // assignable, move assignable, or destructible [...]
6104 if (S.getLangOpts().ObjCAutoRefCount &&
6105 FieldType.hasNonTrivialObjCLifetime()) {
6106 if (Diagnose)
6107 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
6108 << RD << FieldType.getObjCLifetime();
6109 return false;
6110 }
6111
Richard Smith41c35d62013-11-27 03:39:20 +00006112 bool ConstRHS = ConstArg && !FI->isMutable();
6113 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
6114 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00006115 return false;
6116 }
6117
6118 return true;
6119}
6120
6121/// Diagnose why the specified class does not have a trivial special member of
6122/// the given kind.
6123void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
6124 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00006125
Richard Smith41c35d62013-11-27 03:39:20 +00006126 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
6127 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00006128 TSK_CompleteObject, /*Diagnose*/true);
6129}
6130
6131/// Determine whether a defaulted or deleted special member function is trivial,
6132/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6133/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6134bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
6135 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00006136 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
6137
6138 CXXRecordDecl *RD = MD->getParent();
6139
6140 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00006141
Richard Smith2002bfe2013-11-04 02:02:27 +00006142 // C++11 [class.copy]p12, p25: [DR1593]
6143 // A [special member] is trivial if [...] its parameter-type-list is
6144 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00006145 switch (CSM) {
6146 case CXXDefaultConstructor:
6147 case CXXDestructor:
6148 // Trivial default constructors and destructors cannot have parameters.
6149 break;
6150
6151 case CXXCopyConstructor:
6152 case CXXCopyAssignment: {
6153 // Trivial copy operations always have const, non-volatile parameter types.
6154 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00006155 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00006156 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
6157 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
6158 if (Diagnose)
6159 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6160 << Param0->getSourceRange() << Param0->getType()
6161 << Context.getLValueReferenceType(
6162 Context.getRecordType(RD).withConst());
6163 return false;
6164 }
6165 break;
6166 }
6167
6168 case CXXMoveConstructor:
6169 case CXXMoveAssignment: {
6170 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00006171 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00006172 const RValueReferenceType *RT =
6173 Param0->getType()->getAs<RValueReferenceType>();
6174 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
6175 if (Diagnose)
6176 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6177 << Param0->getSourceRange() << Param0->getType()
6178 << Context.getRValueReferenceType(Context.getRecordType(RD));
6179 return false;
6180 }
6181 break;
6182 }
6183
6184 case CXXInvalid:
6185 llvm_unreachable("not a special member");
6186 }
6187
Richard Smith92f241f2012-12-08 02:53:02 +00006188 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
6189 if (Diagnose)
6190 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
6191 diag::note_nontrivial_default_arg)
6192 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
6193 return false;
6194 }
6195 if (MD->isVariadic()) {
6196 if (Diagnose)
6197 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
6198 return false;
6199 }
6200
6201 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6202 // A copy/move [constructor or assignment operator] is trivial if
6203 // -- the [member] selected to copy/move each direct base class subobject
6204 // is trivial
6205 //
6206 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6207 // A [default constructor or destructor] is trivial if
6208 // -- all the direct base classes have trivial [default constructors or
6209 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00006210 for (const auto &BI : RD->bases())
6211 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00006212 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00006213 return false;
6214
6215 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6216 // A copy/move [constructor or assignment operator] for a class X is
6217 // trivial if
6218 // -- for each non-static data member of X that is of class type (or array
6219 // thereof), the constructor selected to copy/move that member is
6220 // trivial
6221 //
6222 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6223 // A [default constructor or destructor] is trivial if
6224 // -- for all of the non-static data members of its class that are of class
6225 // type (or array thereof), each such class has a trivial [default
6226 // constructor or destructor]
6227 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
6228 return false;
6229
6230 // C++11 [class.dtor]p5:
6231 // A destructor is trivial if [...]
6232 // -- the destructor is not virtual
6233 if (CSM == CXXDestructor && MD->isVirtual()) {
6234 if (Diagnose)
6235 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
6236 return false;
6237 }
6238
6239 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
6240 // A [special member] for class X is trivial if [...]
6241 // -- class X has no virtual functions and no virtual base classes
6242 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
6243 if (!Diagnose)
6244 return false;
6245
6246 if (RD->getNumVBases()) {
6247 // Check for virtual bases. We already know that the corresponding
6248 // member in all bases is trivial, so vbases must all be direct.
6249 CXXBaseSpecifier &BS = *RD->vbases_begin();
6250 assert(BS.isVirtual());
6251 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
6252 return false;
6253 }
6254
6255 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00006256 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00006257 if (MI->isVirtual()) {
6258 SourceLocation MLoc = MI->getLocStart();
6259 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
6260 return false;
6261 }
6262 }
6263
6264 llvm_unreachable("dynamic class with no vbases and no virtual functions");
6265 }
6266
6267 // Looks like it's trivial!
6268 return true;
6269}
6270
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006271/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00006272namespace {
6273 struct FindHiddenVirtualMethodData {
6274 Sema *S;
6275 CXXMethodDecl *Method;
6276 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006277 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00006278 };
6279}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006280
David Blaikie282c92a2012-10-19 00:53:08 +00006281/// \brief Check whether any most overriden method from MD in Methods
6282static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00006283 const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00006284 if (MD->size_overridden_methods() == 0)
6285 return Methods.count(MD->getCanonicalDecl());
6286 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6287 E = MD->end_overridden_methods();
6288 I != E; ++I)
6289 if (CheckMostOverridenMethods(*I, Methods))
6290 return true;
6291 return false;
6292}
6293
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006294/// \brief Member lookup function that determines whether a given C++
6295/// method overloads virtual methods in a base class without overriding any,
6296/// to be used with CXXRecordDecl::lookupInBases().
6297static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
6298 CXXBasePath &Path,
6299 void *UserData) {
6300 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
6301
6302 FindHiddenVirtualMethodData &Data
6303 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
6304
6305 DeclarationName Name = Data.Method->getDeclName();
6306 assert(Name.getNameKind() == DeclarationName::Identifier);
6307
6308 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006309 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006310 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00006311 !Path.Decls.empty();
6312 Path.Decls = Path.Decls.slice(1)) {
6313 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006314 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00006315 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006316 foundSameNameMethod = true;
6317 // Interested only in hidden virtual methods.
6318 if (!MD->isVirtual())
6319 continue;
6320 // If the method we are checking overrides a method from its base
Aaron Ballman04559a72014-07-30 23:50:53 +00006321 // don't warn about the other overloaded methods. Clang deviates from GCC
6322 // by only diagnosing overloads of inherited virtual functions that do not
6323 // override any other virtual functions in the base. GCC's
6324 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6325 // function from a base class. These cases may be better served by a
6326 // warning (not specific to virtual functions) on call sites when the call
6327 // would select a different function from the base class, were it visible.
6328 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006329 if (!Data.S->IsOverload(Data.Method, MD, false))
6330 return true;
6331 // Collect the overload only if its hidden.
David Blaikie282c92a2012-10-19 00:53:08 +00006332 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006333 overloadedMethods.push_back(MD);
6334 }
6335 }
6336
6337 if (foundSameNameMethod)
6338 Data.OverloadedMethods.append(overloadedMethods.begin(),
6339 overloadedMethods.end());
6340 return foundSameNameMethod;
6341}
6342
David Blaikie282c92a2012-10-19 00:53:08 +00006343/// \brief Add the most overriden methods from MD to Methods
6344static void AddMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00006345 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00006346 if (MD->size_overridden_methods() == 0)
6347 Methods.insert(MD->getCanonicalDecl());
6348 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6349 E = MD->end_overridden_methods();
6350 I != E; ++I)
6351 AddMostOverridenMethods(*I, Methods);
6352}
6353
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006354/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006355/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006356void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6357 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00006358 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006359 return;
6360
6361 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6362 /*bool RecordPaths=*/false,
6363 /*bool DetectVirtual=*/false);
6364 FindHiddenVirtualMethodData Data;
6365 Data.Method = MD;
6366 Data.S = this;
6367
6368 // Keep the base methods that were overriden or introduced in the subclass
6369 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006370 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00006371 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6372 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6373 NamedDecl *ND = *I;
6374 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00006375 ND = shad->getTargetDecl();
6376 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6377 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006378 }
6379
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006380 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
6381 OverloadedMethods = Data.OverloadedMethods;
6382}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006383
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006384void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6385 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6386 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6387 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6388 PartialDiagnostic PD = PDiag(
6389 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6390 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6391 Diag(overloadedMD->getLocation(), PD);
6392 }
6393}
6394
6395/// \brief Diagnose methods which overload virtual methods in a base class
6396/// without overriding any.
6397void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6398 if (MD->isInvalidDecl())
6399 return;
6400
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006401 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006402 return;
6403
6404 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6405 FindHiddenVirtualMethods(MD, OverloadedMethods);
6406 if (!OverloadedMethods.empty()) {
6407 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6408 << MD << (OverloadedMethods.size() > 1);
6409
6410 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006411 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00006412}
6413
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006414void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00006415 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006416 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00006417 SourceLocation RBrac,
6418 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006419 if (!TagDecl)
6420 return;
Mike Stump11289f42009-09-09 15:08:12 +00006421
Douglas Gregorc9f9b862009-05-11 19:58:34 +00006422 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00006423
Rafael Espindola06e1b132012-07-12 04:32:30 +00006424 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6425 if (l->getKind() != AttributeList::AT_Visibility)
6426 continue;
6427 l->setInvalid();
6428 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6429 l->getName();
6430 }
6431
David Blaikie751c5582011-09-22 02:58:26 +00006432 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00006433 // strict aliasing violation!
6434 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00006435 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00006436
Douglas Gregor0be31a22010-07-02 17:43:08 +00006437 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00006438 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006439}
6440
Douglas Gregor05379422008-11-03 17:51:48 +00006441/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6442/// special functions, such as the default constructor, copy
6443/// constructor, or destructor, to the given C++ class (C++
6444/// [special]p1). This routine can only be executed just before the
6445/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00006446void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006447 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00006448 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006449
Richard Smith6b02d462012-12-08 08:32:28 +00006450 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00006451 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006452
Richard Smith6b02d462012-12-08 08:32:28 +00006453 // If the properties or semantics of the copy constructor couldn't be
6454 // determined while the class was being declared, force a declaration
6455 // of it now.
6456 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6457 DeclareImplicitCopyConstructor(ClassDecl);
6458 }
6459
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006460 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006461 ++ASTContext::NumImplicitMoveConstructors;
6462
Richard Smith6b02d462012-12-08 08:32:28 +00006463 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6464 DeclareImplicitMoveConstructor(ClassDecl);
6465 }
6466
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006467 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6468 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00006469
6470 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006471 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00006472 // it shows up in the right place in the vtable and that we diagnose
6473 // problems with the implicit exception specification.
6474 if (ClassDecl->isDynamicClass() ||
6475 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006476 DeclareImplicitCopyAssignment(ClassDecl);
6477 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006478
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006479 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006480 ++ASTContext::NumImplicitMoveAssignmentOperators;
6481
6482 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00006483 if (ClassDecl->isDynamicClass() ||
6484 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00006485 DeclareImplicitMoveAssignment(ClassDecl);
6486 }
6487
Douglas Gregor7454c562010-07-02 20:37:36 +00006488 if (!ClassDecl->hasUserDeclaredDestructor()) {
6489 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00006490
6491 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00006492 // have to declare the destructor immediately. This ensures that, e.g., it
6493 // shows up in the right place in the vtable and that we diagnose problems
6494 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00006495 if (ClassDecl->isDynamicClass() ||
6496 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00006497 DeclareImplicitDestructor(ClassDecl);
6498 }
Douglas Gregor05379422008-11-03 17:51:48 +00006499}
6500
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006501unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Francois Pichet1c229c02011-04-22 22:18:13 +00006502 if (!D)
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006503 return 0;
Francois Pichet1c229c02011-04-22 22:18:13 +00006504
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006505 // The order of template parameters is not important here. All names
6506 // get added to the same scope.
6507 SmallVector<TemplateParameterList *, 4> ParameterLists;
6508
6509 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6510 D = TD->getTemplatedDecl();
6511
6512 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6513 ParameterLists.push_back(PSD->getTemplateParameters());
6514
6515 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6516 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6517 ParameterLists.push_back(DD->getTemplateParameterList(i));
6518
6519 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6520 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6521 ParameterLists.push_back(FTD->getTemplateParameters());
6522 }
6523 }
6524
6525 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6526 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6527 ParameterLists.push_back(TD->getTemplateParameterList(i));
6528
6529 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6530 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6531 ParameterLists.push_back(CTD->getTemplateParameters());
6532 }
6533 }
6534
6535 unsigned Count = 0;
6536 for (TemplateParameterList *Params : ParameterLists) {
6537 if (Params->size() > 0)
6538 // Ignore explicit specializations; they don't contribute to the template
6539 // depth.
6540 ++Count;
6541 for (NamedDecl *Param : *Params) {
6542 if (Param->getDeclName()) {
6543 S->AddDecl(Param);
6544 IdResolver.AddDecl(Param);
Francois Pichet1c229c02011-04-22 22:18:13 +00006545 }
6546 }
6547 }
Francois Pichet1c229c02011-04-22 22:18:13 +00006548
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006549 return Count;
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006550}
6551
John McCall48871652010-08-21 09:40:31 +00006552void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006553 if (!RecordD) return;
6554 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00006555 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00006556 PushDeclContext(S, Record);
6557}
6558
John McCall48871652010-08-21 09:40:31 +00006559void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006560 if (!RecordD) return;
6561 PopDeclContext();
6562}
6563
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006564/// This is used to implement the constant expression evaluation part of the
6565/// attribute enable_if extension. There is nothing in standard C++ which would
6566/// require reentering parameters.
6567void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6568 if (!Param)
6569 return;
6570
6571 S->AddDecl(Param);
6572 if (Param->getDeclName())
6573 IdResolver.AddDecl(Param);
6574}
6575
Douglas Gregor4d87df52008-12-16 21:30:33 +00006576/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6577/// parsing a top-level (non-nested) C++ class, and we are now
6578/// parsing those parts of the given Method declaration that could
6579/// not be parsed earlier (C++ [class.mem]p2), such as default
6580/// arguments. This action should enter the scope of the given
6581/// Method declaration as if we had just parsed the qualified method
6582/// name. However, it should not bring the parameters into scope;
6583/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00006584void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006585}
6586
6587/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6588/// C++ method declaration. We're (re-)introducing the given
6589/// function parameter into scope for use in parsing later parts of
6590/// the method declaration. For example, we could see an
6591/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00006592void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006593 if (!ParamD)
6594 return;
Mike Stump11289f42009-09-09 15:08:12 +00006595
John McCall48871652010-08-21 09:40:31 +00006596 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00006597
6598 // If this parameter has an unparsed default argument, clear it out
6599 // to make way for the parsed default argument.
6600 if (Param->hasUnparsedDefaultArg())
Craig Topperc3ec1492014-05-26 06:22:03 +00006601 Param->setDefaultArg(nullptr);
Douglas Gregor58354032008-12-24 00:01:03 +00006602
John McCall48871652010-08-21 09:40:31 +00006603 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006604 if (Param->getDeclName())
6605 IdResolver.AddDecl(Param);
6606}
6607
6608/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6609/// processing the delayed method declaration for Method. The method
6610/// declaration is now considered finished. There may be a separate
6611/// ActOnStartOfFunctionDef action later (not necessarily
6612/// immediately!) for this method, if it was also defined inside the
6613/// class body.
John McCall48871652010-08-21 09:40:31 +00006614void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006615 if (!MethodD)
6616 return;
Mike Stump11289f42009-09-09 15:08:12 +00006617
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006618 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00006619
John McCall48871652010-08-21 09:40:31 +00006620 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006621
6622 // Now that we have our default arguments, check the constructor
6623 // again. It could produce additional diagnostics or affect whether
6624 // the class has implicitly-declared destructors, among other
6625 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006626 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6627 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006628
6629 // Check the default arguments, which we may have added.
6630 if (!Method->isInvalidDecl())
6631 CheckCXXDefaultArguments(Method);
6632}
6633
Douglas Gregor831c93f2008-11-05 20:51:48 +00006634/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00006635/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00006636/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006637/// emit diagnostics and set the invalid bit to true. In any case, the type
6638/// will be updated to reflect a well-formed type for the constructor and
6639/// returned.
6640QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006641 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006642 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006643
6644 // C++ [class.ctor]p3:
6645 // A constructor shall not be virtual (10.3) or static (9.4). A
6646 // constructor can be invoked for a const, volatile or const
6647 // volatile object. A constructor shall not be declared const,
6648 // volatile, or const volatile (9.3.2).
6649 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006650 if (!D.isInvalidType())
6651 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6652 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6653 << SourceRange(D.getIdentifierLoc());
6654 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006655 }
John McCall8e7d6562010-08-26 03:08:43 +00006656 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006657 if (!D.isInvalidType())
6658 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6659 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6660 << SourceRange(D.getIdentifierLoc());
6661 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006662 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006663 }
Mike Stump11289f42009-09-09 15:08:12 +00006664
David Majnemer03f705f2014-07-08 18:18:04 +00006665 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6666 diagnoseIgnoredQualifiers(
6667 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6668 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6669 D.getDeclSpec().getRestrictSpecLoc(),
6670 D.getDeclSpec().getAtomicSpecLoc());
6671 D.setInvalidType();
6672 }
6673
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006674 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006675 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00006676 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006677 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6678 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006679 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006680 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6681 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006682 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006683 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6684 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00006685 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006686 }
Mike Stump11289f42009-09-09 15:08:12 +00006687
Douglas Gregordb9d6642011-01-26 05:01:58 +00006688 // C++0x [class.ctor]p4:
6689 // A constructor shall not be declared with a ref-qualifier.
6690 if (FTI.hasRefQualifier()) {
6691 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6692 << FTI.RefQualifierIsLValueRef
6693 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6694 D.setInvalidType();
6695 }
6696
Douglas Gregor831c93f2008-11-05 20:51:48 +00006697 // Rebuild the function type "R" without any type qualifiers (in
6698 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00006699 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00006700 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006701 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00006702 return R;
6703
6704 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6705 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006706 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00006707
6708 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006709}
6710
Douglas Gregor4d87df52008-12-16 21:30:33 +00006711/// CheckConstructor - Checks a fully-formed constructor for
6712/// well-formedness, issuing any diagnostics required. Returns true if
6713/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006714void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00006715 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006716 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6717 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006718 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006719
6720 // C++ [class.copy]p3:
6721 // A declaration of a constructor for a class X is ill-formed if
6722 // its first parameter is of type (optionally cv-qualified) X and
6723 // either there are no other parameters or else all other
6724 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006725 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00006726 ((Constructor->getNumParams() == 1) ||
6727 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00006728 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6729 Constructor->getTemplateSpecializationKind()
6730 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006731 QualType ParamType = Constructor->getParamDecl(0)->getType();
6732 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6733 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00006734 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00006735 const char *ConstRef
6736 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6737 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00006738 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00006739 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00006740
6741 // FIXME: Rather that making the constructor invalid, we should endeavor
6742 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006743 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006744 }
6745 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00006746}
6747
John McCalldeb646e2010-08-04 01:04:25 +00006748/// CheckDestructor - Checks a fully-formed destructor definition for
6749/// well-formedness, issuing any diagnostics required. Returns true
6750/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00006751bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006752 CXXRecordDecl *RD = Destructor->getParent();
6753
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006754 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006755 SourceLocation Loc;
6756
6757 if (!Destructor->isImplicit())
6758 Loc = Destructor->getLocation();
6759 else
6760 Loc = RD->getLocation();
6761
6762 // If we have a virtual destructor, look up the deallocation function
Craig Topperc3ec1492014-05-26 06:22:03 +00006763 FunctionDecl *OperatorDelete = nullptr;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006764 DeclarationName Name =
6765 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006766 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00006767 return true;
Richard Smithf03bd302013-12-05 08:30:59 +00006768 // If there's no class-specific operator delete, look up the global
6769 // non-array delete.
6770 if (!OperatorDelete)
6771 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall1e5d75d2010-07-03 18:33:00 +00006772
Eli Friedmanfa0df832012-02-02 03:46:19 +00006773 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00006774
6775 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006776 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00006777
6778 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006779}
6780
Douglas Gregor831c93f2008-11-05 20:51:48 +00006781/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6782/// the well-formednes of the destructor declarator @p D with type @p
6783/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006784/// emit diagnostics and set the declarator to invalid. Even if this happens,
6785/// will be updated to reflect a well-formed type for the destructor and
6786/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00006787QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006788 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006789 // C++ [class.dtor]p1:
6790 // [...] A typedef-name that names a class is a class-name
6791 // (7.1.3); however, a typedef-name that names a class shall not
6792 // be used as the identifier in the declarator for a destructor
6793 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00006794 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00006795 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00006796 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00006797 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00006798 else if (const TemplateSpecializationType *TST =
6799 DeclaratorType->getAs<TemplateSpecializationType>())
6800 if (TST->isTypeAlias())
6801 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6802 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006803
6804 // C++ [class.dtor]p2:
6805 // A destructor is used to destroy objects of its class type. A
6806 // destructor takes no parameters, and no return type can be
6807 // specified for it (not even void). The address of a destructor
6808 // shall not be taken. A destructor shall not be static. A
6809 // destructor can be invoked for a const, volatile or const
6810 // volatile object. A destructor shall not be declared const,
6811 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00006812 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006813 if (!D.isInvalidType())
6814 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6815 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00006816 << SourceRange(D.getIdentifierLoc())
6817 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6818
John McCall8e7d6562010-08-26 03:08:43 +00006819 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006820 }
David Majnemer03f705f2014-07-08 18:18:04 +00006821 if (!D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006822 // Destructors don't have return types, but the parser will
6823 // happily parse something like:
6824 //
6825 // class X {
6826 // float ~X();
6827 // };
6828 //
6829 // The return type will be eliminated later.
David Majnemer03f705f2014-07-08 18:18:04 +00006830 if (D.getDeclSpec().hasTypeSpecifier())
6831 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6832 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6833 << SourceRange(D.getIdentifierLoc());
6834 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6835 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6836 SourceLocation(),
6837 D.getDeclSpec().getConstSpecLoc(),
6838 D.getDeclSpec().getVolatileSpecLoc(),
6839 D.getDeclSpec().getRestrictSpecLoc(),
6840 D.getDeclSpec().getAtomicSpecLoc());
6841 D.setInvalidType();
6842 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006843 }
Mike Stump11289f42009-09-09 15:08:12 +00006844
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006845 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006846 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006847 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006848 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6849 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006850 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006851 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6852 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006853 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006854 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6855 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00006856 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006857 }
6858
Douglas Gregordb9d6642011-01-26 05:01:58 +00006859 // C++0x [class.dtor]p2:
6860 // A destructor shall not be declared with a ref-qualifier.
6861 if (FTI.hasRefQualifier()) {
6862 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6863 << FTI.RefQualifierIsLValueRef
6864 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6865 D.setInvalidType();
6866 }
6867
Douglas Gregor831c93f2008-11-05 20:51:48 +00006868 // Make sure we don't have any parameters.
Alp Toker4284c6e2014-05-11 16:05:55 +00006869 if (FTIHasNonVoidParameters(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006870 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6871
6872 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006873 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00006874 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006875 }
6876
Mike Stump11289f42009-09-09 15:08:12 +00006877 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00006878 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006879 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00006880 D.setInvalidType();
6881 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006882
6883 // Rebuild the function type "R" without any type qualifiers or
6884 // parameters (in case any of the errors above fired) and with
6885 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00006886 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00006887 if (!D.isInvalidType())
6888 return R;
6889
Douglas Gregor95755162010-07-01 05:10:53 +00006890 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006891 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6892 EPI.Variadic = false;
6893 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006894 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006895 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006896}
6897
Richard Smitha865a162014-12-19 02:07:47 +00006898static void extendLeft(SourceRange &R, const SourceRange &Before) {
6899 if (Before.isInvalid())
6900 return;
6901 R.setBegin(Before.getBegin());
6902 if (R.getEnd().isInvalid())
6903 R.setEnd(Before.getEnd());
6904}
6905
6906static void extendRight(SourceRange &R, const SourceRange &After) {
6907 if (After.isInvalid())
6908 return;
6909 if (R.getBegin().isInvalid())
6910 R.setBegin(After.getBegin());
6911 R.setEnd(After.getEnd());
6912}
6913
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006914/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6915/// well-formednes of the conversion function declarator @p D with
6916/// type @p R. If there are any errors in the declarator, this routine
6917/// will emit diagnostics and return true. Otherwise, it will return
6918/// false. Either way, the type @p R will be updated to reflect a
6919/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006920void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00006921 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006922 // C++ [class.conv.fct]p1:
6923 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00006924 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00006925 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00006926 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006927 if (!D.isInvalidType())
6928 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00006929 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6930 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006931 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006932 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006933 }
John McCall212fa2e2010-04-13 00:04:31 +00006934
Richard Smitha865a162014-12-19 02:07:47 +00006935 TypeSourceInfo *ConvTSI = nullptr;
6936 QualType ConvType =
6937 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
John McCall212fa2e2010-04-13 00:04:31 +00006938
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006939 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006940 // Conversion functions don't have return types, but the parser will
6941 // happily parse something like:
6942 //
6943 // class X {
6944 // float operator bool();
6945 // };
6946 //
6947 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00006948 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6949 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6950 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00006951 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006952 }
6953
John McCall212fa2e2010-04-13 00:04:31 +00006954 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6955
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006956 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00006957 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006958 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6959
6960 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006961 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006962 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00006963 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006964 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006965 D.setInvalidType();
6966 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006967
John McCall212fa2e2010-04-13 00:04:31 +00006968 // Diagnose "&operator bool()" and other such nonsense. This
6969 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00006970 if (Proto->getReturnType() != ConvType) {
Richard Smitha865a162014-12-19 02:07:47 +00006971 bool NeedsTypedef = false;
6972 SourceRange Before, After;
6973
6974 // Walk the chunks and extract information on them for our diagnostic.
6975 bool PastFunctionChunk = false;
6976 for (auto &Chunk : D.type_objects()) {
6977 switch (Chunk.Kind) {
6978 case DeclaratorChunk::Function:
6979 if (!PastFunctionChunk) {
6980 if (Chunk.Fun.HasTrailingReturnType) {
6981 TypeSourceInfo *TRT = nullptr;
6982 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
6983 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
6984 }
6985 PastFunctionChunk = true;
6986 break;
6987 }
6988 // Fall through.
6989 case DeclaratorChunk::Array:
6990 NeedsTypedef = true;
6991 extendRight(After, Chunk.getSourceRange());
6992 break;
6993
6994 case DeclaratorChunk::Pointer:
6995 case DeclaratorChunk::BlockPointer:
6996 case DeclaratorChunk::Reference:
6997 case DeclaratorChunk::MemberPointer:
6998 extendLeft(Before, Chunk.getSourceRange());
6999 break;
7000
7001 case DeclaratorChunk::Paren:
7002 extendLeft(Before, Chunk.Loc);
7003 extendRight(After, Chunk.EndLoc);
7004 break;
7005 }
7006 }
7007
7008 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
7009 After.isValid() ? After.getBegin() :
7010 D.getIdentifierLoc();
7011 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
7012 DB << Before << After;
7013
7014 if (!NeedsTypedef) {
7015 DB << /*don't need a typedef*/0;
7016
7017 // If we can provide a correct fix-it hint, do so.
7018 if (After.isInvalid() && ConvTSI) {
7019 SourceLocation InsertLoc =
7020 PP.getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
7021 DB << FixItHint::CreateInsertion(InsertLoc, " ")
7022 << FixItHint::CreateInsertionFromRange(
7023 InsertLoc, CharSourceRange::getTokenRange(Before))
7024 << FixItHint::CreateRemoval(Before);
7025 }
7026 } else if (!Proto->getReturnType()->isDependentType()) {
7027 DB << /*typedef*/1 << Proto->getReturnType();
7028 } else if (getLangOpts().CPlusPlus11) {
7029 DB << /*alias template*/2 << Proto->getReturnType();
7030 } else {
7031 DB << /*might not be fixable*/3;
7032 }
7033
7034 // Recover by incorporating the other type chunks into the result type.
7035 // Note, this does *not* change the name of the function. This is compatible
7036 // with the GCC extension:
7037 // struct S { &operator int(); } s;
7038 // int &r = s.operator int(); // ok in GCC
7039 // S::operator int&() {} // error in GCC, function name is 'operator int'.
Alp Toker314cc812014-01-25 16:55:45 +00007040 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00007041 }
7042
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007043 // C++ [class.conv.fct]p4:
7044 // The conversion-type-id shall not represent a function type nor
7045 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007046 if (ConvType->isArrayType()) {
7047 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
7048 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007049 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007050 } else if (ConvType->isFunctionType()) {
7051 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
7052 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007053 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007054 }
7055
7056 // Rebuild the function type "R" without any parameters (in case any
7057 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00007058 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00007059 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00007060 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007061
Douglas Gregor5fb53972009-01-14 15:45:31 +00007062 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00007063 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00007064 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007065 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00007066 diag::warn_cxx98_compat_explicit_conversion_functions :
7067 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00007068 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007069}
7070
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007071/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
7072/// the declaration of the given C++ conversion function. This routine
7073/// is responsible for recording the conversion function in the C++
7074/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00007075Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007076 assert(Conversion && "Expected to receive a conversion function declaration");
7077
Douglas Gregor4287b372008-12-12 08:25:50 +00007078 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007079
7080 // Make sure we aren't redeclaring the conversion function.
7081 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007082
7083 // C++ [class.conv.fct]p1:
7084 // [...] A conversion function is never used to convert a
7085 // (possibly cv-qualified) object to the (possibly cv-qualified)
7086 // same object type (or a reference to it), to a (possibly
7087 // cv-qualified) base class of that type (or a reference to it),
7088 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00007089 // FIXME: Suppress this warning if the conversion function ends up being a
7090 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00007091 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007092 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007093 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007094 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00007095 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
7096 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00007097 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00007098 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007099 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
7100 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00007101 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007102 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007103 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00007104 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007105 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007106 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00007107 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007108 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007109 }
7110
Douglas Gregor457104e2010-09-29 04:25:11 +00007111 if (FunctionTemplateDecl *ConversionTemplate
7112 = Conversion->getDescribedFunctionTemplate())
7113 return ConversionTemplate;
7114
John McCall48871652010-08-21 09:40:31 +00007115 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007116}
7117
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007118//===----------------------------------------------------------------------===//
7119// Namespace Handling
7120//===----------------------------------------------------------------------===//
7121
Richard Smith45bb8852012-10-04 22:13:39 +00007122/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
7123/// reopened.
7124static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
7125 SourceLocation Loc,
7126 IdentifierInfo *II, bool *IsInline,
7127 NamespaceDecl *PrevNS) {
7128 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00007129
Richard Smithf501cc32012-10-05 01:46:25 +00007130 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
7131 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
7132 // inline namespaces, with the intention of bringing names into namespace std.
7133 //
7134 // We support this just well enough to get that case working; this is not
7135 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00007136 if (*IsInline && II && II->getName().startswith("__atomic") &&
7137 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00007138 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00007139 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
7140 NS = NS->getPreviousDecl())
7141 NS->setInline(*IsInline);
7142 // Patch up the lookup table for the containing namespace. This isn't really
7143 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00007144 for (auto *I : PrevNS->decls())
7145 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00007146 PrevNS->getParent()->makeDeclVisibleInContext(ND);
7147 return;
7148 }
7149
7150 if (PrevNS->isInline())
7151 // The user probably just forgot the 'inline', so suggest that it
7152 // be added back.
7153 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
7154 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
7155 else
Richard Smith5b5d21e2014-03-12 23:36:42 +00007156 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
Richard Smith45bb8852012-10-04 22:13:39 +00007157
7158 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
7159 *IsInline = PrevNS->isInline();
7160}
John McCallb1be5232010-08-26 09:15:37 +00007161
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007162/// ActOnStartNamespaceDef - This is called at the start of a namespace
7163/// definition.
John McCall48871652010-08-21 09:40:31 +00007164Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00007165 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007166 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00007167 SourceLocation IdentLoc,
7168 IdentifierInfo *II,
7169 SourceLocation LBrace,
7170 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007171 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
7172 // For anonymous namespace, take the location of the left brace.
7173 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00007174 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00007175 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00007176 bool IsStd = false;
7177 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007178 Scope *DeclRegionScope = NamespcScope->getParent();
7179
Craig Topperc3ec1492014-05-26 06:22:03 +00007180 NamespaceDecl *PrevNS = nullptr;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007181 if (II) {
7182 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00007183 // The identifier in an original-namespace-definition shall not
7184 // have been previously defined in the declarative region in
7185 // which the original-namespace-definition appears. The
7186 // identifier in an original-namespace-definition is the name of
7187 // the namespace. Subsequently in that declarative region, it is
7188 // treated as an original-namespace-name.
7189 //
7190 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00007191 // look through using directives, just look for any ordinary names.
7192
7193 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00007194 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
7195 Decl::IDNS_Namespace;
Craig Topperc3ec1492014-05-26 06:22:03 +00007196 NamedDecl *PrevDecl = nullptr;
David Blaikieff7d47a2012-12-19 00:45:41 +00007197 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
7198 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
7199 ++I) {
7200 if ((*I)->getIdentifierNamespace() & IDNS) {
7201 PrevDecl = *I;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00007202 break;
7203 }
7204 }
7205
Douglas Gregore57e7522012-01-07 09:11:48 +00007206 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
7207
7208 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00007209 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00007210 if (IsInline != PrevNS->isInline())
7211 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
7212 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00007213 } else if (PrevDecl) {
7214 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00007215 Diag(Loc, diag::err_redefinition_different_kind)
7216 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00007217 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00007218 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00007219 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00007220 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00007221 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00007222 // This is the first "real" definition of the namespace "std", so update
7223 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00007224 PrevNS = getStdNamespace();
7225 IsStd = true;
7226 AddToKnown = !IsInline;
7227 } else {
7228 // We've seen this namespace for the first time.
7229 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00007230 }
Douglas Gregor91f84212008-12-11 16:49:14 +00007231 } else {
John McCall4fa53422009-10-01 00:25:31 +00007232 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00007233
7234 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00007235 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00007236 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00007237 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00007238 } else {
7239 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00007240 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00007241 }
7242
Richard Smith45bb8852012-10-04 22:13:39 +00007243 if (PrevNS && IsInline != PrevNS->isInline())
7244 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
7245 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00007246 }
7247
7248 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
7249 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00007250 if (IsInvalid)
7251 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00007252
7253 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00007254
Douglas Gregore57e7522012-01-07 09:11:48 +00007255 // FIXME: Should we be merging attributes?
7256 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00007257 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00007258
7259 if (IsStd)
7260 StdNamespace = Namespc;
7261 if (AddToKnown)
7262 KnownNamespaces[Namespc] = false;
7263
7264 if (II) {
7265 PushOnScopeChains(Namespc, DeclRegionScope);
7266 } else {
7267 // Link the anonymous namespace into its parent.
7268 DeclContext *Parent = CurContext->getRedeclContext();
7269 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7270 TU->setAnonymousNamespace(Namespc);
7271 } else {
7272 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00007273 }
John McCall4fa53422009-10-01 00:25:31 +00007274
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00007275 CurContext->addDecl(Namespc);
7276
John McCall4fa53422009-10-01 00:25:31 +00007277 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
7278 // behaves as if it were replaced by
7279 // namespace unique { /* empty body */ }
7280 // using namespace unique;
7281 // namespace unique { namespace-body }
7282 // where all occurrences of 'unique' in a translation unit are
7283 // replaced by the same identifier and this identifier differs
7284 // from all other identifiers in the entire program.
7285
7286 // We just create the namespace with an empty name and then add an
7287 // implicit using declaration, just like the standard suggests.
7288 //
7289 // CodeGen enforces the "universally unique" aspect by giving all
7290 // declarations semantically contained within an anonymous
7291 // namespace internal linkage.
7292
Douglas Gregore57e7522012-01-07 09:11:48 +00007293 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00007294 UsingDirectiveDecl* UD
Nick Lewycky38115822012-11-04 20:21:54 +00007295 = UsingDirectiveDecl::Create(Context, Parent,
John McCall0db42252009-12-16 02:06:49 +00007296 /* 'using' */ LBrace,
7297 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00007298 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00007299 /* identifier */ SourceLocation(),
7300 Namespc,
Nick Lewycky38115822012-11-04 20:21:54 +00007301 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00007302 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00007303 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00007304 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007305 }
7306
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00007307 ActOnDocumentableDecl(Namespc);
7308
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007309 // Although we could have an invalid decl (i.e. the namespace name is a
7310 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00007311 // FIXME: We should be able to push Namespc here, so that the each DeclContext
7312 // for the namespace has the declarations that showed up in that particular
7313 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00007314 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00007315 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007316}
7317
Sebastian Redla6602e92009-11-23 15:34:23 +00007318/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
7319/// is a namespace alias, returns the namespace it points to.
7320static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
7321 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
7322 return AD->getNamespace();
7323 return dyn_cast_or_null<NamespaceDecl>(D);
7324}
7325
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007326/// ActOnFinishNamespaceDef - This callback is called after a namespace is
7327/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00007328void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007329 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
7330 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007331 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007332 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00007333 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00007334 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007335}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007336
John McCall28a0cf72010-08-25 07:42:41 +00007337CXXRecordDecl *Sema::getStdBadAlloc() const {
7338 return cast_or_null<CXXRecordDecl>(
7339 StdBadAlloc.get(Context.getExternalSource()));
7340}
7341
7342NamespaceDecl *Sema::getStdNamespace() const {
7343 return cast_or_null<NamespaceDecl>(
7344 StdNamespace.get(Context.getExternalSource()));
7345}
7346
Douglas Gregorcdf87022010-06-29 17:53:46 +00007347/// \brief Retrieve the special "std" namespace, which may require us to
7348/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007349NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00007350 if (!StdNamespace) {
7351 // The "std" namespace has not yet been defined, so build one implicitly.
7352 StdNamespace = NamespaceDecl::Create(Context,
7353 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00007354 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007355 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00007356 &PP.getIdentifierTable().get("std"),
Craig Topperc3ec1492014-05-26 06:22:03 +00007357 /*PrevDecl=*/nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007358 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007359 }
Eli Bendersky9a220fc2014-09-29 20:38:29 +00007360
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007361 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007362}
7363
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007364bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007365 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007366 "Looking for std::initializer_list outside of C++.");
7367
7368 // We're looking for implicit instantiations of
7369 // template <typename E> class std::initializer_list.
7370
7371 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
7372 return false;
7373
Craig Topperc3ec1492014-05-26 06:22:03 +00007374 ClassTemplateDecl *Template = nullptr;
7375 const TemplateArgument *Arguments = nullptr;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007376
Sebastian Redl43144e72012-01-17 22:49:58 +00007377 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007378
Sebastian Redl43144e72012-01-17 22:49:58 +00007379 ClassTemplateSpecializationDecl *Specialization =
7380 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
7381 if (!Specialization)
7382 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007383
Sebastian Redl43144e72012-01-17 22:49:58 +00007384 Template = Specialization->getSpecializedTemplate();
7385 Arguments = Specialization->getTemplateArgs().data();
7386 } else if (const TemplateSpecializationType *TST =
7387 Ty->getAs<TemplateSpecializationType>()) {
7388 Template = dyn_cast_or_null<ClassTemplateDecl>(
7389 TST->getTemplateName().getAsTemplateDecl());
7390 Arguments = TST->getArgs();
7391 }
7392 if (!Template)
7393 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007394
7395 if (!StdInitializerList) {
7396 // Haven't recognized std::initializer_list yet, maybe this is it.
7397 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
7398 if (TemplateClass->getIdentifier() !=
7399 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00007400 !getStdNamespace()->InEnclosingNamespaceSetOf(
7401 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007402 return false;
7403 // This is a template called std::initializer_list, but is it the right
7404 // template?
7405 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00007406 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007407 return false;
7408 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
7409 return false;
7410
7411 // It's the right template.
7412 StdInitializerList = Template;
7413 }
7414
Richard Smith7d7dee72015-02-24 03:30:14 +00007415 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007416 return false;
7417
7418 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00007419 if (Element)
7420 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007421 return true;
7422}
7423
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007424static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7425 NamespaceDecl *Std = S.getStdNamespace();
7426 if (!Std) {
7427 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00007428 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007429 }
7430
7431 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7432 Loc, Sema::LookupOrdinaryName);
7433 if (!S.LookupQualifiedName(Result, Std)) {
7434 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00007435 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007436 }
7437 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7438 if (!Template) {
7439 Result.suppressDiagnostics();
7440 // We found something weird. Complain about the first thing we found.
7441 NamedDecl *Found = *Result.begin();
7442 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00007443 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007444 }
7445
7446 // We found some template called std::initializer_list. Now verify that it's
7447 // correct.
7448 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00007449 if (Params->getMinRequiredArguments() != 1 ||
7450 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007451 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00007452 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007453 }
7454
7455 return Template;
7456}
7457
7458QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7459 if (!StdInitializerList) {
7460 StdInitializerList = LookupStdInitializerList(*this, Loc);
7461 if (!StdInitializerList)
7462 return QualType();
7463 }
7464
7465 TemplateArgumentListInfo Args(Loc, Loc);
7466 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7467 Context.getTrivialTypeSourceInfo(Element,
7468 Loc)));
7469 return Context.getCanonicalType(
7470 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7471}
7472
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007473bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7474 // C++ [dcl.init.list]p2:
7475 // A constructor is an initializer-list constructor if its first parameter
7476 // is of type std::initializer_list<E> or reference to possibly cv-qualified
7477 // std::initializer_list<E> for some type E, and either there are no other
7478 // parameters or else all other parameters have default arguments.
7479 if (Ctor->getNumParams() < 1 ||
7480 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7481 return false;
7482
7483 QualType ArgType = Ctor->getParamDecl(0)->getType();
7484 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7485 ArgType = RT->getPointeeType().getUnqualifiedType();
7486
Craig Topperc3ec1492014-05-26 06:22:03 +00007487 return isStdInitializerList(ArgType, nullptr);
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007488}
7489
Douglas Gregora172e082011-03-26 22:25:30 +00007490/// \brief Determine whether a using statement is in a context where it will be
7491/// apply in all contexts.
7492static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7493 switch (CurContext->getDeclKind()) {
7494 case Decl::TranslationUnit:
7495 return true;
7496 case Decl::LinkageSpec:
7497 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7498 default:
7499 return false;
7500 }
7501}
7502
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007503namespace {
7504
7505// Callback to only accept typo corrections that are namespaces.
7506class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007507public:
Craig Toppera798a9d2014-03-02 09:32:10 +00007508 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007509 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007510 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007511 return false;
7512 }
7513};
7514
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007515}
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007516
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007517static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7518 CXXScopeSpec &SS,
7519 SourceLocation IdentLoc,
7520 IdentifierInfo *Ident) {
7521 R.clear();
Kaelyn Takata89c881b2014-10-27 18:07:29 +00007522 if (TypoCorrection Corrected =
7523 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
7524 llvm::make_unique<NamespaceValidatorCCC>(),
7525 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007526 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00007527 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7528 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007529 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00007530 S.diagnoseTypo(Corrected,
7531 S.PDiag(diag::err_using_directive_member_suggest)
7532 << Ident << DC << DroppedSpecifier << SS.getRange(),
7533 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007534 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007535 S.diagnoseTypo(Corrected,
7536 S.PDiag(diag::err_using_directive_suggest) << Ident,
7537 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007538 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007539 R.addDecl(Corrected.getCorrectionDecl());
7540 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007541 }
7542 return false;
7543}
7544
John McCall48871652010-08-21 09:40:31 +00007545Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00007546 SourceLocation UsingLoc,
7547 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007548 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00007549 SourceLocation IdentLoc,
7550 IdentifierInfo *NamespcName,
7551 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00007552 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7553 assert(NamespcName && "Invalid NamespcName.");
7554 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00007555
7556 // This can only happen along a recovery path.
7557 while (S->getFlags() & Scope::TemplateParamScope)
7558 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00007559 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00007560
Craig Topperc3ec1492014-05-26 06:22:03 +00007561 UsingDirectiveDecl *UDir = nullptr;
7562 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregorcdf87022010-06-29 17:53:46 +00007563 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00007564 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007565
Douglas Gregor34074322009-01-14 22:20:51 +00007566 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00007567 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7568 LookupParsedName(R, S, &SS);
7569 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00007570 return nullptr;
John McCall27b18f82009-11-17 02:14:36 +00007571
Douglas Gregorcdf87022010-06-29 17:53:46 +00007572 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007573 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007574 // Allow "using namespace std;" or "using namespace ::std;" even if
7575 // "std" hasn't been defined yet, for GCC compatibility.
7576 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7577 NamespcName->isStr("std")) {
7578 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007579 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00007580 R.resolveKind();
7581 }
7582 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007583 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007584 }
7585
John McCall9f3059a2009-10-09 21:13:30 +00007586 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00007587 NamedDecl *Named = R.getFoundDecl();
7588 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7589 && "expected namespace decl");
Aaron Ballman43f40102014-11-14 22:34:56 +00007590
Nico Riecke50e59a2014-11-24 17:29:52 +00007591 // The use of a nested name specifier may trigger deprecation warnings.
7592 DiagnoseUseOfDecl(Named, IdentLoc);
Aaron Ballman43f40102014-11-14 22:34:56 +00007593
Douglas Gregor889ceb72009-02-03 19:21:40 +00007594 // C++ [namespace.udir]p1:
7595 // A using-directive specifies that the names in the nominated
7596 // namespace can be used in the scope in which the
7597 // using-directive appears after the using-directive. During
7598 // unqualified name lookup (3.4.1), the names appear as if they
7599 // were declared in the nearest enclosing namespace which
7600 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00007601 // namespace. [Note: in this context, "contains" means "contains
7602 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00007603
7604 // Find enclosing context containing both using-directive and
7605 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00007606 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007607 DeclContext *CommonAncestor = cast<DeclContext>(NS);
7608 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7609 CommonAncestor = CommonAncestor->getParent();
7610
Sebastian Redla6602e92009-11-23 15:34:23 +00007611 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00007612 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00007613 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007614
Douglas Gregora172e082011-03-26 22:25:30 +00007615 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00007616 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007617 Diag(IdentLoc, diag::warn_using_directive_in_header);
7618 }
7619
Douglas Gregor889ceb72009-02-03 19:21:40 +00007620 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007621 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00007622 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00007623 }
7624
Richard Smith54ecd982013-02-20 19:22:51 +00007625 if (UDir)
7626 ProcessDeclAttributeList(S, UDir, AttrList);
7627
John McCall48871652010-08-21 09:40:31 +00007628 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00007629}
7630
7631void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00007632 // If the scope has an associated entity and the using directive is at
7633 // namespace or translation unit scope, add the UsingDirectiveDecl into
7634 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007635 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00007636 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007637 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007638 else
Yaron Keren065da7c2014-05-20 18:23:05 +00007639 // Otherwise, it is at block scope. The using-directives will affect lookup
Richard Smith05afe5e2012-03-13 03:12:56 +00007640 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00007641 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007642}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007643
Douglas Gregorfec52632009-06-20 00:51:54 +00007644
John McCall48871652010-08-21 09:40:31 +00007645Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00007646 AccessSpecifier AS,
7647 bool HasUsingKeyword,
7648 SourceLocation UsingLoc,
7649 CXXScopeSpec &SS,
7650 UnqualifiedId &Name,
7651 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007652 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00007653 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00007654 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00007655
Douglas Gregor220f4272009-11-04 16:30:06 +00007656 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00007657 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00007658 case UnqualifiedId::IK_Identifier:
7659 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00007660 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00007661 case UnqualifiedId::IK_ConversionFunctionId:
7662 break;
7663
7664 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00007665 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00007666 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007667 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007668 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00007669 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00007670 diag::err_using_decl_constructor)
7671 << SS.getRange();
7672
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007673 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00007674
Craig Topperc3ec1492014-05-26 06:22:03 +00007675 return nullptr;
7676
Douglas Gregor220f4272009-11-04 16:30:06 +00007677 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007678 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00007679 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00007680 return nullptr;
7681
Douglas Gregor220f4272009-11-04 16:30:06 +00007682 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007683 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00007684 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007685 return nullptr;
Douglas Gregor220f4272009-11-04 16:30:06 +00007686 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007687
7688 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7689 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00007690 if (!TargetName)
Craig Topperc3ec1492014-05-26 06:22:03 +00007691 return nullptr;
John McCall3969e302009-12-08 07:46:18 +00007692
Richard Smithc2bc61b2013-03-18 21:12:30 +00007693 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00007694 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00007695 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00007696 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7697 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00007698 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00007699 }
7700
Douglas Gregorc4356532010-12-16 00:46:58 +00007701 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7702 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +00007703 return nullptr;
Douglas Gregorc4356532010-12-16 00:46:58 +00007704
John McCall3f746822009-11-17 05:59:44 +00007705 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007706 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007707 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007708 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00007709 if (UD)
7710 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00007711
John McCall48871652010-08-21 09:40:31 +00007712 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00007713}
7714
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007715/// \brief Determine whether a using declaration considers the given
7716/// declarations as "equivalent", e.g., if they are redeclarations of
7717/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00007718static bool
7719IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7720 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007721 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007722
Richard Smithdda56e42011-04-15 14:24:37 +00007723 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00007724 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007725 return Context.hasSameType(TD1->getUnderlyingType(),
7726 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007727
7728 return false;
7729}
7730
7731
John McCall84d87672009-12-10 09:41:52 +00007732/// Determines whether to create a using shadow decl for a particular
7733/// decl, given the set of decls existing prior to this using lookup.
7734bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00007735 const LookupResult &Previous,
7736 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00007737 // Diagnose finding a decl which is not from a base class of the
7738 // current class. We do this now because there are cases where this
7739 // function will silently decide not to build a shadow decl, which
7740 // will pre-empt further diagnostics.
7741 //
7742 // We don't need to do this in C++0x because we do the check once on
7743 // the qualifier.
7744 //
7745 // FIXME: diagnose the following if we care enough:
7746 // struct A { int foo; };
7747 // struct B : A { using A::foo; };
7748 // template <class T> struct C : A {};
7749 // template <class T> struct D : C<T> { using B::foo; } // <---
7750 // This is invalid (during instantiation) in C++03 because B::foo
7751 // resolves to the using decl in B, which is not a base class of D<T>.
7752 // We can't diagnose it immediately because C<T> is an unknown
7753 // specialization. The UsingShadowDecl in D<T> then points directly
7754 // to A::foo, which will look well-formed when we instantiate.
7755 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007756 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00007757 DeclContext *OrigDC = Orig->getDeclContext();
7758
7759 // Handle enums and anonymous structs.
7760 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7761 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7762 while (OrigRec->isAnonymousStructOrUnion())
7763 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7764
7765 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7766 if (OrigDC == CurContext) {
7767 Diag(Using->getLocation(),
7768 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007769 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007770 Diag(Orig->getLocation(), diag::note_using_decl_target);
7771 return true;
7772 }
7773
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007774 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00007775 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007776 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00007777 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007778 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007779 Diag(Orig->getLocation(), diag::note_using_decl_target);
7780 return true;
7781 }
7782 }
7783
7784 if (Previous.empty()) return false;
7785
7786 NamedDecl *Target = Orig;
7787 if (isa<UsingShadowDecl>(Target))
7788 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7789
John McCalla17e83e2009-12-11 02:33:26 +00007790 // If the target happens to be one of the previous declarations, we
7791 // don't have a conflict.
7792 //
7793 // FIXME: but we might be increasing its access, in which case we
7794 // should redeclare it.
Craig Topperc3ec1492014-05-26 06:22:03 +00007795 NamedDecl *NonTag = nullptr, *Tag = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00007796 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00007797 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7798 I != E; ++I) {
7799 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007800 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7801 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7802 PrevShadow = Shadow;
7803 FoundEquivalentDecl = true;
7804 }
John McCalla17e83e2009-12-11 02:33:26 +00007805
7806 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7807 }
7808
Richard Smithfd8634a2013-10-23 02:17:46 +00007809 if (FoundEquivalentDecl)
7810 return false;
7811
Alp Tokera2794f92014-01-22 07:29:52 +00007812 if (FunctionDecl *FD = Target->getAsFunction()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007813 NamedDecl *OldDecl = nullptr;
7814 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7815 /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00007816 case Ovl_Overload:
7817 return false;
7818
7819 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00007820 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007821 break;
Richard Smith18819302014-02-06 01:31:33 +00007822
John McCall84d87672009-12-10 09:41:52 +00007823 // We found a decl with the exact signature.
7824 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007825 // If we're in a record, we want to hide the target, so we
7826 // return true (without a diagnostic) to tell the caller not to
7827 // build a shadow decl.
7828 if (CurContext->isRecord())
7829 return true;
7830
7831 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00007832 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007833 break;
7834 }
7835
7836 Diag(Target->getLocation(), diag::note_using_decl_target);
7837 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7838 return true;
7839 }
7840
7841 // Target is not a function.
7842
John McCall84d87672009-12-10 09:41:52 +00007843 if (isa<TagDecl>(Target)) {
7844 // No conflict between a tag and a non-tag.
7845 if (!Tag) return false;
7846
John McCalle29c5cd2009-12-10 19:51:03 +00007847 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007848 Diag(Target->getLocation(), diag::note_using_decl_target);
7849 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7850 return true;
7851 }
7852
7853 // No conflict between a tag and a non-tag.
7854 if (!NonTag) return false;
7855
John McCalle29c5cd2009-12-10 19:51:03 +00007856 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007857 Diag(Target->getLocation(), diag::note_using_decl_target);
7858 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7859 return true;
7860}
7861
John McCall3f746822009-11-17 05:59:44 +00007862/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00007863UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00007864 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00007865 NamedDecl *Orig,
7866 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00007867
7868 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00007869 NamedDecl *Target = Orig;
7870 if (isa<UsingShadowDecl>(Target)) {
7871 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7872 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00007873 }
Richard Smithfd8634a2013-10-23 02:17:46 +00007874
John McCall3f746822009-11-17 05:59:44 +00007875 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00007876 = UsingShadowDecl::Create(Context, CurContext,
7877 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00007878 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00007879
Douglas Gregor457104e2010-09-29 04:25:11 +00007880 Shadow->setAccess(UD->getAccess());
7881 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7882 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007883
7884 Shadow->setPreviousDecl(PrevDecl);
7885
John McCall3f746822009-11-17 05:59:44 +00007886 if (S)
John McCall3969e302009-12-08 07:46:18 +00007887 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00007888 else
John McCall3969e302009-12-08 07:46:18 +00007889 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00007890
John McCall3969e302009-12-08 07:46:18 +00007891
John McCall84d87672009-12-10 09:41:52 +00007892 return Shadow;
7893}
John McCall3969e302009-12-08 07:46:18 +00007894
John McCall84d87672009-12-10 09:41:52 +00007895/// Hides a using shadow declaration. This is required by the current
7896/// using-decl implementation when a resolvable using declaration in a
7897/// class is followed by a declaration which would hide or override
7898/// one or more of the using decl's targets; for example:
7899///
7900/// struct Base { void foo(int); };
7901/// struct Derived : Base {
7902/// using Base::foo;
7903/// void foo(int);
7904/// };
7905///
7906/// The governing language is C++03 [namespace.udecl]p12:
7907///
7908/// When a using-declaration brings names from a base class into a
7909/// derived class scope, member functions in the derived class
7910/// override and/or hide member functions with the same name and
7911/// parameter types in a base class (rather than conflicting).
7912///
7913/// There are two ways to implement this:
7914/// (1) optimistically create shadow decls when they're not hidden
7915/// by existing declarations, or
7916/// (2) don't create any shadow decls (or at least don't make them
7917/// visible) until we've fully parsed/instantiated the class.
7918/// The problem with (1) is that we might have to retroactively remove
7919/// a shadow decl, which requires several O(n) operations because the
7920/// decl structures are (very reasonably) not designed for removal.
7921/// (2) avoids this but is very fiddly and phase-dependent.
7922void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00007923 if (Shadow->getDeclName().getNameKind() ==
7924 DeclarationName::CXXConversionFunctionName)
7925 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7926
John McCall84d87672009-12-10 09:41:52 +00007927 // Remove it from the DeclContext...
7928 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007929
John McCall84d87672009-12-10 09:41:52 +00007930 // ...and the scope, if applicable...
7931 if (S) {
John McCall48871652010-08-21 09:40:31 +00007932 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00007933 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007934 }
7935
John McCall84d87672009-12-10 09:41:52 +00007936 // ...and the using decl.
7937 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7938
7939 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00007940 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00007941}
7942
Richard Smith09d5b3a2014-05-01 00:35:04 +00007943/// Find the base specifier for a base class with the given type.
7944static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7945 QualType DesiredBase,
7946 bool &AnyDependentBases) {
7947 // Check whether the named type is a direct base class.
7948 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7949 for (auto &Base : Derived->bases()) {
7950 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7951 if (CanonicalDesiredBase == BaseType)
7952 return &Base;
7953 if (BaseType->isDependentType())
7954 AnyDependentBases = true;
7955 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007956 return nullptr;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007957}
7958
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007959namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007960class UsingValidatorCCC : public CorrectionCandidateCallback {
7961public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007962 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007963 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007964 : HasTypenameKeyword(HasTypenameKeyword),
Richard Smith09d5b3a2014-05-01 00:35:04 +00007965 IsInstantiation(IsInstantiation), OldNNS(NNS),
7966 RequireMemberOf(RequireMemberOf) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007967
Craig Toppera798a9d2014-03-02 09:32:10 +00007968 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007969 NamedDecl *ND = Candidate.getCorrectionDecl();
7970
7971 // Keywords are not valid here.
7972 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007973 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007974
7975 // Completely unqualified names are invalid for a 'using' declaration.
7976 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7977 return false;
7978
Richard Smith09d5b3a2014-05-01 00:35:04 +00007979 if (RequireMemberOf) {
7980 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7981 if (FoundRecord && FoundRecord->isInjectedClassName()) {
7982 // No-one ever wants a using-declaration to name an injected-class-name
7983 // of a base class, unless they're declaring an inheriting constructor.
7984 ASTContext &Ctx = ND->getASTContext();
7985 if (!Ctx.getLangOpts().CPlusPlus11)
7986 return false;
7987 QualType FoundType = Ctx.getRecordType(FoundRecord);
7988
7989 // Check that the injected-class-name is named as a member of its own
7990 // type; we don't want to suggest 'using Derived::Base;', since that
7991 // means something else.
7992 NestedNameSpecifier *Specifier =
7993 Candidate.WillReplaceSpecifier()
7994 ? Candidate.getCorrectionSpecifier()
7995 : OldNNS;
7996 if (!Specifier->getAsType() ||
7997 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
7998 return false;
7999
8000 // Check that this inheriting constructor declaration actually names a
8001 // direct base class of the current class.
8002 bool AnyDependentBases = false;
8003 if (!findDirectBaseWithType(RequireMemberOf,
8004 Ctx.getRecordType(FoundRecord),
8005 AnyDependentBases) &&
8006 !AnyDependentBases)
8007 return false;
8008 } else {
8009 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
8010 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
8011 return false;
8012
8013 // FIXME: Check that the base class member is accessible?
8014 }
8015 }
8016
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008017 if (isa<TypeDecl>(ND))
8018 return HasTypenameKeyword || !IsInstantiation;
8019
8020 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008021 }
8022
8023private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008024 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008025 bool IsInstantiation;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008026 NestedNameSpecifier *OldNNS;
Richard Smith21866c32014-04-30 18:03:21 +00008027 CXXRecordDecl *RequireMemberOf;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008028};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008029} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008030
John McCalle61f2ba2009-11-18 02:36:19 +00008031/// Builds a using declaration.
8032///
8033/// \param IsInstantiation - Whether this call arises from an
8034/// instantiation of an unresolved using declaration. We treat
8035/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00008036NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
8037 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00008038 CXXScopeSpec &SS,
Richard Smith09d5b3a2014-05-01 00:35:04 +00008039 DeclarationNameInfo NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00008040 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00008041 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008042 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00008043 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00008044 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008045 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00008046 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00008047
Anders Carlssonf038fc22009-08-28 05:49:21 +00008048 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00008049
Anders Carlsson59140b32009-08-28 03:16:11 +00008050 if (SS.isEmpty()) {
8051 Diag(IdentLoc, diag::err_using_requires_qualname);
Craig Topperc3ec1492014-05-26 06:22:03 +00008052 return nullptr;
Anders Carlsson59140b32009-08-28 03:16:11 +00008053 }
Mike Stump11289f42009-09-09 15:08:12 +00008054
John McCall84d87672009-12-10 09:41:52 +00008055 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008056 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00008057 ForRedeclaration);
8058 Previous.setHideTags(false);
8059 if (S) {
8060 LookupName(Previous, S);
8061
8062 // It is really dumb that we have to do this.
8063 LookupResult::Filter F = Previous.makeFilter();
8064 while (F.hasNext()) {
8065 NamedDecl *D = F.next();
8066 if (!isDeclInScope(D, CurContext, S))
8067 F.erase();
Richard Smith83e78f52014-04-11 01:03:38 +00008068 // If we found a local extern declaration that's not ordinarily visible,
8069 // and this declaration is being added to a non-block scope, ignore it.
8070 // We're only checking for scope conflicts here, not also for violations
8071 // of the linkage rules.
8072 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
8073 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
8074 F.erase();
John McCall84d87672009-12-10 09:41:52 +00008075 }
8076 F.done();
8077 } else {
8078 assert(IsInstantiation && "no scope in non-instantiation");
8079 assert(CurContext->isRecord() && "scope not record in instantiation");
8080 LookupQualifiedName(Previous, CurContext);
8081 }
8082
John McCall84d87672009-12-10 09:41:52 +00008083 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008084 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
8085 SS, IdentLoc, Previous))
Craig Topperc3ec1492014-05-26 06:22:03 +00008086 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00008087
8088 // Check for bad qualifiers.
Richard Smith7ad0b882014-04-02 21:44:35 +00008089 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00008090 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00008091
John McCall84c16cf2009-11-12 03:15:40 +00008092 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00008093 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008094 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00008095 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008096 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00008097 // FIXME: not all declaration name kinds are legal here
8098 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
8099 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008100 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008101 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00008102 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008103 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
8104 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00008105 }
Richard Smith09d5b3a2014-05-01 00:35:04 +00008106 D->setAccess(AS);
8107 CurContext->addDecl(D);
8108 return D;
Anders Carlssonf038fc22009-08-28 05:49:21 +00008109 }
John McCallb96ec562009-12-04 22:46:56 +00008110
Richard Smith09d5b3a2014-05-01 00:35:04 +00008111 auto Build = [&](bool Invalid) {
8112 UsingDecl *UD =
8113 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
8114 HasTypenameKeyword);
8115 UD->setAccess(AS);
8116 CurContext->addDecl(UD);
8117 UD->setInvalidDecl(Invalid);
John McCall3969e302009-12-08 07:46:18 +00008118 return UD;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008119 };
8120 auto BuildInvalid = [&]{ return Build(true); };
8121 auto BuildValid = [&]{ return Build(false); };
8122
8123 if (RequireCompleteDeclContext(SS, LookupContext))
8124 return BuildInvalid();
Anders Carlsson59140b32009-08-28 03:16:11 +00008125
Richard Smith78163e22015-04-01 19:31:06 +00008126 // Look up the target name.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008127 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00008128
John McCall3969e302009-12-08 07:46:18 +00008129 // Unlike most lookups, we don't always want to hide tag
8130 // declarations: tag names are visible through the using declaration
8131 // even if hidden by ordinary names, *except* in a dependent context
8132 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00008133 if (!IsInstantiation)
8134 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00008135
John McCall5dadb652012-04-07 03:04:20 +00008136 // For the purposes of this lookup, we have a base object type
8137 // equal to that of the current context.
8138 if (CurContext->isRecord()) {
8139 R.setBaseObjectType(
8140 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
8141 }
8142
John McCall27b18f82009-11-17 02:14:36 +00008143 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00008144
Richard Smith78163e22015-04-01 19:31:06 +00008145 // Try to correct typos if possible. If constructor name lookup finds no
8146 // results, that means the named class has no explicit constructors, and we
8147 // suppressed declaring implicit ones (probably because it's dependent or
8148 // invalid).
8149 if (R.empty() &&
8150 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00008151 if (TypoCorrection Corrected = CorrectTypo(
8152 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
8153 llvm::make_unique<UsingValidatorCCC>(
8154 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
8155 dyn_cast<CXXRecordDecl>(CurContext)),
8156 CTK_ErrorRecovery)) {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008157 // We reject any correction for which ND would be NULL.
8158 NamedDecl *ND = Corrected.getCorrectionDecl();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008159
Richard Smithf9b15102013-08-17 00:46:16 +00008160 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008161 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00008162 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
8163 << NameInfo.getName() << LookupContext << 0
8164 << SS.getRange());
Richard Smith09d5b3a2014-05-01 00:35:04 +00008165
8166 // If we corrected to an inheriting constructor, handle it as one.
8167 auto *RD = dyn_cast<CXXRecordDecl>(ND);
8168 if (RD && RD->isInjectedClassName()) {
8169 // Fix up the information we'll use to build the using declaration.
8170 if (Corrected.WillReplaceSpecifier()) {
8171 NestedNameSpecifierLocBuilder Builder;
8172 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
8173 QualifierLoc.getSourceRange());
8174 QualifierLoc = Builder.getWithLocInContext(Context);
8175 }
8176
8177 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
8178 Context.getCanonicalType(Context.getRecordType(RD))));
Craig Topperc3ec1492014-05-26 06:22:03 +00008179 NameInfo.setNamedTypeInfo(nullptr);
Richard Smith78163e22015-04-01 19:31:06 +00008180 for (auto *Ctor : LookupConstructors(RD))
8181 R.addDecl(Ctor);
8182 } else {
8183 // FIXME: Pick up all the declarations if we found an overloaded function.
8184 R.addDecl(ND);
Richard Smith09d5b3a2014-05-01 00:35:04 +00008185 }
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008186 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00008187 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008188 << NameInfo.getName() << LookupContext << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008189 return BuildInvalid();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008190 }
Douglas Gregorfec52632009-06-20 00:51:54 +00008191 }
8192
Richard Smith09d5b3a2014-05-01 00:35:04 +00008193 if (R.isAmbiguous())
8194 return BuildInvalid();
Mike Stump11289f42009-09-09 15:08:12 +00008195
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008196 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00008197 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00008198 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00008199 Diag(IdentLoc, diag::err_using_typename_non_type);
8200 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8201 Diag((*I)->getUnderlyingDecl()->getLocation(),
8202 diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00008203 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00008204 }
8205 } else {
8206 // If we asked for a non-typename and we got a type, error out,
8207 // but only if this is an instantiation of an unresolved using
8208 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00008209 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00008210 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
8211 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00008212 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00008213 }
Anders Carlsson59140b32009-08-28 03:16:11 +00008214 }
8215
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008216 // C++0x N2914 [namespace.udecl]p6:
8217 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00008218 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008219 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
8220 << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008221 return BuildInvalid();
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008222 }
Mike Stump11289f42009-09-09 15:08:12 +00008223
Richard Smith09d5b3a2014-05-01 00:35:04 +00008224 UsingDecl *UD = BuildValid();
Richard Smith78163e22015-04-01 19:31:06 +00008225
8226 // The normal rules do not apply to inheriting constructor declarations.
8227 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
8228 // Suppress access diagnostics; the access check is instead performed at the
8229 // point of use for an inheriting constructor.
8230 R.suppressDiagnostics();
8231 CheckInheritingConstructorUsingDecl(UD);
8232 return UD;
8233 }
8234
8235 // Otherwise, look up the target name.
8236
John McCall84d87672009-12-10 09:41:52 +00008237 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008238 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00008239 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
8240 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00008241 }
John McCall3f746822009-11-17 05:59:44 +00008242
8243 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00008244}
8245
Sebastian Redl08905022011-02-05 19:23:19 +00008246/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00008247bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008248 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00008249
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008250 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00008251 assert(SourceType &&
8252 "Using decl naming constructor doesn't have type in scope spec.");
8253 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
8254
8255 // Check whether the named type is a direct base class.
Richard Smith09d5b3a2014-05-01 00:35:04 +00008256 bool AnyDependentBases = false;
8257 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
8258 AnyDependentBases);
8259 if (!Base && !AnyDependentBases) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008260 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00008261 diag::err_using_decl_constructor_not_in_direct_base)
8262 << UD->getNameInfo().getSourceRange()
8263 << QualType(SourceType, 0) << TargetClass;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008264 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00008265 return true;
8266 }
8267
Richard Smith09d5b3a2014-05-01 00:35:04 +00008268 if (Base)
8269 Base->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00008270
8271 return false;
8272}
8273
John McCall84d87672009-12-10 09:41:52 +00008274/// Checks that the given using declaration is not an invalid
8275/// redeclaration. Note that this is checking only for the using decl
8276/// itself, not for any ill-formedness among the UsingShadowDecls.
8277bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008278 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00008279 const CXXScopeSpec &SS,
8280 SourceLocation NameLoc,
8281 const LookupResult &Prev) {
8282 // C++03 [namespace.udecl]p8:
8283 // C++0x [namespace.udecl]p10:
8284 // A using-declaration is a declaration and can therefore be used
8285 // repeatedly where (and only where) multiple declarations are
8286 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00008287 //
John McCall032092f2010-11-29 18:01:58 +00008288 // That's in non-member contexts.
8289 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00008290 return false;
8291
Aaron Ballman4a979672014-01-03 13:56:08 +00008292 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall84d87672009-12-10 09:41:52 +00008293
8294 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
8295 NamedDecl *D = *I;
8296
8297 bool DTypename;
8298 NestedNameSpecifier *DQual;
8299 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008300 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008301 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008302 } else if (UnresolvedUsingValueDecl *UD
8303 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
8304 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008305 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008306 } else if (UnresolvedUsingTypenameDecl *UD
8307 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
8308 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008309 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008310 } else continue;
8311
8312 // using decls differ if one says 'typename' and the other doesn't.
8313 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008314 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00008315
8316 // using decls differ if they name different scopes (but note that
8317 // template instantiation can cause this check to trigger when it
8318 // didn't before instantiation).
8319 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
8320 Context.getCanonicalNestedNameSpecifier(DQual))
8321 continue;
8322
8323 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00008324 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00008325 return true;
8326 }
8327
8328 return false;
8329}
8330
John McCall3969e302009-12-08 07:46:18 +00008331
John McCallb96ec562009-12-04 22:46:56 +00008332/// Checks that the given nested-name qualifier used in a using decl
8333/// in the current context is appropriately related to the current
8334/// scope. If an error is found, diagnoses it and returns true.
8335bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
8336 const CXXScopeSpec &SS,
Richard Smith7ad0b882014-04-02 21:44:35 +00008337 const DeclarationNameInfo &NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00008338 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00008339 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00008340
John McCall3969e302009-12-08 07:46:18 +00008341 if (!CurContext->isRecord()) {
8342 // C++03 [namespace.udecl]p3:
8343 // C++0x [namespace.udecl]p8:
8344 // A using-declaration for a class member shall be a member-declaration.
8345
8346 // If we weren't able to compute a valid scope, it must be a
8347 // dependent class scope.
8348 if (!NamedContext || NamedContext->isRecord()) {
David Majnemer4d2de1b02014-12-17 02:41:36 +00008349 auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext);
Richard Smith7ad0b882014-04-02 21:44:35 +00008350 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
Craig Topperc3ec1492014-05-26 06:22:03 +00008351 RD = nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00008352
John McCall3969e302009-12-08 07:46:18 +00008353 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
8354 << SS.getRange();
Richard Smith7ad0b882014-04-02 21:44:35 +00008355
8356 // If we have a complete, non-dependent source type, try to suggest a
8357 // way to get the same effect.
8358 if (!RD)
8359 return true;
8360
8361 // Find what this using-declaration was referring to.
8362 LookupResult R(*this, NameInfo, LookupOrdinaryName);
8363 R.setHideTags(false);
8364 R.suppressDiagnostics();
8365 LookupQualifiedName(R, RD);
8366
8367 if (R.getAsSingle<TypeDecl>()) {
8368 if (getLangOpts().CPlusPlus11) {
8369 // Convert 'using X::Y;' to 'using Y = X::Y;'.
8370 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
8371 << 0 // alias declaration
8372 << FixItHint::CreateInsertion(SS.getBeginLoc(),
8373 NameInfo.getName().getAsString() +
8374 " = ");
8375 } else {
8376 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
8377 SourceLocation InsertLoc =
8378 PP.getLocForEndOfToken(NameInfo.getLocEnd());
8379 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
8380 << 1 // typedef declaration
8381 << FixItHint::CreateReplacement(UsingLoc, "typedef")
8382 << FixItHint::CreateInsertion(
8383 InsertLoc, " " + NameInfo.getName().getAsString());
8384 }
8385 } else if (R.getAsSingle<VarDecl>()) {
8386 // Don't provide a fixit outside C++11 mode; we don't want to suggest
8387 // repeating the type of the static data member here.
8388 FixItHint FixIt;
8389 if (getLangOpts().CPlusPlus11) {
8390 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8391 FixIt = FixItHint::CreateReplacement(
8392 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
8393 }
8394
8395 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8396 << 2 // reference declaration
8397 << FixIt;
8398 }
John McCall3969e302009-12-08 07:46:18 +00008399 return true;
8400 }
8401
8402 // Otherwise, everything is known to be fine.
8403 return false;
8404 }
8405
8406 // The current scope is a record.
8407
8408 // If the named context is dependent, we can't decide much.
8409 if (!NamedContext) {
8410 // FIXME: in C++0x, we can diagnose if we can prove that the
8411 // nested-name-specifier does not refer to a base class, which is
8412 // still possible in some cases.
8413
8414 // Otherwise we have to conservatively report that things might be
8415 // okay.
8416 return false;
8417 }
8418
8419 if (!NamedContext->isRecord()) {
8420 // Ideally this would point at the last name in the specifier,
8421 // but we don't have that level of source info.
8422 Diag(SS.getRange().getBegin(),
8423 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00008424 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00008425 return true;
8426 }
8427
Douglas Gregor7c842292010-12-21 07:41:49 +00008428 if (!NamedContext->isDependentContext() &&
8429 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8430 return true;
8431
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008432 if (getLangOpts().CPlusPlus11) {
John McCall3969e302009-12-08 07:46:18 +00008433 // C++0x [namespace.udecl]p3:
8434 // In a using-declaration used as a member-declaration, the
8435 // nested-name-specifier shall name a base class of the class
8436 // being defined.
8437
8438 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8439 cast<CXXRecordDecl>(NamedContext))) {
8440 if (CurContext == NamedContext) {
8441 Diag(NameLoc,
8442 diag::err_using_decl_nested_name_specifier_is_current_class)
8443 << SS.getRange();
8444 return true;
8445 }
8446
8447 Diag(SS.getRange().getBegin(),
8448 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00008449 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00008450 << cast<CXXRecordDecl>(CurContext)
8451 << SS.getRange();
8452 return true;
8453 }
8454
8455 return false;
8456 }
8457
8458 // C++03 [namespace.udecl]p4:
8459 // A using-declaration used as a member-declaration shall refer
8460 // to a member of a base class of the class being defined [etc.].
8461
8462 // Salient point: SS doesn't have to name a base class as long as
8463 // lookup only finds members from base classes. Therefore we can
8464 // diagnose here only if we can prove that that can't happen,
8465 // i.e. if the class hierarchies provably don't intersect.
8466
8467 // TODO: it would be nice if "definitely valid" results were cached
8468 // in the UsingDecl and UsingShadowDecl so that these checks didn't
8469 // need to be repeated.
8470
8471 struct UserData {
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00008472 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall3969e302009-12-08 07:46:18 +00008473
8474 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
8475 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8476 Data->Bases.insert(Base);
8477 return true;
8478 }
8479
8480 bool hasDependentBases(const CXXRecordDecl *Class) {
8481 return !Class->forallBases(collect, this);
8482 }
8483
8484 /// Returns true if the base is dependent or is one of the
8485 /// accumulated base classes.
8486 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
8487 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8488 return !Data->Bases.count(Base);
8489 }
8490
8491 bool mightShareBases(const CXXRecordDecl *Class) {
8492 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
8493 }
8494 };
8495
8496 UserData Data;
8497
8498 // Returns false if we find a dependent base.
8499 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
8500 return false;
8501
8502 // Returns false if the class has a dependent base or if it or one
8503 // of its bases is present in the base set of the current context.
8504 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
8505 return false;
8506
8507 Diag(SS.getRange().getBegin(),
8508 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00008509 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00008510 << cast<CXXRecordDecl>(CurContext)
8511 << SS.getRange();
8512
8513 return true;
John McCallb96ec562009-12-04 22:46:56 +00008514}
8515
Richard Smithdda56e42011-04-15 14:24:37 +00008516Decl *Sema::ActOnAliasDeclaration(Scope *S,
8517 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008518 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00008519 SourceLocation UsingLoc,
8520 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00008521 AttributeList *AttrList,
David Majnemerf9bde282015-03-11 06:45:39 +00008522 TypeResult Type,
8523 Decl *DeclFromDeclSpec) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00008524 // Skip up to the relevant declaration scope.
8525 while (S->getFlags() & Scope::TemplateParamScope)
8526 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00008527 assert((S->getFlags() & Scope::DeclScope) &&
8528 "got alias-declaration outside of declaration scope");
8529
8530 if (Type.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00008531 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008532
8533 bool Invalid = false;
8534 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
Craig Topperc3ec1492014-05-26 06:22:03 +00008535 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky82e47802011-05-02 01:07:19 +00008536 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00008537
8538 if (DiagnoseClassNameShadow(CurContext, NameInfo))
Craig Topperc3ec1492014-05-26 06:22:03 +00008539 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008540
8541 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008542 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00008543 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008544 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8545 TInfo->getTypeLoc().getBeginLoc());
8546 }
Richard Smithdda56e42011-04-15 14:24:37 +00008547
8548 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8549 LookupName(Previous, S);
8550
8551 // Warn about shadowing the name of a template parameter.
8552 if (Previous.isSingleResult() &&
8553 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00008554 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00008555 Previous.clear();
8556 }
8557
8558 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8559 "name in alias declaration must be an identifier");
8560 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8561 Name.StartLocation,
8562 Name.Identifier, TInfo);
8563
8564 NewTD->setAccess(AS);
8565
8566 if (Invalid)
8567 NewTD->setInvalidDecl();
8568
Richard Smith54ecd982013-02-20 19:22:51 +00008569 ProcessDeclAttributeList(S, NewTD, AttrList);
8570
Richard Smith3f1b5d02011-05-05 21:57:07 +00008571 CheckTypedefForVariablyModifiedType(S, NewTD);
8572 Invalid |= NewTD->isInvalidDecl();
8573
Richard Smithdda56e42011-04-15 14:24:37 +00008574 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008575
8576 NamedDecl *NewND;
8577 if (TemplateParamLists.size()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008578 TypeAliasTemplateDecl *OldDecl = nullptr;
8579 TemplateParameterList *OldTemplateParams = nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008580
8581 if (TemplateParamLists.size() != 1) {
8582 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008583 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8584 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00008585 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008586 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00008587
8588 // Only consider previous declarations in the same scope.
8589 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8590 /*ExplicitInstantiationOrSpecialization*/false);
8591 if (!Previous.empty()) {
8592 Redeclaration = true;
8593
8594 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8595 if (!OldDecl && !Invalid) {
8596 Diag(UsingLoc, diag::err_redefinition_different_kind)
8597 << Name.Identifier;
8598
8599 NamedDecl *OldD = Previous.getRepresentativeDecl();
8600 if (OldD->getLocation().isValid())
8601 Diag(OldD->getLocation(), diag::note_previous_definition);
8602
8603 Invalid = true;
8604 }
8605
8606 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8607 if (TemplateParameterListsAreEqual(TemplateParams,
8608 OldDecl->getTemplateParameters(),
8609 /*Complain=*/true,
8610 TPL_TemplateMatch))
8611 OldTemplateParams = OldDecl->getTemplateParameters();
8612 else
8613 Invalid = true;
8614
8615 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8616 if (!Invalid &&
8617 !Context.hasSameType(OldTD->getUnderlyingType(),
8618 NewTD->getUnderlyingType())) {
8619 // FIXME: The C++0x standard does not clearly say this is ill-formed,
8620 // but we can't reasonably accept it.
8621 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8622 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8623 if (OldTD->getLocation().isValid())
8624 Diag(OldTD->getLocation(), diag::note_previous_definition);
8625 Invalid = true;
8626 }
8627 }
8628 }
8629
8630 // Merge any previous default template arguments into our parameters,
8631 // and check the parameter list.
8632 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8633 TPC_TypeAliasTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +00008634 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008635
8636 TypeAliasTemplateDecl *NewDecl =
8637 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8638 Name.Identifier, TemplateParams,
8639 NewTD);
Richard Smith43ccec8e2014-08-26 03:52:16 +00008640 NewTD->setDescribedAliasTemplate(NewDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008641
8642 NewDecl->setAccess(AS);
8643
8644 if (Invalid)
8645 NewDecl->setInvalidDecl();
8646 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00008647 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008648
8649 NewND = NewDecl;
8650 } else {
David Majnemerf9bde282015-03-11 06:45:39 +00008651 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
8652 setTagNameForLinkagePurposes(TD, NewTD);
8653 handleTagNumbering(TD, S);
8654 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00008655 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8656 NewND = NewTD;
8657 }
Richard Smithdda56e42011-04-15 14:24:37 +00008658
8659 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00008660 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00008661
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00008662 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008663 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00008664}
8665
Richard Smithf4634362014-09-03 23:11:22 +00008666Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
8667 SourceLocation AliasLoc,
8668 IdentifierInfo *Alias, CXXScopeSpec &SS,
8669 SourceLocation IdentLoc,
8670 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00008671
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008672 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00008673 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8674 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008675
John McCall27b18f82009-11-17 02:14:36 +00008676 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00008677 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008678
John McCall9f3059a2009-10-09 21:13:30 +00008679 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008680 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00008681 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00008682 return nullptr;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00008683 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00008684 }
Richard Smithf4634362014-09-03 23:11:22 +00008685 assert(!R.isAmbiguous() && !R.empty());
8686
8687 // Check if we have a previous declaration with the same name.
8688 NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8689 ForRedeclaration);
8690 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
8691 PrevDecl = nullptr;
8692
Aaron Ballman43f40102014-11-14 22:34:56 +00008693 NamedDecl *ND = R.getFoundDecl();
8694
Richard Smithf4634362014-09-03 23:11:22 +00008695 if (PrevDecl) {
8696 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8697 // We already have an alias with the same name that points to the same
8698 // namespace; check that it matches.
Aaron Ballman43f40102014-11-14 22:34:56 +00008699 if (!AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
Richard Smithf4634362014-09-03 23:11:22 +00008700 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
8701 << Alias;
8702 Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias)
8703 << AD->getNamespace();
8704 return nullptr;
8705 }
8706 } else {
8707 unsigned DiagID = isa<NamespaceDecl>(PrevDecl)
8708 ? diag::err_redefinition
8709 : diag::err_redefinition_different_kind;
8710 Diag(AliasLoc, DiagID) << Alias;
8711 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8712 return nullptr;
8713 }
8714 }
Mike Stump11289f42009-09-09 15:08:12 +00008715
Nico Riecke50e59a2014-11-24 17:29:52 +00008716 // The use of a nested name specifier may trigger deprecation warnings.
Aaron Ballman43f40102014-11-14 22:34:56 +00008717 DiagnoseUseOfDecl(ND, IdentLoc);
8718
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008719 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00008720 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00008721 Alias, SS.getWithLocInContext(Context),
Aaron Ballman43f40102014-11-14 22:34:56 +00008722 IdentLoc, ND);
Richard Smithf4634362014-09-03 23:11:22 +00008723 if (PrevDecl)
8724 AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl));
Mike Stump11289f42009-09-09 15:08:12 +00008725
John McCalld8d0d432010-02-16 06:53:13 +00008726 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00008727 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00008728}
8729
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008730Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008731Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8732 CXXMethodDecl *MD) {
8733 CXXRecordDecl *ClassDecl = MD->getParent();
8734
Douglas Gregor6d880b12010-07-01 22:31:05 +00008735 // C++ [except.spec]p14:
8736 // An implicitly declared special member function (Clause 12) shall have an
8737 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00008738 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008739 if (ClassDecl->isInvalidDecl())
8740 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00008741
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008742 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008743 for (const auto &B : ClassDecl->bases()) {
8744 if (B.isVirtual()) // Handled below.
Douglas Gregor6d880b12010-07-01 22:31:05 +00008745 continue;
8746
Aaron Ballman574705e2014-03-13 15:41:46 +00008747 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008748 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008749 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8750 // If this is a deleted function, add it anyway. This might be conformant
8751 // with the standard. This might not. I'm not sure. It might not matter.
8752 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008753 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008754 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008755 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008756
8757 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008758 for (const auto &B : ClassDecl->vbases()) {
8759 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008760 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008761 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8762 // If this is a deleted function, add it anyway. This might be conformant
8763 // with the standard. This might not. I'm not sure. It might not matter.
8764 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008765 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008766 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008767 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008768
8769 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008770 for (const auto *F : ClassDecl->fields()) {
Richard Smith938f40b2011-06-11 17:19:42 +00008771 if (F->hasInClassInitializer()) {
8772 if (Expr *E = F->getInClassInitializer())
8773 ExceptSpec.CalledExpr(E);
Richard Smith938f40b2011-06-11 17:19:42 +00008774 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00008775 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00008776 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8777 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8778 // If this is a deleted function, add it anyway. This might be conformant
8779 // with the standard. This might not. I'm not sure. It might not matter.
8780 // In particular, the problem is that this function never gets called. It
8781 // might just be ill-formed because this function attempts to refer to
8782 // a deleted function here.
8783 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008784 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008785 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008786 }
John McCalldb40c7f2010-12-14 08:05:40 +00008787
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008788 return ExceptSpec;
8789}
8790
Richard Smithc2bc61b2013-03-18 21:12:30 +00008791Sema::ImplicitExceptionSpecification
Richard Smithb7151b92013-04-10 06:11:48 +00008792Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8793 CXXRecordDecl *ClassDecl = CD->getParent();
8794
8795 // C++ [except.spec]p14:
8796 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00008797 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00008798 if (ClassDecl->isInvalidDecl())
8799 return ExceptSpec;
8800
8801 // Inherited constructor.
8802 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8803 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8804 // FIXME: Copying or moving the parameters could add extra exceptions to the
8805 // set, as could the default arguments for the inherited constructor. This
8806 // will be addressed when we implement the resolution of core issue 1351.
8807 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8808
8809 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008810 for (const auto &B : ClassDecl->bases()) {
8811 if (B.isVirtual()) // Handled below.
Richard Smithb7151b92013-04-10 06:11:48 +00008812 continue;
8813
Aaron Ballman574705e2014-03-13 15:41:46 +00008814 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008815 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8816 if (BaseClassDecl == InheritedDecl)
8817 continue;
8818 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8819 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008820 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008821 }
8822 }
8823
8824 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008825 for (const auto &B : ClassDecl->vbases()) {
8826 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008827 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8828 if (BaseClassDecl == InheritedDecl)
8829 continue;
8830 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8831 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008832 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008833 }
8834 }
8835
8836 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008837 for (const auto *F : ClassDecl->fields()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008838 if (F->hasInClassInitializer()) {
8839 if (Expr *E = F->getInClassInitializer())
8840 ExceptSpec.CalledExpr(E);
Richard Smithb7151b92013-04-10 06:11:48 +00008841 } else if (const RecordType *RecordTy
8842 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8843 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8844 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8845 if (Constructor)
8846 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8847 }
8848 }
8849
Richard Smithc2bc61b2013-03-18 21:12:30 +00008850 return ExceptSpec;
8851}
8852
Richard Smith8bf22e52012-11-29 01:34:07 +00008853namespace {
8854/// RAII object to register a special member as being currently declared.
8855struct DeclaringSpecialMember {
8856 Sema &S;
8857 Sema::SpecialMemberDecl D;
8858 bool WasAlreadyBeingDeclared;
8859
8860 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8861 : S(S), D(RD, CSM) {
David Blaikie82e95a32014-11-19 07:49:47 +00008862 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
Richard Smith8bf22e52012-11-29 01:34:07 +00008863 if (WasAlreadyBeingDeclared)
8864 // This almost never happens, but if it does, ensure that our cache
8865 // doesn't contain a stale result.
8866 S.SpecialMemberCache.clear();
8867
8868 // FIXME: Register a note to be produced if we encounter an error while
8869 // declaring the special member.
8870 }
8871 ~DeclaringSpecialMember() {
8872 if (!WasAlreadyBeingDeclared)
8873 S.SpecialMembersBeingDeclared.erase(D);
8874 }
8875
8876 /// \brief Are we already trying to declare this special member?
8877 bool isAlreadyBeingDeclared() const {
8878 return WasAlreadyBeingDeclared;
8879 }
8880};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008881}
Richard Smith8bf22e52012-11-29 01:34:07 +00008882
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008883CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8884 CXXRecordDecl *ClassDecl) {
8885 // C++ [class.ctor]p5:
8886 // A default constructor for a class X is a constructor of class X
8887 // that can be called without an argument. If there is no
8888 // user-declared constructor for class X, a default constructor is
8889 // implicitly declared. An implicitly-declared default constructor
8890 // is an inline public member of its class.
Eli Bendersky9a220fc2014-09-29 20:38:29 +00008891 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008892 "Should not build implicit default constructor!");
8893
Richard Smith8bf22e52012-11-29 01:34:07 +00008894 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8895 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00008896 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00008897
Richard Smithb5800092012-06-10 05:43:50 +00008898 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8899 CXXDefaultConstructor,
8900 false);
8901
Douglas Gregor6d880b12010-07-01 22:31:05 +00008902 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008903 CanQualType ClassType
8904 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008905 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008906 DeclarationName Name
8907 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008908 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00008909 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00008910 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8911 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8912 /*isImplicitlyDeclared=*/true, Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008913 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00008914 DefaultCon->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +00008915
8916 if (getLangOpts().CUDA) {
8917 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
8918 DefaultCon,
8919 /* ConstRHS */ false,
8920 /* Diagnose */ false);
8921 }
Richard Smithd3b5c9082012-07-27 04:22:15 +00008922
8923 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008924 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008925 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008926
Richard Smith6b02d462012-12-08 08:32:28 +00008927 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8928 // constructors is easy to compute.
8929 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8930
8931 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008932 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008933
Douglas Gregor9672f922010-07-03 00:47:00 +00008934 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00008935 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00008936
Douglas Gregor0be31a22010-07-02 17:43:08 +00008937 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00008938 PushOnScopeChains(DefaultCon, S, false);
8939 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008940
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008941 return DefaultCon;
8942}
8943
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008944void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8945 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008946 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008947 !Constructor->doesThisDeclarationHaveABody() &&
8948 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008949 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008950
Anders Carlsson423f5d82010-04-23 16:04:08 +00008951 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00008952 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00008953
Eli Friedmaneaf34142012-10-18 20:14:08 +00008954 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008955 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00008956 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008957 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008958 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008959 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00008960 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00008961 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00008962 }
Douglas Gregor73193272010-09-20 16:48:21 +00008963
Ben Langmuir2f8e6b82014-09-25 20:55:00 +00008964 // The exception specification is needed because we are defining the
8965 // function.
8966 ResolveExceptionSpec(CurrentLocation,
8967 Constructor->getType()->castAs<FunctionProtoType>());
8968
Daniel Jasperb3b0b802014-06-20 08:44:22 +00008969 SourceLocation Loc = Constructor->getLocEnd().isValid()
8970 ? Constructor->getLocEnd()
8971 : Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008972 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +00008973
Eli Friedman276dd182013-09-05 00:02:25 +00008974 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +00008975 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008976
8977 if (ASTMutationListener *L = getASTMutationListener()) {
8978 L->CompletedImplicitDefinition(Constructor);
8979 }
Richard Trieuef64e942013-10-25 00:56:00 +00008980
8981 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008982}
8983
Richard Smith938f40b2011-06-11 17:19:42 +00008984void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008985 // Perform any delayed checks on exception specifications.
8986 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +00008987}
8988
Richard Smith185be182013-04-10 05:48:59 +00008989namespace {
8990/// Information on inheriting constructors to declare.
8991class InheritingConstructorInfo {
8992public:
8993 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8994 : SemaRef(SemaRef), Derived(Derived) {
8995 // Mark the constructors that we already have in the derived class.
8996 //
8997 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8998 // unless there is a user-declared constructor with the same signature in
8999 // the class where the using-declaration appears.
9000 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
9001 }
9002
9003 void inheritAll(CXXRecordDecl *RD) {
9004 visitAll(RD, &InheritingConstructorInfo::inherit);
9005 }
9006
9007private:
9008 /// Information about an inheriting constructor.
9009 struct InheritingConstructor {
9010 InheritingConstructor()
Craig Topperc3ec1492014-05-26 06:22:03 +00009011 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
Richard Smith185be182013-04-10 05:48:59 +00009012
9013 /// If \c true, a constructor with this signature is already declared
9014 /// in the derived class.
9015 bool DeclaredInDerived;
9016
9017 /// The constructor which is inherited.
9018 const CXXConstructorDecl *BaseCtor;
9019
9020 /// The derived constructor we declared.
9021 CXXConstructorDecl *DerivedCtor;
9022 };
9023
9024 /// Inheriting constructors with a given canonical type. There can be at
9025 /// most one such non-template constructor, and any number of templated
9026 /// constructors.
9027 struct InheritingConstructorsForType {
9028 InheritingConstructor NonTemplate;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009029 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
9030 Templates;
Richard Smith185be182013-04-10 05:48:59 +00009031
9032 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
9033 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
9034 TemplateParameterList *ParamList = FTD->getTemplateParameters();
9035 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
9036 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
9037 false, S.TPL_TemplateMatch))
9038 return Templates[I].second;
9039 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
9040 return Templates.back().second;
Sebastian Redl08905022011-02-05 19:23:19 +00009041 }
Richard Smith185be182013-04-10 05:48:59 +00009042
9043 return NonTemplate;
9044 }
9045 };
9046
9047 /// Get or create the inheriting constructor record for a constructor.
9048 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
9049 QualType CtorType) {
9050 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
9051 .getEntry(SemaRef, Ctor);
9052 }
9053
9054 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
9055
9056 /// Process all constructors for a class.
9057 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009058 for (const auto *Ctor : RD->ctors())
9059 (this->*Callback)(Ctor);
Richard Smith185be182013-04-10 05:48:59 +00009060 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
9061 I(RD->decls_begin()), E(RD->decls_end());
9062 I != E; ++I) {
9063 const FunctionDecl *FD = (*I)->getTemplatedDecl();
9064 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
9065 (this->*Callback)(CD);
Sebastian Redl08905022011-02-05 19:23:19 +00009066 }
9067 }
Richard Smith185be182013-04-10 05:48:59 +00009068
9069 /// Note that a constructor (or constructor template) was declared in Derived.
9070 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
9071 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
9072 }
9073
9074 /// Inherit a single constructor.
9075 void inherit(const CXXConstructorDecl *Ctor) {
9076 const FunctionProtoType *CtorType =
9077 Ctor->getType()->castAs<FunctionProtoType>();
Craig Topper5fc8fc22014-08-27 06:28:36 +00009078 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
Richard Smith185be182013-04-10 05:48:59 +00009079 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
9080
9081 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
9082
9083 // Core issue (no number yet): the ellipsis is always discarded.
9084 if (EPI.Variadic) {
9085 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
9086 SemaRef.Diag(Ctor->getLocation(),
9087 diag::note_using_decl_constructor_ellipsis);
9088 EPI.Variadic = false;
9089 }
9090
9091 // Declare a constructor for each number of parameters.
9092 //
9093 // C++11 [class.inhctor]p1:
9094 // The candidate set of inherited constructors from the class X named in
9095 // the using-declaration consists of [... modulo defects ...] for each
9096 // constructor or constructor template of X, the set of constructors or
9097 // constructor templates that results from omitting any ellipsis parameter
9098 // specification and successively omitting parameters with a default
9099 // argument from the end of the parameter-type-list
Richard Smith3c626ed2013-04-17 19:00:52 +00009100 unsigned MinParams = minParamsToInherit(Ctor);
9101 unsigned Params = Ctor->getNumParams();
9102 if (Params >= MinParams) {
9103 do
9104 declareCtor(UsingLoc, Ctor,
9105 SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00009106 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
Richard Smith3c626ed2013-04-17 19:00:52 +00009107 while (Params > MinParams &&
9108 Ctor->getParamDecl(--Params)->hasDefaultArg());
9109 }
Richard Smith185be182013-04-10 05:48:59 +00009110 }
9111
9112 /// Find the using-declaration which specified that we should inherit the
9113 /// constructors of \p Base.
9114 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
9115 // No fancy lookup required; just look for the base constructor name
9116 // directly within the derived class.
9117 ASTContext &Context = SemaRef.Context;
9118 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9119 Context.getCanonicalType(Context.getRecordType(Base)));
Richard Smithcf4bdde2015-02-21 02:45:19 +00009120 DeclContext::lookup_result Decls = Derived->lookup(Name);
Richard Smith185be182013-04-10 05:48:59 +00009121 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
9122 }
9123
9124 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
9125 // C++11 [class.inhctor]p3:
9126 // [F]or each constructor template in the candidate set of inherited
9127 // constructors, a constructor template is implicitly declared
9128 if (Ctor->getDescribedFunctionTemplate())
9129 return 0;
9130
9131 // For each non-template constructor in the candidate set of inherited
9132 // constructors other than a constructor having no parameters or a
9133 // copy/move constructor having a single parameter, a constructor is
9134 // implicitly declared [...]
9135 if (Ctor->getNumParams() == 0)
9136 return 1;
9137 if (Ctor->isCopyOrMoveConstructor())
9138 return 2;
9139
9140 // Per discussion on core reflector, never inherit a constructor which
9141 // would become a default, copy, or move constructor of Derived either.
9142 const ParmVarDecl *PD = Ctor->getParamDecl(0);
9143 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
9144 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
9145 }
9146
9147 /// Declare a single inheriting constructor, inheriting the specified
9148 /// constructor, with the given type.
9149 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
9150 QualType DerivedType) {
9151 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
9152
9153 // C++11 [class.inhctor]p3:
9154 // ... a constructor is implicitly declared with the same constructor
9155 // characteristics unless there is a user-declared constructor with
9156 // the same signature in the class where the using-declaration appears
9157 if (Entry.DeclaredInDerived)
9158 return;
9159
9160 // C++11 [class.inhctor]p7:
9161 // If two using-declarations declare inheriting constructors with the
9162 // same signature, the program is ill-formed
9163 if (Entry.DerivedCtor) {
9164 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
9165 // Only diagnose this once per constructor.
9166 if (Entry.DerivedCtor->isInvalidDecl())
9167 return;
9168 Entry.DerivedCtor->setInvalidDecl();
9169
9170 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
9171 SemaRef.Diag(BaseCtor->getLocation(),
9172 diag::note_using_decl_constructor_conflict_current_ctor);
9173 SemaRef.Diag(Entry.BaseCtor->getLocation(),
9174 diag::note_using_decl_constructor_conflict_previous_ctor);
9175 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
9176 diag::note_using_decl_constructor_conflict_previous_using);
9177 } else {
9178 // Core issue (no number): if the same inheriting constructor is
9179 // produced by multiple base class constructors from the same base
9180 // class, the inheriting constructor is defined as deleted.
9181 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
9182 }
9183
9184 return;
9185 }
9186
9187 ASTContext &Context = SemaRef.Context;
9188 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9189 Context.getCanonicalType(Context.getRecordType(Derived)));
9190 DeclarationNameInfo NameInfo(Name, UsingLoc);
9191
Craig Topperc3ec1492014-05-26 06:22:03 +00009192 TemplateParameterList *TemplateParams = nullptr;
Richard Smith185be182013-04-10 05:48:59 +00009193 if (const FunctionTemplateDecl *FTD =
9194 BaseCtor->getDescribedFunctionTemplate()) {
9195 TemplateParams = FTD->getTemplateParameters();
9196 // We're reusing template parameters from a different DeclContext. This
9197 // is questionable at best, but works out because the template depth in
9198 // both places is guaranteed to be 0.
9199 // FIXME: Rebuild the template parameters in the new context, and
9200 // transform the function type to refer to them.
9201 }
9202
9203 // Build type source info pointing at the using-declaration. This is
9204 // required by template instantiation.
9205 TypeSourceInfo *TInfo =
9206 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
9207 FunctionProtoTypeLoc ProtoLoc =
9208 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
9209
9210 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
9211 Context, Derived, UsingLoc, NameInfo, DerivedType,
9212 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
9213 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
9214
9215 // Build an unevaluated exception specification for this constructor.
9216 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
9217 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00009218 EPI.ExceptionSpec.Type = EST_Unevaluated;
9219 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
Alp Toker314cc812014-01-25 16:55:45 +00009220 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00009221 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +00009222
9223 // Build the parameter declarations.
9224 SmallVector<ParmVarDecl *, 16> ParamDecls;
Alp Toker9cacbab2014-01-20 20:26:09 +00009225 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +00009226 TypeSourceInfo *TInfo =
Alp Toker9cacbab2014-01-20 20:26:09 +00009227 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
Richard Smith185be182013-04-10 05:48:59 +00009228 ParmVarDecl *PD = ParmVarDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00009229 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
9230 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
Richard Smith185be182013-04-10 05:48:59 +00009231 PD->setScopeInfo(0, I);
9232 PD->setImplicit();
9233 ParamDecls.push_back(PD);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009234 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +00009235 }
9236
9237 // Set up the new constructor.
9238 DerivedCtor->setAccess(BaseCtor->getAccess());
9239 DerivedCtor->setParams(ParamDecls);
9240 DerivedCtor->setInheritedConstructor(BaseCtor);
9241 if (BaseCtor->isDeleted())
9242 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
9243
9244 // If this is a constructor template, build the template declaration.
9245 if (TemplateParams) {
9246 FunctionTemplateDecl *DerivedTemplate =
9247 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
9248 TemplateParams, DerivedCtor);
9249 DerivedTemplate->setAccess(BaseCtor->getAccess());
9250 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
9251 Derived->addDecl(DerivedTemplate);
9252 } else {
9253 Derived->addDecl(DerivedCtor);
9254 }
9255
9256 Entry.BaseCtor = BaseCtor;
9257 Entry.DerivedCtor = DerivedCtor;
9258 }
9259
9260 Sema &SemaRef;
9261 CXXRecordDecl *Derived;
9262 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
9263 MapType Map;
9264};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009265}
Richard Smith185be182013-04-10 05:48:59 +00009266
9267void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
9268 // Defer declaring the inheriting constructors until the class is
9269 // instantiated.
9270 if (ClassDecl->isDependentContext())
Sebastian Redl08905022011-02-05 19:23:19 +00009271 return;
9272
Richard Smith185be182013-04-10 05:48:59 +00009273 // Find base classes from which we might inherit constructors.
9274 SmallVector<CXXRecordDecl*, 4> InheritedBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00009275 for (const auto &BaseIt : ClassDecl->bases())
9276 if (BaseIt.getInheritConstructors())
9277 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
Richard Smithc2bc61b2013-03-18 21:12:30 +00009278
Richard Smith185be182013-04-10 05:48:59 +00009279 // Go no further if we're not inheriting any constructors.
9280 if (InheritedBases.empty())
9281 return;
Sebastian Redl08905022011-02-05 19:23:19 +00009282
Richard Smith185be182013-04-10 05:48:59 +00009283 // Declare the inherited constructors.
9284 InheritingConstructorInfo ICI(*this, ClassDecl);
9285 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
9286 ICI.inheritAll(InheritedBases[I]);
Sebastian Redl08905022011-02-05 19:23:19 +00009287}
9288
Richard Smithc2bc61b2013-03-18 21:12:30 +00009289void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
9290 CXXConstructorDecl *Constructor) {
9291 CXXRecordDecl *ClassDecl = Constructor->getParent();
9292 assert(Constructor->getInheritedConstructor() &&
9293 !Constructor->doesThisDeclarationHaveABody() &&
9294 !Constructor->isDeleted());
9295
9296 SynthesizedFunctionScope Scope(*this, Constructor);
9297 DiagnosticErrorTrap Trap(Diags);
9298 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9299 Trap.hasErrorOccurred()) {
9300 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
9301 << Context.getTagDeclType(ClassDecl);
9302 Constructor->setInvalidDecl();
9303 return;
9304 }
9305
9306 SourceLocation Loc = Constructor->getLocation();
9307 Constructor->setBody(new (Context) CompoundStmt(Loc));
9308
Eli Friedman276dd182013-09-05 00:02:25 +00009309 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +00009310 MarkVTableUsed(CurrentLocation, ClassDecl);
9311
9312 if (ASTMutationListener *L = getASTMutationListener()) {
9313 L->CompletedImplicitDefinition(Constructor);
9314 }
9315}
9316
9317
Alexis Huntf91729462011-05-12 22:46:25 +00009318Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009319Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
9320 CXXRecordDecl *ClassDecl = MD->getParent();
9321
Douglas Gregorf1203042010-07-01 19:09:28 +00009322 // C++ [except.spec]p14:
9323 // An implicitly declared special member function (Clause 12) shall have
9324 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +00009325 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009326 if (ClassDecl->isInvalidDecl())
9327 return ExceptSpec;
9328
Douglas Gregorf1203042010-07-01 19:09:28 +00009329 // Direct base-class destructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00009330 for (const auto &B : ClassDecl->bases()) {
9331 if (B.isVirtual()) // Handled below.
Douglas Gregorf1203042010-07-01 19:09:28 +00009332 continue;
9333
Aaron Ballman574705e2014-03-13 15:41:46 +00009334 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9335 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009336 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009337 }
Sebastian Redl623ea822011-05-19 05:13:44 +00009338
Douglas Gregorf1203042010-07-01 19:09:28 +00009339 // Virtual base-class destructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00009340 for (const auto &B : ClassDecl->vbases()) {
9341 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9342 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009343 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009344 }
Sebastian Redl623ea822011-05-19 05:13:44 +00009345
Douglas Gregorf1203042010-07-01 19:09:28 +00009346 // Field destructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009347 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorf1203042010-07-01 19:09:28 +00009348 if (const RecordType *RecordTy
9349 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00009350 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009351 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009352 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009353
Alexis Huntf91729462011-05-12 22:46:25 +00009354 return ExceptSpec;
9355}
9356
9357CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
9358 // C++ [class.dtor]p2:
9359 // If a class has no user-declared destructor, a destructor is
9360 // declared implicitly. An implicitly-declared destructor is an
9361 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +00009362 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +00009363
Richard Smith8bf22e52012-11-29 01:34:07 +00009364 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
9365 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009366 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009367
Douglas Gregor7454c562010-07-02 20:37:36 +00009368 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00009369 CanQualType ClassType
9370 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00009371 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00009372 DeclarationName Name
9373 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009374 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00009375 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +00009376 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +00009377 QualType(), nullptr, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009378 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00009379 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00009380 Destructor->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009381
9382 if (getLangOpts().CUDA) {
9383 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
9384 Destructor,
9385 /* ConstRHS */ false,
9386 /* Diagnose */ false);
9387 }
Richard Smithd3b5c9082012-07-27 04:22:15 +00009388
9389 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00009390 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009391 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009392
Richard Smith6b02d462012-12-08 08:32:28 +00009393 AddOverriddenMethods(ClassDecl, Destructor);
9394
9395 // We don't need to use SpecialMemberIsTrivial here; triviality for
9396 // destructors is easy to compute.
9397 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
9398
9399 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00009400 SetDeclDeleted(Destructor, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00009401
Douglas Gregor7454c562010-07-02 20:37:36 +00009402 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00009403 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +00009404
Douglas Gregor7454c562010-07-02 20:37:36 +00009405 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00009406 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00009407 PushOnScopeChains(Destructor, S, false);
9408 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +00009409
Douglas Gregorf1203042010-07-01 19:09:28 +00009410 return Destructor;
9411}
9412
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009413void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00009414 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00009415 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +00009416 !Destructor->doesThisDeclarationHaveABody() &&
9417 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009418 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00009419 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009420 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009421
Douglas Gregor54818f02010-05-12 16:39:35 +00009422 if (Destructor->isInvalidDecl())
9423 return;
9424
Eli Friedmaneaf34142012-10-18 20:14:08 +00009425 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009426
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009427 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00009428 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9429 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00009430
Douglas Gregor54818f02010-05-12 16:39:35 +00009431 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00009432 Diag(CurrentLocation, diag::note_member_synthesized_at)
9433 << CXXDestructor << Context.getTagDeclType(ClassDecl);
9434
9435 Destructor->setInvalidDecl();
9436 return;
9437 }
9438
Ben Langmuir2f8e6b82014-09-25 20:55:00 +00009439 // The exception specification is needed because we are defining the
9440 // function.
9441 ResolveExceptionSpec(CurrentLocation,
9442 Destructor->getType()->castAs<FunctionProtoType>());
9443
Daniel Jasperb3b0b802014-06-20 08:44:22 +00009444 SourceLocation Loc = Destructor->getLocEnd().isValid()
9445 ? Destructor->getLocEnd()
9446 : Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00009447 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +00009448 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009449 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00009450
9451 if (ASTMutationListener *L = getASTMutationListener()) {
9452 L->CompletedImplicitDefinition(Destructor);
9453 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009454}
9455
Richard Smith84973e52012-04-21 18:42:51 +00009456/// \brief Perform any semantic analysis which needs to be delayed until all
9457/// pending class member declarations have been parsed.
9458void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00009459 // If the context is an invalid C++ class, just suppress these checks.
9460 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9461 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +00009462 DelayedDefaultedMemberExceptionSpecs.clear();
Richard Smith88f45492014-11-22 03:09:05 +00009463 DelayedExceptionSpecChecks.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00009464 return;
9465 }
9466 }
Richard Smith84973e52012-04-21 18:42:51 +00009467}
9468
Reid Klecknerbba3cb92015-03-17 19:00:50 +00009469static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) {
9470 // Don't do anything for template patterns.
9471 if (Class->getDescribedClassTemplate())
9472 return;
9473
9474 for (Decl *Member : Class->decls()) {
9475 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
9476 if (!CD) {
9477 // Recurse on nested classes.
9478 if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member))
9479 getDefaultArgExprsForConstructors(S, NestedRD);
9480 continue;
9481 } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) {
9482 continue;
9483 }
9484
9485 for (unsigned I = 0, E = CD->getNumParams(); I != E; ++I) {
9486 // Skip any default arguments that we've already instantiated.
9487 if (S.Context.getDefaultArgExprForConstructor(CD, I))
9488 continue;
9489
9490 Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD,
9491 CD->getParamDecl(I)).get();
David Majnemer9321f922015-06-11 02:38:06 +00009492 S.DiscardCleanupsInEvaluationContext();
Reid Klecknerbba3cb92015-03-17 19:00:50 +00009493 S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
9494 }
9495 }
9496}
9497
Reid Kleckner93f661a2015-03-17 21:51:43 +00009498void Sema::ActOnFinishCXXMemberDefaultArgs(Decl *D) {
Reid Klecknerbba3cb92015-03-17 19:00:50 +00009499 auto *RD = dyn_cast<CXXRecordDecl>(D);
9500
9501 // Default constructors that are annotated with __declspec(dllexport) which
9502 // have default arguments or don't use the standard calling convention are
9503 // wrapped with a thunk called the default constructor closure.
9504 if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft())
9505 getDefaultArgExprsForConstructors(*this, RD);
9506}
9507
Richard Smithd3b5c9082012-07-27 04:22:15 +00009508void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9509 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009510 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00009511 "adjusting dtor exception specs was introduced in c++11");
9512
Sebastian Redl623ea822011-05-19 05:13:44 +00009513 // C++11 [class.dtor]p3:
9514 // A declaration of a destructor that does not have an exception-
9515 // specification is implicitly considered to have the same exception-
9516 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009517 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +00009518 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009519 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +00009520 return;
9521
Chandler Carruth9a797572011-09-20 04:55:26 +00009522 // Replace the destructor's type, building off the existing one. Fortunately,
9523 // the only thing of interest in the destructor type is its extended info.
9524 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009525 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00009526 EPI.ExceptionSpec.Type = EST_Unevaluated;
9527 EPI.ExceptionSpec.SourceDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009528 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +00009529
Sebastian Redl623ea822011-05-19 05:13:44 +00009530 // FIXME: If the destructor has a body that could throw, and the newly created
9531 // spec doesn't allow exceptions, we should emit a warning, because this
9532 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009533 // However, we don't have a body or an exception specification yet, so it
9534 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +00009535}
9536
Pavel Labath58934982013-08-30 08:52:28 +00009537namespace {
9538/// \brief An abstract base class for all helper classes used in building the
9539// copy/move operators. These classes serve as factory functions and help us
9540// avoid using the same Expr* in the AST twice.
9541class ExprBuilder {
Aaron Ballmanabc18922015-02-15 22:54:08 +00009542 ExprBuilder(const ExprBuilder&) = delete;
9543 ExprBuilder &operator=(const ExprBuilder&) = delete;
Pavel Labath58934982013-08-30 08:52:28 +00009544
9545protected:
9546 static Expr *assertNotNull(Expr *E) {
9547 assert(E && "Expression construction must not fail.");
9548 return E;
9549 }
9550
9551public:
9552 ExprBuilder() {}
9553 virtual ~ExprBuilder() {}
9554
9555 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9556};
9557
9558class RefBuilder: public ExprBuilder {
9559 VarDecl *Var;
9560 QualType VarType;
9561
9562public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009563 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009564 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009565 }
9566
9567 RefBuilder(VarDecl *Var, QualType VarType)
9568 : Var(Var), VarType(VarType) {}
9569};
9570
9571class ThisBuilder: public ExprBuilder {
9572public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009573 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009574 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
Pavel Labath58934982013-08-30 08:52:28 +00009575 }
9576};
9577
9578class CastBuilder: public ExprBuilder {
9579 const ExprBuilder &Builder;
9580 QualType Type;
9581 ExprValueKind Kind;
9582 const CXXCastPath &Path;
9583
9584public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009585 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009586 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9587 CK_UncheckedDerivedToBase, Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009588 &Path).get());
Pavel Labath58934982013-08-30 08:52:28 +00009589 }
9590
9591 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9592 const CXXCastPath &Path)
9593 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9594};
9595
9596class DerefBuilder: public ExprBuilder {
9597 const ExprBuilder &Builder;
9598
9599public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009600 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009601 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009602 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009603 }
9604
9605 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9606};
9607
9608class MemberBuilder: public ExprBuilder {
9609 const ExprBuilder &Builder;
9610 QualType Type;
9611 CXXScopeSpec SS;
9612 bool IsArrow;
9613 LookupResult &MemberLookup;
9614
9615public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009616 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009617 return assertNotNull(S.BuildMemberReferenceExpr(
Craig Topperc3ec1492014-05-26 06:22:03 +00009618 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009619 nullptr, MemberLookup, nullptr).get());
Pavel Labath58934982013-08-30 08:52:28 +00009620 }
9621
9622 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9623 LookupResult &MemberLookup)
9624 : Builder(Builder), Type(Type), IsArrow(IsArrow),
9625 MemberLookup(MemberLookup) {}
9626};
9627
9628class MoveCastBuilder: public ExprBuilder {
9629 const ExprBuilder &Builder;
9630
9631public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009632 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009633 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9634 }
9635
9636 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9637};
9638
9639class LvalueConvBuilder: public ExprBuilder {
9640 const ExprBuilder &Builder;
9641
9642public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009643 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009644 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009645 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009646 }
9647
9648 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9649};
9650
9651class SubscriptBuilder: public ExprBuilder {
9652 const ExprBuilder &Base;
9653 const ExprBuilder &Index;
9654
9655public:
David Blaikie1cbb9712014-11-14 19:09:44 +00009656 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009657 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009658 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009659 }
9660
9661 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9662 : Base(Base), Index(Index) {}
9663};
9664
9665} // end anonymous namespace
9666
Richard Smith41ae3282012-11-14 00:50:40 +00009667/// When generating a defaulted copy or move assignment operator, if a field
9668/// should be copied with __builtin_memcpy rather than via explicit assignments,
9669/// do so. This optimization only applies for arrays of scalars, and for arrays
9670/// of class type where the selected copy/move-assignment operator is trivial.
9671static StmtResult
9672buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009673 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +00009674 // Compute the size of the memory buffer to be copied.
9675 QualType SizeType = S.Context.getSizeType();
9676 llvm::APInt Size(S.Context.getTypeSize(SizeType),
9677 S.Context.getTypeSizeInChars(T).getQuantity());
9678
9679 // Take the address of the field references for "from" and "to". We
9680 // directly construct UnaryOperators here because semantic analysis
9681 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009682 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009683 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9684 S.Context.getPointerType(From->getType()),
9685 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +00009686 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009687 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9688 S.Context.getPointerType(To->getType()),
9689 VK_RValue, OK_Ordinary, Loc);
9690
9691 const Type *E = T->getBaseElementTypeUnsafe();
9692 bool NeedsCollectableMemCpy =
9693 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9694
9695 // Create a reference to the __builtin_objc_memmove_collectable function
9696 StringRef MemCpyName = NeedsCollectableMemCpy ?
9697 "__builtin_objc_memmove_collectable" :
9698 "__builtin_memcpy";
9699 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9700 Sema::LookupOrdinaryName);
9701 S.LookupName(R, S.TUScope, true);
9702
9703 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9704 if (!MemCpy)
9705 // Something went horribly wrong earlier, and we will have complained
9706 // about it.
9707 return StmtError();
9708
9709 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
Craig Topperc3ec1492014-05-26 06:22:03 +00009710 VK_RValue, Loc, nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009711 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9712
9713 Expr *CallArgs[] = {
9714 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9715 };
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009716 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
Richard Smith41ae3282012-11-14 00:50:40 +00009717 Loc, CallArgs, Loc);
9718
9719 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009720 return Call.getAs<Stmt>();
Richard Smith41ae3282012-11-14 00:50:40 +00009721}
9722
Sebastian Redl22653ba2011-08-30 19:58:05 +00009723/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00009724/// \c To.
9725///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009726/// This routine is used to copy/move the members of a class with an
9727/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00009728/// copied are arrays, this routine builds for loops to copy them.
9729///
9730/// \param S The Sema object used for type-checking.
9731///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009732/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009733///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009734/// \param T The type of the expressions being copied/moved. Both expressions
9735/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009736///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009737/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009738///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009739/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009740///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009741/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009742/// Otherwise, it's a non-static member subobject.
9743///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009744/// \param Copying Whether we're copying or moving.
9745///
Douglas Gregorb139cd52010-05-01 20:49:11 +00009746/// \param Depth Internal parameter recording the depth of the recursion.
9747///
Richard Smith41ae3282012-11-14 00:50:40 +00009748/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9749/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +00009750static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +00009751buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009752 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009753 bool CopyingBaseSubobject, bool Copying,
9754 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +00009755 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00009756 // Each subobject is assigned in the manner appropriate to its type:
9757 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00009758 // - if the subobject is of class type, as if by a call to operator= with
9759 // the subobject as the object expression and the corresponding
9760 // subobject of x as a single function argument (as if by explicit
9761 // qualification; that is, ignoring any possible virtual overriding
9762 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +00009763 //
9764 // C++03 [class.copy]p13:
9765 // - if the subobject is of class type, the copy assignment operator for
9766 // the class is used (as if by explicit qualification; that is,
9767 // ignoring any possible virtual overriding functions in more derived
9768 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009769 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9770 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +00009771
Douglas Gregorb139cd52010-05-01 20:49:11 +00009772 // Look for operator=.
9773 DeclarationName Name
9774 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9775 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9776 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009777
Richard Smith52c0b582012-11-13 00:54:12 +00009778 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9779 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009780 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +00009781 LookupResult::Filter F = OpLookup.makeFilter();
9782 while (F.hasNext()) {
9783 NamedDecl *D = F.next();
9784 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9785 if (Method->isCopyAssignmentOperator() ||
9786 (!Copying && Method->isMoveAssignmentOperator()))
9787 continue;
9788
9789 F.erase();
9790 }
9791 F.done();
John McCallab8c2732010-03-16 06:11:48 +00009792 }
Richard Smith52c0b582012-11-13 00:54:12 +00009793
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009794 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +00009795 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009796 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +00009797 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009798 // ambiguities), we need to cast "this" to that subobject type; to
9799 // ensure that we don't go through the virtual call mechanism, we need
9800 // to qualify the operator= name with the base class (see below). However,
9801 // this means that if the base class has a protected copy assignment
9802 // operator, the protected member access check will fail. So, we
9803 // rewrite "protected" access to "public" access in this case, since we
9804 // know by construction that we're calling from a derived class.
9805 if (CopyingBaseSubobject) {
9806 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9807 L != LEnd; ++L) {
9808 if (L.getAccess() == AS_protected)
9809 L.setAccess(AS_public);
9810 }
9811 }
Richard Smith52c0b582012-11-13 00:54:12 +00009812
Douglas Gregorb139cd52010-05-01 20:49:11 +00009813 // Create the nested-name-specifier that will be used to qualify the
9814 // reference to operator=; this is required to suppress the virtual
9815 // call mechanism.
9816 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00009817 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +00009818 SS.MakeTrivial(S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +00009819 NestedNameSpecifier::Create(S.Context, nullptr, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00009820 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00009821 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009822
Douglas Gregorb139cd52010-05-01 20:49:11 +00009823 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00009824 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +00009825 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9826 SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009827 /*FirstQualifierInScope=*/nullptr,
Abramo Bagnara7945c982012-01-27 09:46:47 +00009828 OpLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00009829 /*TemplateArgs=*/nullptr,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009830 /*SuppressQualifierCheck=*/true);
9831 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009832 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009833
Douglas Gregorb139cd52010-05-01 20:49:11 +00009834 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00009835
Pavel Labath58934982013-08-30 08:52:28 +00009836 Expr *FromInst = From.build(S, Loc);
Craig Topperc3ec1492014-05-26 06:22:03 +00009837 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009838 OpEqualRef.getAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +00009839 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009840 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009841 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009842
Richard Smith41ae3282012-11-14 00:50:40 +00009843 // If we built a call to a trivial 'operator=' while copying an array,
9844 // bail out. We'll replace the whole shebang with a memcpy.
9845 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9846 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
Craig Topperc3ec1492014-05-26 06:22:03 +00009847 return StmtResult((Stmt*)nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009848
Richard Smith52c0b582012-11-13 00:54:12 +00009849 // Convert to an expression-statement, and clean up any produced
9850 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +00009851 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009852 }
John McCallab8c2732010-03-16 06:11:48 +00009853
Richard Smith52c0b582012-11-13 00:54:12 +00009854 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +00009855 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +00009856 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009857 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +00009858 ExprResult Assignment = S.CreateBuiltinBinOp(
9859 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009860 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009861 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +00009862 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009863 }
Richard Smith52c0b582012-11-13 00:54:12 +00009864
9865 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +00009866 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +00009867
Douglas Gregorb139cd52010-05-01 20:49:11 +00009868 // Construct a loop over the array bounds, e.g.,
9869 //
9870 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9871 //
9872 // that will copy each of the array elements.
9873 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +00009874
Douglas Gregorb139cd52010-05-01 20:49:11 +00009875 // Create the iteration variable.
Craig Topperc3ec1492014-05-26 06:22:03 +00009876 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009877 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009878 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009879 llvm::raw_svector_ostream OS(Str);
9880 OS << "__i" << Depth;
9881 IterationVarName = &S.Context.Idents.get(OS.str());
9882 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00009883 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009884 IterationVarName, SizeType,
9885 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009886 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +00009887
Douglas Gregorb139cd52010-05-01 20:49:11 +00009888 // Initialize the iteration variable to zero.
9889 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009890 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009891
Pavel Labath58934982013-08-30 08:52:28 +00009892 // Creates a reference to the iteration variable.
9893 RefBuilder IterationVarRef(IterationVar, SizeType);
9894 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +00009895
Douglas Gregorb139cd52010-05-01 20:49:11 +00009896 // Create the DeclStmt that holds the iteration variable.
9897 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009898
Douglas Gregorb139cd52010-05-01 20:49:11 +00009899 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +00009900 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9901 MoveCastBuilder FromIndexMove(FromIndexCopy);
9902 const ExprBuilder *FromIndex;
9903 if (Copying)
9904 FromIndex = &FromIndexCopy;
9905 else
9906 FromIndex = &FromIndexMove;
9907
9908 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009909
9910 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +00009911 StmtResult Copy =
9912 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +00009913 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +00009914 Copying, Depth + 1);
9915 // Bail out if copying fails or if we determined that we should use memcpy.
9916 if (Copy.isInvalid() || !Copy.get())
9917 return Copy;
9918
9919 // Create the comparison against the array bound.
9920 llvm::APInt Upper
9921 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9922 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +00009923 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +00009924 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9925 BO_NE, S.Context.BoolTy,
9926 VK_RValue, OK_Ordinary, Loc, false);
9927
9928 // Create the pre-increment of the iteration variable.
9929 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +00009930 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9931 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009932
Douglas Gregorb139cd52010-05-01 20:49:11 +00009933 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00009934 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009935 S.MakeFullExpr(Comparison),
Craig Topperc3ec1492014-05-26 06:22:03 +00009936 nullptr, S.MakeFullDiscardedValueExpr(Increment),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009937 Loc, Copy.get());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009938}
9939
Richard Smith41ae3282012-11-14 00:50:40 +00009940static StmtResult
9941buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009942 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009943 bool CopyingBaseSubobject, bool Copying) {
9944 // Maybe we should use a memcpy?
9945 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9946 T.isTriviallyCopyableType(S.Context))
9947 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9948
9949 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9950 CopyingBaseSubobject,
9951 Copying, 0));
9952
9953 // If we ended up picking a trivial assignment operator for an array of a
9954 // non-trivially-copyable class type, just emit a memcpy.
9955 if (!Result.isInvalid() && !Result.get())
9956 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9957
9958 return Result;
9959}
9960
Richard Smithd3b5c9082012-07-27 04:22:15 +00009961Sema::ImplicitExceptionSpecification
9962Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9963 CXXRecordDecl *ClassDecl = MD->getParent();
9964
9965 ImplicitExceptionSpecification ExceptSpec(*this);
9966 if (ClassDecl->isInvalidDecl())
9967 return ExceptSpec;
9968
9969 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00009970 assert(T->getNumParams() == 1 && "not a copy assignment op");
9971 unsigned ArgQuals =
9972 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009973
Douglas Gregor68e11362010-07-01 17:48:08 +00009974 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +00009975 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +00009976 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00009977
9978 // It is unspecified whether or not an implicit copy assignment operator
9979 // attempts to deduplicate calls to assignment operators of virtual bases are
9980 // made. As such, this exception specification is effectively unspecified.
9981 // Based on a similar decision made for constness in C++0x, we're erring on
9982 // the side of assuming such calls to be made regardless of whether they
9983 // actually happen.
Aaron Ballman574705e2014-03-13 15:41:46 +00009984 for (const auto &Base : ClassDecl->bases()) {
9985 if (Base.isVirtual())
Alexis Hunt491ec602011-06-21 23:42:56 +00009986 continue;
9987
Douglas Gregor330b9cf2010-07-02 21:50:04 +00009988 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009989 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009990 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9991 ArgQuals, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009992 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00009993 }
Alexis Hunt491ec602011-06-21 23:42:56 +00009994
Aaron Ballman445a9392014-03-13 16:15:17 +00009995 for (const auto &Base : ClassDecl->vbases()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00009996 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009997 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009998 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9999 ArgQuals, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +000010000 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +000010001 }
10002
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010003 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010004 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +000010005 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10006 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +000010007 LookupCopyingAssignment(FieldClassDecl,
10008 ArgQuals | FieldType.getCVRQualifiers(),
10009 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +000010010 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +000010011 }
Douglas Gregor68e11362010-07-01 17:48:08 +000010012 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010013
Richard Smithd3b5c9082012-07-27 04:22:15 +000010014 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +000010015}
10016
10017CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
10018 // Note: The following rules are largely analoguous to the copy
10019 // constructor rules. Note that virtual bases are not taken into account
10020 // for determining the argument type of the operator. Note also that
10021 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +000010022 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +000010023
Richard Smith8bf22e52012-11-29 01:34:07 +000010024 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
10025 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010026 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010027
Alexis Hunt119f3652011-05-14 05:23:20 +000010028 QualType ArgType = Context.getTypeDeclType(ClassDecl);
10029 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +000010030 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
10031 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +000010032 ArgType = ArgType.withConst();
10033 ArgType = Context.getLValueReferenceType(ArgType);
10034
Richard Smith99005e62013-05-07 03:19:20 +000010035 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10036 CXXCopyAssignment,
10037 Const);
10038
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010039 // An implicitly-declared copy assignment operator is an inline public
10040 // member of its class.
10041 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +000010042 SourceLocation ClassLoc = ClassDecl->getLocation();
10043 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000010044 CXXMethodDecl *CopyAssignment =
10045 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000010046 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10047 /*isInline=*/true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010048 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +000010049 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010050 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010051
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010052 if (getLangOpts().CUDA) {
10053 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
10054 CopyAssignment,
10055 /* ConstRHS */ Const,
10056 /* Diagnose */ false);
10057 }
10058
Richard Smithd3b5c9082012-07-27 04:22:15 +000010059 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010060 FunctionProtoType::ExtProtoInfo EPI =
10061 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000010062 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010063
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010064 // Add the parameter to the operator.
10065 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000010066 ClassLoc, ClassLoc,
10067 /*Id=*/nullptr, ArgType,
10068 /*TInfo=*/nullptr, SC_None,
10069 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010070 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +000010071
Richard Smith6b02d462012-12-08 08:32:28 +000010072 AddOverriddenMethods(ClassDecl, CopyAssignment);
10073
10074 CopyAssignment->setTrivial(
10075 ClassDecl->needsOverloadResolutionForCopyAssignment()
10076 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
10077 : ClassDecl->hasTrivialCopyAssignment());
10078
Richard Smith852265f2012-03-30 20:53:28 +000010079 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smithb4d2a152013-04-02 19:38:47 +000010080 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010081
Richard Smith6b02d462012-12-08 08:32:28 +000010082 // Note that we have added this copy-assignment operator.
10083 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
10084
10085 if (Scope *S = getScopeForContext(ClassDecl))
10086 PushOnScopeChains(CopyAssignment, S, false);
10087 ClassDecl->addDecl(CopyAssignment);
10088
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010089 return CopyAssignment;
10090}
10091
Richard Smithd577fbb2013-06-13 03:23:42 +000010092/// Diagnose an implicit copy operation for a class which is odr-used, but
10093/// which is deprecated because the class has a user-declared copy constructor,
10094/// copy assignment operator, or destructor.
10095static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
10096 SourceLocation UseLoc) {
10097 assert(CopyOp->isImplicit());
10098
10099 CXXRecordDecl *RD = CopyOp->getParent();
Craig Topperc3ec1492014-05-26 06:22:03 +000010100 CXXMethodDecl *UserDeclaredOperation = nullptr;
Richard Smithd577fbb2013-06-13 03:23:42 +000010101
10102 // In Microsoft mode, assignment operations don't affect constructors and
10103 // vice versa.
10104 if (RD->hasUserDeclaredDestructor()) {
10105 UserDeclaredOperation = RD->getDestructor();
10106 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
10107 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000010108 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +000010109 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +000010110 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +000010111 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +000010112 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +000010113 break;
10114 }
10115 }
10116 assert(UserDeclaredOperation);
10117 } else if (isa<CXXConstructorDecl>(CopyOp) &&
10118 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000010119 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +000010120 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +000010121 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +000010122 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000010123 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +000010124 break;
10125 }
10126 }
10127 assert(UserDeclaredOperation);
10128 }
10129
10130 if (UserDeclaredOperation) {
10131 S.Diag(UserDeclaredOperation->getLocation(),
10132 diag::warn_deprecated_copy_operation)
10133 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
10134 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
10135 S.Diag(UseLoc, diag::note_member_synthesized_at)
10136 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
10137 : Sema::CXXCopyAssignment)
10138 << RD;
10139 }
10140}
10141
Douglas Gregorb139cd52010-05-01 20:49:11 +000010142void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
10143 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +000010144 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000010145 CopyAssignOperator->isOverloadedOperator() &&
10146 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000010147 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
10148 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000010149 "DefineImplicitCopyAssignment called for wrong function");
10150
10151 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
10152
10153 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
10154 CopyAssignOperator->setInvalidDecl();
10155 return;
10156 }
Richard Smithd577fbb2013-06-13 03:23:42 +000010157
10158 // C++11 [class.copy]p18:
10159 // The [definition of an implicitly declared copy assignment operator] is
10160 // deprecated if the class has a user-declared copy constructor or a
10161 // user-declared destructor.
10162 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
10163 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
10164
Eli Friedman276dd182013-09-05 00:02:25 +000010165 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010166
Eli Friedmaneaf34142012-10-18 20:14:08 +000010167 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010168 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010169
10170 // C++0x [class.copy]p30:
10171 // The implicitly-defined or explicitly-defaulted copy assignment operator
10172 // for a non-union class X performs memberwise copy assignment of its
10173 // subobjects. The direct base classes of X are assigned first, in the
10174 // order of their declaration in the base-specifier-list, and then the
10175 // immediate non-static data members of X are assigned, in the order in
10176 // which they were declared in the class definition.
10177
10178 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000010179 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010180
10181 // The parameter for the "other" object, which we are copying from.
10182 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
10183 Qualifiers OtherQuals = Other->getType().getQualifiers();
10184 QualType OtherRefType = Other->getType();
10185 if (const LValueReferenceType *OtherRef
10186 = OtherRefType->getAs<LValueReferenceType>()) {
10187 OtherRefType = OtherRef->getPointeeType();
10188 OtherQuals = OtherRefType.getQualifiers();
10189 }
10190
10191 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010192 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
10193 ? CopyAssignOperator->getLocEnd()
10194 : CopyAssignOperator->getLocation();
10195
Pavel Labath58934982013-08-30 08:52:28 +000010196 // Builds a DeclRefExpr for the "other" object.
10197 RefBuilder OtherRef(Other, OtherRefType);
10198
10199 // Builds the "this" pointer.
10200 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010201
10202 // Assign base classes.
10203 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000010204 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000010205 // Form the assignment:
10206 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000010207 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +000010208 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000010209 Invalid = true;
10210 continue;
10211 }
10212
John McCallcf142162010-08-07 06:22:56 +000010213 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000010214 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +000010215
Douglas Gregorb139cd52010-05-01 20:49:11 +000010216 // Construct the "from" expression, which is an implicit cast to the
10217 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010218 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
10219 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010220
10221 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000010222 DerefBuilder DerefThis(This);
10223 CastBuilder To(DerefThis,
10224 Context.getCVRQualifiedType(
10225 BaseType, CopyAssignOperator->getTypeQualifiers()),
10226 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010227
10228 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +000010229 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000010230 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010231 /*CopyingBaseSubobject=*/true,
10232 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010233 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010234 Diag(CurrentLocation, diag::note_member_synthesized_at)
10235 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10236 CopyAssignOperator->setInvalidDecl();
10237 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010238 }
10239
10240 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010241 Statements.push_back(Copy.getAs<Expr>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010242 }
10243
Douglas Gregorb139cd52010-05-01 20:49:11 +000010244 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010245 for (auto *Field : ClassDecl->fields()) {
Richard Smith419bd092015-04-29 19:26:57 +000010246 // FIXME: We should form some kind of AST representation for the implied
10247 // memcpy in a union copy operation.
10248 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
Douglas Gregor556e5862011-10-10 17:22:13 +000010249 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +000010250
10251 if (Field->isInvalidDecl()) {
10252 Invalid = true;
10253 continue;
10254 }
10255
Douglas Gregorb139cd52010-05-01 20:49:11 +000010256 // Check for members of reference type; we can't copy those.
10257 if (Field->getType()->isReferenceType()) {
10258 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10259 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10260 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010261 Diag(CurrentLocation, diag::note_member_synthesized_at)
10262 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010263 Invalid = true;
10264 continue;
10265 }
10266
10267 // Check for members of const-qualified, non-class type.
10268 QualType BaseType = Context.getBaseElementType(Field->getType());
10269 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10270 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10271 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10272 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010273 Diag(CurrentLocation, diag::note_member_synthesized_at)
10274 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010275 Invalid = true;
10276 continue;
10277 }
John McCall1b1a1db2011-06-17 00:18:42 +000010278
10279 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000010280 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10281 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010282
10283 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000010284 if (FieldType->isIncompleteArrayType()) {
10285 assert(ClassDecl->hasFlexibleArrayMember() &&
10286 "Incomplete array type is not valid");
10287 continue;
10288 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000010289
10290 // Build references to the field in the object we're copying from and to.
10291 CXXScopeSpec SS; // Intentionally empty
10292 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10293 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010294 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010295 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000010296
10297 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
10298
10299 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010300
Douglas Gregorb139cd52010-05-01 20:49:11 +000010301 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000010302 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010303 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010304 /*CopyingBaseSubobject=*/false,
10305 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010306 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010307 Diag(CurrentLocation, diag::note_member_synthesized_at)
10308 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10309 CopyAssignOperator->setInvalidDecl();
10310 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010311 }
10312
10313 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010314 Statements.push_back(Copy.getAs<Stmt>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010315 }
10316
10317 if (!Invalid) {
10318 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +000010319 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000010320
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010321 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010322 if (Return.isInvalid())
10323 Invalid = true;
10324 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010325 Statements.push_back(Return.getAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +000010326
10327 if (Trap.hasErrorOccurred()) {
10328 Diag(CurrentLocation, diag::note_member_synthesized_at)
10329 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10330 Invalid = true;
10331 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000010332 }
10333 }
10334
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010335 // The exception specification is needed because we are defining the
10336 // function.
10337 ResolveExceptionSpec(CurrentLocation,
10338 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
10339
Douglas Gregorb139cd52010-05-01 20:49:11 +000010340 if (Invalid) {
10341 CopyAssignOperator->setInvalidDecl();
10342 return;
10343 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010344
10345 StmtResult Body;
10346 {
10347 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010348 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010349 /*isStmtExpr=*/false);
10350 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10351 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010352 CopyAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +000010353
10354 if (ASTMutationListener *L = getASTMutationListener()) {
10355 L->CompletedImplicitDefinition(CopyAssignOperator);
10356 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010357}
10358
Sebastian Redl22653ba2011-08-30 19:58:05 +000010359Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010360Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
10361 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010362
Richard Smithd3b5c9082012-07-27 04:22:15 +000010363 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010364 if (ClassDecl->isInvalidDecl())
10365 return ExceptSpec;
10366
10367 // C++0x [except.spec]p14:
10368 // An implicitly declared special member function (Clause 12) shall have an
10369 // exception-specification. [...]
10370
10371 // It is unspecified whether or not an implicit move assignment operator
10372 // attempts to deduplicate calls to assignment operators of virtual bases are
10373 // made. As such, this exception specification is effectively unspecified.
10374 // Based on a similar decision made for constness in C++0x, we're erring on
10375 // the side of assuming such calls to be made regardless of whether they
10376 // actually happen.
10377 // Note that a move constructor is not implicitly declared when there are
10378 // virtual bases, but it can still be user-declared and explicitly defaulted.
Aaron Ballman574705e2014-03-13 15:41:46 +000010379 for (const auto &Base : ClassDecl->bases()) {
10380 if (Base.isVirtual())
Sebastian Redl22653ba2011-08-30 19:58:05 +000010381 continue;
10382
10383 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010384 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010385 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000010386 0, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +000010387 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010388 }
10389
Aaron Ballman445a9392014-03-13 16:15:17 +000010390 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010391 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010392 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010393 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000010394 0, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +000010395 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010396 }
10397
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010398 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010399 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010400 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010401 if (CXXMethodDecl *MoveAssign =
10402 LookupMovingAssignment(FieldClassDecl,
10403 FieldType.getCVRQualifiers(),
10404 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +000010405 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010406 }
10407 }
10408
10409 return ExceptSpec;
10410}
10411
10412CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010413 assert(ClassDecl->needsImplicitMoveAssignment());
10414
Richard Smith8bf22e52012-11-29 01:34:07 +000010415 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
10416 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010417 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010418
Sebastian Redl22653ba2011-08-30 19:58:05 +000010419 // Note: The following rules are largely analoguous to the move
10420 // constructor rules.
10421
Sebastian Redl22653ba2011-08-30 19:58:05 +000010422 QualType ArgType = Context.getTypeDeclType(ClassDecl);
10423 QualType RetType = Context.getLValueReferenceType(ArgType);
10424 ArgType = Context.getRValueReferenceType(ArgType);
10425
Richard Smith99005e62013-05-07 03:19:20 +000010426 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10427 CXXMoveAssignment,
10428 false);
10429
Sebastian Redl22653ba2011-08-30 19:58:05 +000010430 // An implicitly-declared move assignment operator is an inline public
10431 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010432 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10433 SourceLocation ClassLoc = ClassDecl->getLocation();
10434 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000010435 CXXMethodDecl *MoveAssignment =
10436 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000010437 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
Richard Smith99005e62013-05-07 03:19:20 +000010438 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010439 MoveAssignment->setAccess(AS_public);
10440 MoveAssignment->setDefaulted();
10441 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010442
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010443 if (getLangOpts().CUDA) {
10444 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
10445 MoveAssignment,
10446 /* ConstRHS */ false,
10447 /* Diagnose */ false);
10448 }
10449
Richard Smithd3b5c9082012-07-27 04:22:15 +000010450 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010451 FunctionProtoType::ExtProtoInfo EPI =
10452 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000010453 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010454
Sebastian Redl22653ba2011-08-30 19:58:05 +000010455 // Add the parameter to the operator.
10456 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000010457 ClassLoc, ClassLoc,
10458 /*Id=*/nullptr, ArgType,
10459 /*TInfo=*/nullptr, SC_None,
10460 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010461 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010462
Richard Smith6b02d462012-12-08 08:32:28 +000010463 AddOverriddenMethods(ClassDecl, MoveAssignment);
10464
10465 MoveAssignment->setTrivial(
10466 ClassDecl->needsOverloadResolutionForMoveAssignment()
10467 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
10468 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010469
Richard Smithd951a1d2012-02-18 02:02:13 +000010470 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010471 ClassDecl->setImplicitMoveAssignmentIsDeleted();
10472 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010473 }
10474
Richard Smith6b02d462012-12-08 08:32:28 +000010475 // Note that we have added this copy-assignment operator.
10476 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
10477
Sebastian Redl22653ba2011-08-30 19:58:05 +000010478 if (Scope *S = getScopeForContext(ClassDecl))
10479 PushOnScopeChains(MoveAssignment, S, false);
10480 ClassDecl->addDecl(MoveAssignment);
10481
Sebastian Redl22653ba2011-08-30 19:58:05 +000010482 return MoveAssignment;
10483}
10484
Richard Smithb2504bd2013-11-04 04:26:14 +000010485/// Check if we're implicitly defining a move assignment operator for a class
10486/// with virtual bases. Such a move assignment might move-assign the virtual
10487/// base multiple times.
10488static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
10489 SourceLocation CurrentLocation) {
10490 assert(!Class->isDependentContext() && "should not define dependent move");
10491
10492 // Only a virtual base could get implicitly move-assigned multiple times.
10493 // Only a non-trivial move assignment can observe this. We only want to
10494 // diagnose if we implicitly define an assignment operator that assigns
10495 // two base classes, both of which move-assign the same virtual base.
10496 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10497 Class->getNumBases() < 2)
10498 return;
10499
10500 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10501 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10502 VBaseMap VBases;
10503
Aaron Ballman574705e2014-03-13 15:41:46 +000010504 for (auto &BI : Class->bases()) {
10505 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000010506 while (!Worklist.empty()) {
10507 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10508 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10509
10510 // If the base has no non-trivial move assignment operators,
10511 // we don't care about moves from it.
10512 if (!Base->hasNonTrivialMoveAssignment())
10513 continue;
10514
10515 // If there's nothing virtual here, skip it.
10516 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10517 continue;
10518
10519 // If we're not actually going to call a move assignment for this base,
10520 // or the selected move assignment is trivial, skip it.
10521 Sema::SpecialMemberOverloadResult *SMOR =
10522 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10523 /*ConstArg*/false, /*VolatileArg*/false,
10524 /*RValueThis*/true, /*ConstThis*/false,
10525 /*VolatileThis*/false);
10526 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10527 !SMOR->getMethod()->isMoveAssignmentOperator())
10528 continue;
10529
10530 if (BaseSpec->isVirtual()) {
10531 // We're going to move-assign this virtual base, and its move
10532 // assignment operator is not trivial. If this can happen for
10533 // multiple distinct direct bases of Class, diagnose it. (If it
10534 // only happens in one base, we'll diagnose it when synthesizing
10535 // that base class's move assignment operator.)
10536 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +000010537 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +000010538 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +000010539 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010540 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10541 << Class << Base;
10542 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10543 << (Base->getCanonicalDecl() ==
10544 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10545 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +000010546 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +000010547 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +000010548 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10549 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +000010550
10551 // Only diagnose each vbase once.
Craig Topperc3ec1492014-05-26 06:22:03 +000010552 Existing = nullptr;
Richard Smithb2504bd2013-11-04 04:26:14 +000010553 }
10554 } else {
10555 // Only walk over bases that have defaulted move assignment operators.
10556 // We assume that any user-provided move assignment operator handles
10557 // the multiple-moves-of-vbase case itself somehow.
10558 if (!SMOR->getMethod()->isDefaulted())
10559 continue;
10560
10561 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +000010562 for (auto &BI : Base->bases())
10563 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000010564 }
10565 }
10566 }
10567}
10568
Sebastian Redl22653ba2011-08-30 19:58:05 +000010569void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10570 CXXMethodDecl *MoveAssignOperator) {
10571 assert((MoveAssignOperator->isDefaulted() &&
10572 MoveAssignOperator->isOverloadedOperator() &&
10573 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000010574 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10575 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010576 "DefineImplicitMoveAssignment called for wrong function");
10577
10578 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10579
10580 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10581 MoveAssignOperator->setInvalidDecl();
10582 return;
10583 }
10584
Eli Friedman276dd182013-09-05 00:02:25 +000010585 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010586
Eli Friedmaneaf34142012-10-18 20:14:08 +000010587 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010588 DiagnosticErrorTrap Trap(Diags);
10589
10590 // C++0x [class.copy]p28:
10591 // The implicitly-defined or move assignment operator for a non-union class
10592 // X performs memberwise move assignment of its subobjects. The direct base
10593 // classes of X are assigned first, in the order of their declaration in the
10594 // base-specifier-list, and then the immediate non-static data members of X
10595 // are assigned, in the order in which they were declared in the class
10596 // definition.
10597
Richard Smithb2504bd2013-11-04 04:26:14 +000010598 // Issue a warning if our implicit move assignment operator will move
10599 // from a virtual base more than once.
10600 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +000010601
Sebastian Redl22653ba2011-08-30 19:58:05 +000010602 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000010603 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010604
10605 // The parameter for the "other" object, which we are move from.
10606 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10607 QualType OtherRefType = Other->getType()->
10608 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +000010609 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010610 "Bad argument type of defaulted move assignment");
10611
10612 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010613 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10614 ? MoveAssignOperator->getLocEnd()
10615 : MoveAssignOperator->getLocation();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010616
Pavel Labath58934982013-08-30 08:52:28 +000010617 // Builds a reference to the "other" object.
10618 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010619 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +000010620 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010621
Pavel Labath58934982013-08-30 08:52:28 +000010622 // Builds the "this" pointer.
10623 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010624
Sebastian Redl22653ba2011-08-30 19:58:05 +000010625 // Assign base classes.
10626 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000010627 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010628 // C++11 [class.copy]p28:
10629 // It is unspecified whether subobjects representing virtual base classes
10630 // are assigned more than once by the implicitly-defined copy assignment
10631 // operator.
10632 // FIXME: Do not assign to a vbase that will be assigned by some other base
10633 // class. For a move-assignment, this can result in the vbase being moved
10634 // multiple times.
10635
Sebastian Redl22653ba2011-08-30 19:58:05 +000010636 // Form the assignment:
10637 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000010638 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010639 if (!BaseType->isRecordType()) {
10640 Invalid = true;
10641 continue;
10642 }
10643
10644 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000010645 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010646
10647 // Construct the "from" expression, which is an implicit cast to the
10648 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010649 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010650
10651 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000010652 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010653
10654 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010655 CastBuilder To(DerefThis,
10656 Context.getCVRQualifiedType(
10657 BaseType, MoveAssignOperator->getTypeQualifiers()),
10658 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010659
10660 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +000010661 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000010662 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010663 /*CopyingBaseSubobject=*/true,
10664 /*Copying=*/false);
10665 if (Move.isInvalid()) {
10666 Diag(CurrentLocation, diag::note_member_synthesized_at)
10667 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10668 MoveAssignOperator->setInvalidDecl();
10669 return;
10670 }
10671
10672 // Success! Record the move.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010673 Statements.push_back(Move.getAs<Expr>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010674 }
10675
Sebastian Redl22653ba2011-08-30 19:58:05 +000010676 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010677 for (auto *Field : ClassDecl->fields()) {
Richard Smith419bd092015-04-29 19:26:57 +000010678 // FIXME: We should form some kind of AST representation for the implied
10679 // memcpy in a union copy operation.
10680 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
Douglas Gregor556e5862011-10-10 17:22:13 +000010681 continue;
10682
Eli Friedmanc9817fd2013-06-07 01:48:56 +000010683 if (Field->isInvalidDecl()) {
10684 Invalid = true;
10685 continue;
10686 }
10687
Sebastian Redl22653ba2011-08-30 19:58:05 +000010688 // Check for members of reference type; we can't move those.
10689 if (Field->getType()->isReferenceType()) {
10690 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10691 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10692 Diag(Field->getLocation(), diag::note_declared_at);
10693 Diag(CurrentLocation, diag::note_member_synthesized_at)
10694 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10695 Invalid = true;
10696 continue;
10697 }
10698
10699 // Check for members of const-qualified, non-class type.
10700 QualType BaseType = Context.getBaseElementType(Field->getType());
10701 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10702 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10703 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10704 Diag(Field->getLocation(), diag::note_declared_at);
10705 Diag(CurrentLocation, diag::note_member_synthesized_at)
10706 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10707 Invalid = true;
10708 continue;
10709 }
10710
10711 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000010712 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10713 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010714
10715 QualType FieldType = Field->getType().getNonReferenceType();
10716 if (FieldType->isIncompleteArrayType()) {
10717 assert(ClassDecl->hasFlexibleArrayMember() &&
10718 "Incomplete array type is not valid");
10719 continue;
10720 }
10721
10722 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010723 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10724 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010725 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010726 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000010727 MemberBuilder From(MoveOther, OtherRefType,
10728 /*IsArrow=*/false, MemberLookup);
10729 MemberBuilder To(This, getCurrentThisType(),
10730 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010731
Pavel Labath58934982013-08-30 08:52:28 +000010732 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +000010733 "Member reference with rvalue base must be rvalue except for reference "
10734 "members, which aren't allowed for move assignment.");
10735
Sebastian Redl22653ba2011-08-30 19:58:05 +000010736 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000010737 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010738 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010739 /*CopyingBaseSubobject=*/false,
10740 /*Copying=*/false);
10741 if (Move.isInvalid()) {
10742 Diag(CurrentLocation, diag::note_member_synthesized_at)
10743 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10744 MoveAssignOperator->setInvalidDecl();
10745 return;
10746 }
Richard Smith11d19592012-11-12 23:33:00 +000010747
Sebastian Redl22653ba2011-08-30 19:58:05 +000010748 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010749 Statements.push_back(Move.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010750 }
10751
10752 if (!Invalid) {
10753 // Add a "return *this;"
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010754 ExprResult ThisObj =
10755 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10756
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010757 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010758 if (Return.isInvalid())
10759 Invalid = true;
10760 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010761 Statements.push_back(Return.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010762
10763 if (Trap.hasErrorOccurred()) {
10764 Diag(CurrentLocation, diag::note_member_synthesized_at)
10765 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10766 Invalid = true;
10767 }
10768 }
10769 }
10770
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010771 // The exception specification is needed because we are defining the
10772 // function.
10773 ResolveExceptionSpec(CurrentLocation,
10774 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
10775
Sebastian Redl22653ba2011-08-30 19:58:05 +000010776 if (Invalid) {
10777 MoveAssignOperator->setInvalidDecl();
10778 return;
10779 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010780
10781 StmtResult Body;
10782 {
10783 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010784 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010785 /*isStmtExpr=*/false);
10786 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10787 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010788 MoveAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010789
10790 if (ASTMutationListener *L = getASTMutationListener()) {
10791 L->CompletedImplicitDefinition(MoveAssignOperator);
10792 }
10793}
10794
Richard Smithd3b5c9082012-07-27 04:22:15 +000010795Sema::ImplicitExceptionSpecification
10796Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10797 CXXRecordDecl *ClassDecl = MD->getParent();
10798
10799 ImplicitExceptionSpecification ExceptSpec(*this);
10800 if (ClassDecl->isInvalidDecl())
10801 return ExceptSpec;
10802
10803 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000010804 assert(T->getNumParams() >= 1 && "not a copy ctor");
10805 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010806
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010807 // C++ [except.spec]p14:
10808 // An implicitly declared special member function (Clause 12) shall have an
10809 // exception-specification. [...]
Aaron Ballman574705e2014-03-13 15:41:46 +000010810 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010811 // Virtual bases are handled below.
Aaron Ballman574705e2014-03-13 15:41:46 +000010812 if (Base.isVirtual())
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010813 continue;
10814
Douglas Gregora6d69502010-07-02 23:41:54 +000010815 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010816 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010817 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010818 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman574705e2014-03-13 15:41:46 +000010819 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010820 }
Aaron Ballman445a9392014-03-13 16:15:17 +000010821 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregora6d69502010-07-02 23:41:54 +000010822 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010823 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010824 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010825 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman445a9392014-03-13 16:15:17 +000010826 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010827 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010828 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010829 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000010830 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10831 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000010832 LookupCopyingConstructor(FieldClassDecl,
10833 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000010834 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010835 }
10836 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010837
Richard Smithd3b5c9082012-07-27 04:22:15 +000010838 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000010839}
10840
10841CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10842 CXXRecordDecl *ClassDecl) {
10843 // C++ [class.copy]p4:
10844 // If the class definition does not explicitly declare a copy
10845 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000010846 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000010847
Richard Smith8bf22e52012-11-29 01:34:07 +000010848 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10849 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010850 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010851
Alexis Hunt913820d2011-05-13 06:10:58 +000010852 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10853 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000010854 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000010855 if (Const)
10856 ArgType = ArgType.withConst();
10857 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000010858
Richard Smithb5800092012-06-10 05:43:50 +000010859 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10860 CXXCopyConstructor,
10861 Const);
10862
Douglas Gregor54be3392010-07-01 17:57:27 +000010863 DeclarationName Name
10864 = Context.DeclarationNames.getCXXConstructorName(
10865 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010866 SourceLocation ClassLoc = ClassDecl->getLocation();
10867 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000010868
10869 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010870 // member of its class.
10871 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010872 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000010873 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010874 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000010875 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000010876 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010877
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010878 if (getLangOpts().CUDA) {
10879 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
10880 CopyConstructor,
10881 /* ConstRHS */ Const,
10882 /* Diagnose */ false);
10883 }
10884
Richard Smithd3b5c9082012-07-27 04:22:15 +000010885 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010886 FunctionProtoType::ExtProtoInfo EPI =
10887 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010888 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010889 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010890
Douglas Gregor54be3392010-07-01 17:57:27 +000010891 // Add the parameter to the constructor.
10892 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000010893 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010894 /*IdentifierInfo=*/nullptr,
10895 ArgType, /*TInfo=*/nullptr,
10896 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010897 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000010898
Richard Smith6b02d462012-12-08 08:32:28 +000010899 CopyConstructor->setTrivial(
10900 ClassDecl->needsOverloadResolutionForCopyConstructor()
10901 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10902 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000010903
Richard Smith852265f2012-03-30 20:53:28 +000010904 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +000010905 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010906
Richard Smith6b02d462012-12-08 08:32:28 +000010907 // Note that we have declared this constructor.
10908 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10909
10910 if (Scope *S = getScopeForContext(ClassDecl))
10911 PushOnScopeChains(CopyConstructor, S, false);
10912 ClassDecl->addDecl(CopyConstructor);
10913
Douglas Gregor54be3392010-07-01 17:57:27 +000010914 return CopyConstructor;
10915}
10916
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010917void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000010918 CXXConstructorDecl *CopyConstructor) {
10919 assert((CopyConstructor->isDefaulted() &&
10920 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010921 !CopyConstructor->doesThisDeclarationHaveABody() &&
10922 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010923 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010924
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000010925 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010926 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010927
Richard Smithd577fbb2013-06-13 03:23:42 +000010928 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000010929 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000010930 // deprecated if the class has a user-declared copy assignment operator
10931 // or a user-declared destructor.
10932 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10933 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10934
Eli Friedmaneaf34142012-10-18 20:14:08 +000010935 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010936 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010937
David Blaikie3fc2f912013-01-17 05:26:25 +000010938 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010939 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000010940 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000010941 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000010942 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000010943 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010944 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10945 ? CopyConstructor->getLocEnd()
10946 : CopyConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010947 Sema::CompoundScopeRAII CompoundScope(*this);
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010948 CopyConstructor->setBody(
10949 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000010950 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010951
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010952 // The exception specification is needed because we are defining the
10953 // function.
10954 ResolveExceptionSpec(CurrentLocation,
10955 CopyConstructor->getType()->castAs<FunctionProtoType>());
10956
Eli Friedman276dd182013-09-05 00:02:25 +000010957 CopyConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000010958 MarkVTableUsed(CurrentLocation, ClassDecl);
10959
Sebastian Redlab238a72011-04-24 16:28:06 +000010960 if (ASTMutationListener *L = getASTMutationListener()) {
10961 L->CompletedImplicitDefinition(CopyConstructor);
10962 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010963}
10964
Sebastian Redl22653ba2011-08-30 19:58:05 +000010965Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010966Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10967 CXXRecordDecl *ClassDecl = MD->getParent();
10968
Sebastian Redl22653ba2011-08-30 19:58:05 +000010969 // C++ [except.spec]p14:
10970 // An implicitly declared special member function (Clause 12) shall have an
10971 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000010972 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010973 if (ClassDecl->isInvalidDecl())
10974 return ExceptSpec;
10975
10976 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000010977 for (const auto &B : ClassDecl->bases()) {
10978 if (B.isVirtual()) // Handled below.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010979 continue;
10980
Aaron Ballman574705e2014-03-13 15:41:46 +000010981 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010982 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010983 CXXConstructorDecl *Constructor =
10984 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010985 // If this is a deleted function, add it anyway. This might be conformant
10986 // with the standard. This might not. I'm not sure. It might not matter.
10987 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +000010988 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010989 }
10990 }
10991
10992 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000010993 for (const auto &B : ClassDecl->vbases()) {
10994 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010995 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010996 CXXConstructorDecl *Constructor =
10997 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010998 // If this is a deleted function, add it anyway. This might be conformant
10999 // with the standard. This might not. I'm not sure. It might not matter.
11000 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000011001 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011002 }
11003 }
11004
11005 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011006 for (const auto *F : ClassDecl->fields()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000011007 QualType FieldType = Context.getBaseElementType(F->getType());
11008 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
11009 CXXConstructorDecl *Constructor =
11010 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011011 // If this is a deleted function, add it anyway. This might be conformant
11012 // with the standard. This might not. I'm not sure. It might not matter.
11013 // In particular, the problem is that this function never gets called. It
11014 // might just be ill-formed because this function attempts to refer to
11015 // a deleted function here.
11016 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000011017 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011018 }
11019 }
11020
11021 return ExceptSpec;
11022}
11023
11024CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
11025 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000011026 assert(ClassDecl->needsImplicitMoveConstructor());
11027
Richard Smith8bf22e52012-11-29 01:34:07 +000011028 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
11029 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000011030 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000011031
Sebastian Redl22653ba2011-08-30 19:58:05 +000011032 QualType ClassType = Context.getTypeDeclType(ClassDecl);
11033 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011034
Richard Smithb5800092012-06-10 05:43:50 +000011035 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11036 CXXMoveConstructor,
11037 false);
11038
Sebastian Redl22653ba2011-08-30 19:58:05 +000011039 DeclarationName Name
11040 = Context.DeclarationNames.getCXXConstructorName(
11041 Context.getCanonicalType(ClassType));
11042 SourceLocation ClassLoc = ClassDecl->getLocation();
11043 DeclarationNameInfo NameInfo(Name, ClassLoc);
11044
Richard Smith99005e62013-05-07 03:19:20 +000011045 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000011046 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000011047 // member of its class.
11048 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000011049 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000011050 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000011051 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011052 MoveConstructor->setAccess(AS_public);
11053 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000011054
Eli Bendersky9a220fc2014-09-29 20:38:29 +000011055 if (getLangOpts().CUDA) {
11056 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
11057 MoveConstructor,
11058 /* ConstRHS */ false,
11059 /* Diagnose */ false);
11060 }
11061
Richard Smithd3b5c9082012-07-27 04:22:15 +000011062 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000011063 FunctionProtoType::ExtProtoInfo EPI =
11064 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000011065 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000011066 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000011067
Sebastian Redl22653ba2011-08-30 19:58:05 +000011068 // Add the parameter to the constructor.
11069 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
11070 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000011071 /*IdentifierInfo=*/nullptr,
11072 ArgType, /*TInfo=*/nullptr,
11073 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000011074 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011075
Richard Smith6b02d462012-12-08 08:32:28 +000011076 MoveConstructor->setTrivial(
11077 ClassDecl->needsOverloadResolutionForMoveConstructor()
11078 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
11079 : ClassDecl->hasTrivialMoveConstructor());
11080
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000011081 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000011082 ClassDecl->setImplicitMoveConstructorIsDeleted();
11083 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011084 }
11085
11086 // Note that we have declared this constructor.
11087 ++ASTContext::NumImplicitMoveConstructorsDeclared;
11088
11089 if (Scope *S = getScopeForContext(ClassDecl))
11090 PushOnScopeChains(MoveConstructor, S, false);
11091 ClassDecl->addDecl(MoveConstructor);
11092
11093 return MoveConstructor;
11094}
11095
11096void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
11097 CXXConstructorDecl *MoveConstructor) {
11098 assert((MoveConstructor->isDefaulted() &&
11099 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000011100 !MoveConstructor->doesThisDeclarationHaveABody() &&
11101 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000011102 "DefineImplicitMoveConstructor - call it for implicit move ctor");
11103
11104 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
11105 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
11106
Eli Friedmaneaf34142012-10-18 20:14:08 +000011107 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011108 DiagnosticErrorTrap Trap(Diags);
11109
David Blaikie3fc2f912013-01-17 05:26:25 +000011110 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000011111 Trap.hasErrorOccurred()) {
11112 Diag(CurrentLocation, diag::note_member_synthesized_at)
11113 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
11114 MoveConstructor->setInvalidDecl();
11115 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011116 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
11117 ? MoveConstructor->getLocEnd()
11118 : MoveConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011119 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000011120 MoveConstructor->setBody(ActOnCompoundStmt(
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011121 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011122 }
11123
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000011124 // The exception specification is needed because we are defining the
11125 // function.
11126 ResolveExceptionSpec(CurrentLocation,
11127 MoveConstructor->getType()->castAs<FunctionProtoType>());
11128
Eli Friedman276dd182013-09-05 00:02:25 +000011129 MoveConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000011130 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011131
11132 if (ASTMutationListener *L = getASTMutationListener()) {
11133 L->CompletedImplicitDefinition(MoveConstructor);
11134 }
11135}
11136
Douglas Gregor74f7d502012-02-15 19:33:52 +000011137bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000011138 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000011139}
Douglas Gregord3b672c2012-02-16 01:06:16 +000011140
11141void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000011142 SourceLocation CurrentLocation,
11143 CXXConversionDecl *Conv) {
11144 CXXRecordDecl *Lambda = Conv->getParent();
11145 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
11146 // If we are defining a specialization of a conversion to function-ptr
11147 // cache the deduced template arguments for this specialization
11148 // so that we can use them to retrieve the corresponding call-operator
11149 // and static-invoker.
Craig Topperc3ec1492014-05-26 06:22:03 +000011150 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
11151
Faisal Vali571df122013-09-29 08:45:24 +000011152 // Retrieve the corresponding call-operator specialization.
11153 if (Lambda->isGenericLambda()) {
11154 assert(Conv->isFunctionTemplateSpecialization());
11155 FunctionTemplateDecl *CallOpTemplate =
11156 CallOp->getDescribedFunctionTemplate();
11157 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
Craig Topperc3ec1492014-05-26 06:22:03 +000011158 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000011159 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000011160 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000011161 InsertPos);
11162 assert(CallOpSpec &&
11163 "Conversion operator must have a corresponding call operator");
11164 CallOp = cast<CXXMethodDecl>(CallOpSpec);
11165 }
11166 // Mark the call operator referenced (and add to pending instantiations
11167 // if necessary).
11168 // For both the conversion and static-invoker template specializations
11169 // we construct their body's in this function, so no need to add them
11170 // to the PendingInstantiations.
11171 MarkFunctionReferenced(CurrentLocation, CallOp);
11172
Eli Friedmaneaf34142012-10-18 20:14:08 +000011173 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011174 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000011175
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011176 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000011177 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
11178 // ... and get the corresponding specialization for a generic lambda.
11179 if (Lambda->isGenericLambda()) {
11180 assert(DeducedTemplateArgs &&
11181 "Must have deduced template arguments from Conversion Operator");
11182 FunctionTemplateDecl *InvokeTemplate =
11183 Invoker->getDescribedFunctionTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +000011184 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000011185 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000011186 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000011187 InsertPos);
11188 assert(InvokeSpec &&
11189 "Must have a corresponding static invoker specialization");
11190 Invoker = cast<CXXMethodDecl>(InvokeSpec);
11191 }
11192 // Construct the body of the conversion function { return __invoke; }.
11193 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011194 VK_LValue, Conv->getLocation()).get();
Faisal Vali571df122013-09-29 08:45:24 +000011195 assert(FunctionRef && "Can't refer to __invoke function?");
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011196 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
Faisal Vali571df122013-09-29 08:45:24 +000011197 Conv->setBody(new (Context) CompoundStmt(Context, Return,
11198 Conv->getLocation(),
11199 Conv->getLocation()));
11200
11201 Conv->markUsed(Context);
11202 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000011203
Faisal Vali571df122013-09-29 08:45:24 +000011204 // Fill in the __invoke function with a dummy implementation. IR generation
11205 // will fill in the actual details.
11206 Invoker->markUsed(Context);
11207 Invoker->setReferenced();
11208 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
11209
Douglas Gregord3b672c2012-02-16 01:06:16 +000011210 if (ASTMutationListener *L = getASTMutationListener()) {
11211 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000011212 L->CompletedImplicitDefinition(Invoker);
11213 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000011214}
11215
Faisal Vali571df122013-09-29 08:45:24 +000011216
11217
Douglas Gregord3b672c2012-02-16 01:06:16 +000011218void Sema::DefineImplicitLambdaToBlockPointerConversion(
11219 SourceLocation CurrentLocation,
11220 CXXConversionDecl *Conv)
11221{
Faisal Vali850da1a2013-09-29 17:08:32 +000011222 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000011223
Eli Friedman276dd182013-09-05 00:02:25 +000011224 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011225
Eli Friedmaneaf34142012-10-18 20:14:08 +000011226 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000011227 DiagnosticErrorTrap Trap(Diags);
11228
Douglas Gregored90df32012-02-22 05:02:47 +000011229 // Copy-initialize the lambda object as needed to capture it.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011230 Expr *This = ActOnCXXThis(CurrentLocation).get();
11231 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
Douglas Gregord3b672c2012-02-16 01:06:16 +000011232
Eli Friedman98b01ed2012-03-01 04:01:32 +000011233 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
11234 Conv->getLocation(),
11235 Conv, DerefThis);
11236
11237 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
11238 // behavior. Note that only the general conversion function does this
11239 // (since it's unusable otherwise); in the case where we inline the
11240 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011241 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000011242 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
11243 CK_CopyAndAutoreleaseBlockObject,
Craig Topperc3ec1492014-05-26 06:22:03 +000011244 BuildBlock.get(), nullptr, VK_RValue);
Eli Friedman98b01ed2012-03-01 04:01:32 +000011245
11246 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000011247 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000011248 Conv->setInvalidDecl();
11249 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000011250 }
Douglas Gregored90df32012-02-22 05:02:47 +000011251
Douglas Gregored90df32012-02-22 05:02:47 +000011252 // Create the return statement that returns the block from the conversion
11253 // function.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000011254 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000011255 if (Return.isInvalid()) {
11256 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11257 Conv->setInvalidDecl();
11258 return;
11259 }
11260
11261 // Set the body of the conversion function.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011262 Stmt *ReturnS = Return.get();
Nico Webera2a0eb92012-12-29 20:03:39 +000011263 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000011264 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000011265 Conv->getLocation()));
11266
Douglas Gregored90df32012-02-22 05:02:47 +000011267 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000011268 if (ASTMutationListener *L = getASTMutationListener()) {
11269 L->CompletedImplicitDefinition(Conv);
11270 }
11271}
11272
Douglas Gregord2f70072012-03-10 06:53:13 +000011273/// \brief Determine whether the given list arguments contains exactly one
11274/// "real" (non-default) argument.
11275static bool hasOneRealArgument(MultiExprArg Args) {
11276 switch (Args.size()) {
11277 case 0:
11278 return false;
11279
11280 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011281 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000011282 return false;
11283
11284 // fall through
11285 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011286 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000011287 }
11288
11289 return false;
11290}
11291
John McCalldadc5752010-08-24 06:29:42 +000011292ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000011293Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +000011294 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000011295 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011296 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000011297 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011298 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011299 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000011300 unsigned ConstructKind,
11301 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000011302 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000011303
Douglas Gregor45cf7e32010-04-02 18:24:57 +000011304 // C++0x [class.copy]p34:
11305 // When certain criteria are met, an implementation is allowed to
11306 // omit the copy/move construction of a class object, even if the
11307 // copy/move constructor and/or destructor for the object have
11308 // side effects. [...]
11309 // - when a temporary class object that has not been bound to a
11310 // reference (12.2) would be copied/moved to a class object
11311 // with the same cv-unqualified type, the copy/move operation
11312 // can be omitted by constructing the temporary object
11313 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +000011314 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregord2f70072012-03-10 06:53:13 +000011315 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011316 Expr *SubExpr = ExprArgs[0];
John McCall7a626f62010-09-15 10:14:12 +000011317 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +000011318 }
Mike Stump11289f42009-09-09 15:08:12 +000011319
11320 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011321 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011322 IsListInitialization,
11323 IsStdInitListInitialization, RequiresZeroInit,
Richard Smithd59b8322012-12-19 01:39:02 +000011324 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000011325}
11326
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000011327/// BuildCXXConstructExpr - Creates a complete call to a constructor,
11328/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +000011329ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000011330Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11331 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000011332 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011333 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000011334 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011335 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011336 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000011337 unsigned ConstructKind,
11338 SourceRange ParenRange) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011339 MarkFunctionReferenced(ConstructLoc, Constructor);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011340 return CXXConstructExpr::Create(
11341 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011342 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
11343 RequiresZeroInit,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011344 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
11345 ParenRange);
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000011346}
11347
Reid Klecknerd60b82f2014-11-17 23:36:45 +000011348ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
11349 assert(Field->hasInClassInitializer());
11350
11351 // If we already have the in-class initializer nothing needs to be done.
11352 if (Field->getInClassInitializer())
11353 return CXXDefaultInitExpr::Create(Context, Loc, Field);
11354
11355 // Maybe we haven't instantiated the in-class initializer. Go check the
11356 // pattern FieldDecl to see if it has one.
11357 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
11358
11359 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
11360 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
11361 DeclContext::lookup_result Lookup =
11362 ClassPattern->lookup(Field->getDeclName());
11363 assert(Lookup.size() == 1);
11364 FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]);
11365 if (InstantiateInClassInitializer(Loc, Field, Pattern,
11366 getTemplateInstantiationArgs(Field)))
11367 return ExprError();
11368 return CXXDefaultInitExpr::Create(Context, Loc, Field);
11369 }
11370
11371 // DR1351:
11372 // If the brace-or-equal-initializer of a non-static data member
11373 // invokes a defaulted default constructor of its class or of an
11374 // enclosing class in a potentially evaluated subexpression, the
11375 // program is ill-formed.
11376 //
11377 // This resolution is unworkable: the exception specification of the
11378 // default constructor can be needed in an unevaluated context, in
11379 // particular, in the operand of a noexcept-expression, and we can be
11380 // unable to compute an exception specification for an enclosed class.
11381 //
11382 // Any attempt to resolve the exception specification of a defaulted default
11383 // constructor before the initializer is lexically complete will ultimately
11384 // come here at which point we can diagnose it.
11385 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
11386 if (OutermostClass == ParentRD) {
11387 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
11388 << ParentRD << Field;
11389 } else {
11390 Diag(Field->getLocEnd(),
11391 diag::err_in_class_initializer_not_yet_parsed_outer_class)
11392 << ParentRD << OutermostClass << Field;
11393 }
11394
11395 return ExprError();
11396}
11397
John McCall03c48482010-02-02 09:10:11 +000011398void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000011399 if (VD->isInvalidDecl()) return;
11400
John McCall03c48482010-02-02 09:10:11 +000011401 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000011402 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000011403 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000011404 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000011405
Chandler Carruth86d17d32011-03-27 21:26:48 +000011406 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000011407 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000011408 CheckDestructorAccess(VD->getLocation(), Destructor,
11409 PDiag(diag::err_access_dtor_var)
11410 << VD->getDeclName()
11411 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000011412 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000011413
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000011414 if (Destructor->isTrivial()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000011415 if (!VD->hasGlobalStorage()) return;
11416
11417 // Emit warning for non-trivial dtor in global scope (a real global,
11418 // class-static, function-static).
11419 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
11420
11421 // TODO: this should be re-enabled for static locals by !CXAAtExit
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000011422 if (!VD->isStaticLocal())
Chandler Carruth86d17d32011-03-27 21:26:48 +000011423 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000011424}
11425
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011426/// \brief Given a constructor and the set of arguments provided for the
11427/// constructor, convert the arguments and add any required default arguments
11428/// to form a proper call to this constructor.
11429///
11430/// \returns true if an error occurred, false otherwise.
11431bool
11432Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
11433 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000011434 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000011435 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000011436 bool AllowExplicit,
11437 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011438 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
11439 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011440 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011441
11442 const FunctionProtoType *Proto
11443 = Constructor->getType()->getAs<FunctionProtoType>();
11444 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011445 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000011446
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011447 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011448 if (NumArgs < NumParams)
11449 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011450 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011451 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011452
11453 VariadicCallType CallType =
11454 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011455 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011456 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011457 Proto, 0,
11458 llvm::makeArrayRef(Args, NumArgs),
11459 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000011460 CallType, AllowExplicit,
11461 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000011462 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000011463
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011464 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011465
Dmitri Gribenko765396f2013-01-13 20:46:02 +000011466 CheckConstructorCall(Constructor,
Craig Topper8c2a2a02014-08-30 16:55:39 +000011467 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000011468 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011469
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011470 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000011471}
11472
Anders Carlssone363c8e2009-12-12 00:32:00 +000011473static inline bool
11474CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
11475 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000011476 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000011477 if (isa<NamespaceDecl>(DC)) {
11478 return SemaRef.Diag(FnDecl->getLocation(),
11479 diag::err_operator_new_delete_declared_in_namespace)
11480 << FnDecl->getDeclName();
11481 }
11482
11483 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000011484 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000011485 return SemaRef.Diag(FnDecl->getLocation(),
11486 diag::err_operator_new_delete_declared_static)
11487 << FnDecl->getDeclName();
11488 }
11489
Anders Carlsson60659a82009-12-12 02:43:16 +000011490 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000011491}
11492
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011493static inline bool
11494CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
11495 CanQualType ExpectedResultType,
11496 CanQualType ExpectedFirstParamType,
11497 unsigned DependentParamTypeDiag,
11498 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000011499 QualType ResultType =
11500 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011501
11502 // Check that the result type is not dependent.
11503 if (ResultType->isDependentType())
11504 return SemaRef.Diag(FnDecl->getLocation(),
11505 diag::err_operator_new_delete_dependent_result_type)
11506 << FnDecl->getDeclName() << ExpectedResultType;
11507
11508 // Check that the result type is what we expect.
11509 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
11510 return SemaRef.Diag(FnDecl->getLocation(),
11511 diag::err_operator_new_delete_invalid_result_type)
11512 << FnDecl->getDeclName() << ExpectedResultType;
11513
11514 // A function template must have at least 2 parameters.
11515 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
11516 return SemaRef.Diag(FnDecl->getLocation(),
11517 diag::err_operator_new_delete_template_too_few_parameters)
11518 << FnDecl->getDeclName();
11519
11520 // The function decl must have at least 1 parameter.
11521 if (FnDecl->getNumParams() == 0)
11522 return SemaRef.Diag(FnDecl->getLocation(),
11523 diag::err_operator_new_delete_too_few_parameters)
11524 << FnDecl->getDeclName();
11525
Sylvestre Ledru830885c2012-07-23 08:59:39 +000011526 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011527 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
11528 if (FirstParamType->isDependentType())
11529 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
11530 << FnDecl->getDeclName() << ExpectedFirstParamType;
11531
11532 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000011533 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011534 ExpectedFirstParamType)
11535 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
11536 << FnDecl->getDeclName() << ExpectedFirstParamType;
11537
11538 return false;
11539}
11540
Anders Carlsson12308f42009-12-11 23:23:22 +000011541static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011542CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000011543 // C++ [basic.stc.dynamic.allocation]p1:
11544 // A program is ill-formed if an allocation function is declared in a
11545 // namespace scope other than global scope or declared static in global
11546 // scope.
11547 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11548 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011549
11550 CanQualType SizeTy =
11551 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11552
11553 // C++ [basic.stc.dynamic.allocation]p1:
11554 // The return type shall be void*. The first parameter shall have type
11555 // std::size_t.
11556 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
11557 SizeTy,
11558 diag::err_operator_new_dependent_param_type,
11559 diag::err_operator_new_param_type))
11560 return true;
11561
11562 // C++ [basic.stc.dynamic.allocation]p1:
11563 // The first parameter shall not have an associated default argument.
11564 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000011565 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011566 diag::err_operator_new_default_arg)
11567 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11568
11569 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000011570}
11571
11572static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000011573CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000011574 // C++ [basic.stc.dynamic.deallocation]p1:
11575 // A program is ill-formed if deallocation functions are declared in a
11576 // namespace scope other than global scope or declared static in global
11577 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000011578 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11579 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000011580
11581 // C++ [basic.stc.dynamic.deallocation]p2:
11582 // Each deallocation function shall return void and its first parameter
11583 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011584 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
11585 SemaRef.Context.VoidPtrTy,
11586 diag::err_operator_delete_dependent_param_type,
11587 diag::err_operator_delete_param_type))
11588 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000011589
Anders Carlsson12308f42009-12-11 23:23:22 +000011590 return false;
11591}
11592
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011593/// CheckOverloadedOperatorDeclaration - Check whether the declaration
11594/// of this overloaded operator is well-formed. If so, returns false;
11595/// otherwise, emits appropriate diagnostics and returns true.
11596bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000011597 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011598 "Expected an overloaded operator declaration");
11599
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011600 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11601
Mike Stump11289f42009-09-09 15:08:12 +000011602 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011603 // The allocation and deallocation functions, operator new,
11604 // operator new[], operator delete and operator delete[], are
11605 // described completely in 3.7.3. The attributes and restrictions
11606 // found in the rest of this subclause do not apply to them unless
11607 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000011608 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000011609 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000011610
Anders Carlsson22f443f2009-12-12 00:26:23 +000011611 if (Op == OO_New || Op == OO_Array_New)
11612 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011613
11614 // C++ [over.oper]p6:
11615 // An operator function shall either be a non-static member
11616 // function or be a non-member function and have at least one
11617 // parameter whose type is a class, a reference to a class, an
11618 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000011619 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11620 if (MethodDecl->isStatic())
11621 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011622 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011623 } else {
11624 bool ClassOrEnumParam = false;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011625 for (auto Param : FnDecl->params()) {
11626 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000011627 if (ParamType->isDependentType() || ParamType->isRecordType() ||
11628 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011629 ClassOrEnumParam = true;
11630 break;
11631 }
11632 }
11633
Douglas Gregord69246b2008-11-17 16:14:12 +000011634 if (!ClassOrEnumParam)
11635 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011636 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011637 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011638 }
11639
11640 // C++ [over.oper]p8:
11641 // An operator function cannot have default arguments (8.3.6),
11642 // except where explicitly stated below.
11643 //
Mike Stump11289f42009-09-09 15:08:12 +000011644 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011645 // (C++ [over.call]p1).
11646 if (Op != OO_Call) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011647 for (auto Param : FnDecl->params()) {
11648 if (Param->hasDefaultArg())
11649 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000011650 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011651 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011652 }
11653 }
11654
Douglas Gregor6cf08062008-11-10 13:38:07 +000011655 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11656 { false, false, false }
11657#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11658 , { Unary, Binary, MemberOnly }
11659#include "clang/Basic/OperatorKinds.def"
11660 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011661
Douglas Gregor6cf08062008-11-10 13:38:07 +000011662 bool CanBeUnaryOperator = OperatorUses[Op][0];
11663 bool CanBeBinaryOperator = OperatorUses[Op][1];
11664 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011665
11666 // C++ [over.oper]p8:
11667 // [...] Operator functions cannot have more or fewer parameters
11668 // than the number required for the corresponding operator, as
11669 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000011670 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000011671 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011672 if (Op != OO_Call &&
11673 ((NumParams == 1 && !CanBeUnaryOperator) ||
11674 (NumParams == 2 && !CanBeBinaryOperator) ||
11675 (NumParams < 1) || (NumParams > 2))) {
11676 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011677 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000011678 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011679 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000011680 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011681 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011682 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000011683 assert(CanBeBinaryOperator &&
11684 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011685 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011686 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011687
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011688 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011689 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011690 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000011691
Douglas Gregord69246b2008-11-17 16:14:12 +000011692 // Overloaded operators other than operator() cannot be variadic.
11693 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000011694 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000011695 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011696 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011697 }
11698
11699 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000011700 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11701 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011702 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011703 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011704 }
11705
11706 // C++ [over.inc]p1:
11707 // The user-defined function called operator++ implements the
11708 // prefix and postfix ++ operator. If this function is a member
11709 // function with no parameters, or a non-member function with one
11710 // parameter of class or enumeration type, it defines the prefix
11711 // increment operator ++ for objects of that type. If the function
11712 // is a member function with one parameter (which shall be of type
11713 // int) or a non-member function with two parameters (the second
11714 // of which shall be of type int), it defines the postfix
11715 // increment operator ++ for objects of that type.
11716 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11717 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000011718 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011719
Richard Smith538b52a2014-01-30 22:24:05 +000011720 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11721 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000011722 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000011723 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000011724 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011725 }
11726
Douglas Gregord69246b2008-11-17 16:14:12 +000011727 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011728}
Chris Lattner3b024a32008-12-17 07:09:26 +000011729
Alexis Huntc88db062010-01-13 09:01:02 +000011730/// CheckLiteralOperatorDeclaration - Check whether the declaration
11731/// of this literal operator function is well-formed. If so, returns
11732/// false; otherwise, emits appropriate diagnostics and returns true.
11733bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000011734 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000011735 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11736 << FnDecl->getDeclName();
11737 return true;
11738 }
11739
Richard Smith72eebee2012-03-04 09:41:16 +000011740 if (FnDecl->isExternC()) {
11741 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11742 return true;
11743 }
11744
Alexis Huntc88db062010-01-13 09:01:02 +000011745 bool Valid = false;
11746
Richard Smithbcc22fc2012-03-09 08:00:36 +000011747 // This might be the definition of a literal operator template.
11748 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11749 // This might be a specialization of a literal operator template.
11750 if (!TpDecl)
11751 TpDecl = FnDecl->getPrimaryTemplate();
11752
Richard Smithb8b41d32013-10-07 19:57:58 +000011753 // template <char...> type operator "" name() and
11754 // template <class T, T...> type operator "" name() are the only valid
11755 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000011756 if (TpDecl) {
Richard Smith72eebee2012-03-04 09:41:16 +000011757 if (FnDecl->param_size() == 0) {
Richard Smithb8b41d32013-10-07 19:57:58 +000011758 // Must have one or two template parameters
Alexis Hunt7dd26172010-04-07 23:11:06 +000011759 TemplateParameterList *Params = TpDecl->getTemplateParameters();
11760 if (Params->size() == 1) {
11761 NonTypeTemplateParmDecl *PmDecl =
Richard Smithed943022012-08-03 21:14:57 +000011762 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +000011763
Alexis Hunt7dd26172010-04-07 23:11:06 +000011764 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +000011765 if (PmDecl && PmDecl->isTemplateParameterPack() &&
11766 Context.hasSameType(PmDecl->getType(), Context.CharTy))
11767 Valid = true;
Richard Smithb8b41d32013-10-07 19:57:58 +000011768 } else if (Params->size() == 2) {
11769 TemplateTypeParmDecl *PmType =
11770 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11771 NonTypeTemplateParmDecl *PmArgs =
11772 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11773
11774 // The second template parameter must be a parameter pack with the
11775 // first template parameter as its type.
11776 if (PmType && PmArgs &&
11777 !PmType->isTemplateParameterPack() &&
11778 PmArgs->isTemplateParameterPack()) {
11779 const TemplateTypeParmType *TArgs =
11780 PmArgs->getType()->getAs<TemplateTypeParmType>();
11781 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11782 TArgs->getIndex() == PmType->getIndex()) {
11783 Valid = true;
11784 if (ActiveTemplateInstantiations.empty())
11785 Diag(FnDecl->getLocation(),
11786 diag::ext_string_literal_operator_template);
11787 }
11788 }
Alexis Hunt7dd26172010-04-07 23:11:06 +000011789 }
11790 }
Richard Smith72eebee2012-03-04 09:41:16 +000011791 } else if (FnDecl->param_size()) {
Alexis Huntc88db062010-01-13 09:01:02 +000011792 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +000011793 FunctionDecl::param_iterator Param = FnDecl->param_begin();
11794
Richard Smith72eebee2012-03-04 09:41:16 +000011795 QualType T = (*Param)->getType().getUnqualifiedType();
Alexis Huntc88db062010-01-13 09:01:02 +000011796
Alexis Hunt079a6f72010-04-07 22:57:35 +000011797 // unsigned long long int, long double, and any character type are allowed
11798 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +000011799 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11800 Context.hasSameType(T, Context.LongDoubleTy) ||
11801 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011802 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011803 Context.hasSameType(T, Context.Char16Ty) ||
11804 Context.hasSameType(T, Context.Char32Ty)) {
11805 if (++Param == FnDecl->param_end())
11806 Valid = true;
11807 goto FinishedParams;
11808 }
11809
Alexis Hunt079a6f72010-04-07 22:57:35 +000011810 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +000011811 const PointerType *PT = T->getAs<PointerType>();
11812 if (!PT)
11813 goto FinishedParams;
11814 T = PT->getPointeeType();
Richard Smith72eebee2012-03-04 09:41:16 +000011815 if (!T.isConstQualified() || T.isVolatileQualified())
Alexis Huntc88db062010-01-13 09:01:02 +000011816 goto FinishedParams;
11817 T = T.getUnqualifiedType();
11818
11819 // Move on to the second parameter;
11820 ++Param;
11821
11822 // If there is no second parameter, the first must be a const char *
11823 if (Param == FnDecl->param_end()) {
11824 if (Context.hasSameType(T, Context.CharTy))
11825 Valid = true;
11826 goto FinishedParams;
11827 }
11828
11829 // const char *, const wchar_t*, const char16_t*, and const char32_t*
11830 // are allowed as the first parameter to a two-parameter function
11831 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011832 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011833 Context.hasSameType(T, Context.Char16Ty) ||
11834 Context.hasSameType(T, Context.Char32Ty)))
11835 goto FinishedParams;
11836
11837 // The second and final parameter must be an std::size_t
11838 T = (*Param)->getType().getUnqualifiedType();
11839 if (Context.hasSameType(T, Context.getSizeType()) &&
11840 ++Param == FnDecl->param_end())
11841 Valid = true;
11842 }
11843
11844 // FIXME: This diagnostic is absolutely terrible.
11845FinishedParams:
11846 if (!Valid) {
11847 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11848 << FnDecl->getDeclName();
11849 return true;
11850 }
11851
Richard Smith768cecc2012-03-09 08:16:22 +000011852 // A parameter-declaration-clause containing a default argument is not
11853 // equivalent to any of the permitted forms.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011854 for (auto Param : FnDecl->params()) {
11855 if (Param->hasDefaultArg()) {
11856 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000011857 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011858 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000011859 break;
11860 }
11861 }
11862
Richard Smith0df56f42012-03-08 02:39:21 +000011863 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000011864 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11865 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000011866 // C++11 [usrlit.suffix]p1:
11867 // Literal suffix identifiers that do not start with an underscore
11868 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000011869 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11870 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000011871 }
Richard Smith0df56f42012-03-08 02:39:21 +000011872
Alexis Huntc88db062010-01-13 09:01:02 +000011873 return false;
11874}
11875
Douglas Gregor07665a62009-01-05 19:45:36 +000011876/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11877/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000011878/// the '{'. ExternLoc is the location of the 'extern', Lang is the
11879/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000011880/// the '{' brace. Otherwise, this linkage specification does not
11881/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000011882Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000011883 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000011884 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011885 StringLiteral *Lit = cast<StringLiteral>(LangStr);
11886 if (!Lit->isAscii()) {
11887 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11888 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011889 return nullptr;
Richard Smith4ee696d2014-02-17 23:25:27 +000011890 }
11891
11892 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000011893 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000011894 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000011895 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000011896 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000011897 Language = LinkageSpecDecl::lang_cxx;
11898 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000011899 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11900 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011901 return nullptr;
Chris Lattner438e5012008-12-17 07:13:27 +000011902 }
Mike Stump11289f42009-09-09 15:08:12 +000011903
Chris Lattner438e5012008-12-17 07:13:27 +000011904 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000011905
Richard Smith4ee696d2014-02-17 23:25:27 +000011906 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11907 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000011908 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011909 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000011910 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000011911 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000011912}
11913
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000011914/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000011915/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11916/// valid, it's the position of the closing '}' brace in a linkage
11917/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000011918Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011919 Decl *LinkageSpec,
11920 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011921 if (RBraceLoc.isValid()) {
11922 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11923 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011924 }
Richard Smith4ee696d2014-02-17 23:25:27 +000011925 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000011926 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000011927}
11928
Michael Han84324352013-02-22 17:15:32 +000011929Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11930 AttributeList *AttrList,
11931 SourceLocation SemiLoc) {
11932 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11933 // Attribute declarations appertain to empty declaration so we handle
11934 // them here.
11935 if (AttrList)
11936 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000011937
Michael Han84324352013-02-22 17:15:32 +000011938 CurContext->addDecl(ED);
11939 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000011940}
11941
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011942/// \brief Perform semantic analysis for the variable declaration that
11943/// occurs within a C++ catch clause, returning the newly-created
11944/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011945VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000011946 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011947 SourceLocation StartLoc,
11948 SourceLocation Loc,
11949 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011950 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011951 QualType ExDeclType = TInfo->getType();
11952
Sebastian Redl54c04d42008-12-22 19:15:10 +000011953 // Arrays and functions decay.
11954 if (ExDeclType->isArrayType())
11955 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11956 else if (ExDeclType->isFunctionType())
11957 ExDeclType = Context.getPointerType(ExDeclType);
11958
11959 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11960 // The exception-declaration shall not denote a pointer or reference to an
11961 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000011962 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000011963 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011964 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000011965 Invalid = true;
11966 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011967
Sebastian Redl54c04d42008-12-22 19:15:10 +000011968 QualType BaseType = ExDeclType;
11969 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000011970 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011971 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011972 BaseType = Ptr->getPointeeType();
11973 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011974 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000011975 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000011976 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011977 BaseType = Ref->getPointeeType();
11978 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011979 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011980 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000011981 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011982 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000011983 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011984
Mike Stump11289f42009-09-09 15:08:12 +000011985 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011986 RequireNonAbstractType(Loc, ExDeclType,
11987 diag::err_abstract_type_in_decl,
11988 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000011989 Invalid = true;
11990
John McCall2ca705e2010-07-24 00:37:23 +000011991 // Only the non-fragile NeXT runtime currently supports C++ catches
11992 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011993 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000011994 QualType T = ExDeclType;
11995 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11996 T = RT->getPointeeType();
11997
11998 if (T->isObjCObjectType()) {
11999 Diag(Loc, diag::err_objc_object_catch);
12000 Invalid = true;
12001 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000012002 // FIXME: should this be a test for macosx-fragile specifically?
12003 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000012004 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000012005 }
12006 }
12007
Abramo Bagnaradff19302011-03-08 08:55:46 +000012008 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000012009 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000012010 ExDecl->setExceptionVariable(true);
12011
Douglas Gregor8ca0c642011-12-10 01:22:52 +000012012 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012013 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000012014 Invalid = true;
12015
Douglas Gregor750734c2011-07-06 18:14:43 +000012016 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000012017 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000012018 // Insulate this from anything else we might currently be parsing.
12019 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
12020
Douglas Gregor6de584c2010-03-05 23:38:39 +000012021 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000012022 // The object declared in an exception-declaration or, if the
12023 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000012024 // copy-initialized (8.5) from the exception object. [...]
12025 // The object is destroyed when the handler exits, after the destruction
12026 // of any automatic objects initialized within the handler.
12027 //
Nick Lewycky0f292892013-09-22 10:06:57 +000012028 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000012029 // it can be destroyed later.
David Majnemerfba75df2015-03-03 04:38:34 +000012030 QualType initType = Context.getExceptionObjectType(ExDeclType);
John McCall1bf58462011-02-16 08:02:54 +000012031
12032 InitializedEntity entity =
12033 InitializedEntity::InitializeVariable(ExDecl);
12034 InitializationKind initKind =
12035 InitializationKind::CreateCopy(Loc, SourceLocation());
12036
12037 Expr *opaqueValue =
12038 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000012039 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
12040 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000012041 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000012042 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000012043 else {
12044 // If the constructor used was non-trivial, set this as the
12045 // "initializer".
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012046 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000012047 if (!construct->getConstructor()->isTrivial()) {
12048 Expr *init = MaybeCreateExprWithCleanups(construct);
12049 ExDecl->setInit(init);
12050 }
12051
12052 // And make sure it's destructable.
12053 FinalizeVarWithDestructor(ExDecl, recordType);
12054 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000012055 }
12056 }
12057
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000012058 if (Invalid)
12059 ExDecl->setInvalidDecl();
12060
12061 return ExDecl;
12062}
12063
12064/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
12065/// handler.
John McCall48871652010-08-21 09:40:31 +000012066Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000012067 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000012068 bool Invalid = D.isInvalidType();
12069
12070 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000012071 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12072 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000012073 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12074 D.getIdentifierLoc());
12075 Invalid = true;
12076 }
12077
Sebastian Redl54c04d42008-12-22 19:15:10 +000012078 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000012079 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000012080 LookupOrdinaryName,
12081 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000012082 // The scope should be freshly made just for us. There is just no way
Aaron Ballman9ef622e2014-06-02 13:10:07 +000012083 // it contains any previous declaration, except for function parameters in
12084 // a function-try-block's catch statement.
John McCall48871652010-08-21 09:40:31 +000012085 assert(!S->isDeclScope(PrevDecl));
Aaron Ballman9ef622e2014-06-02 13:10:07 +000012086 if (isDeclInScope(PrevDecl, CurContext, S)) {
12087 Diag(D.getIdentifierLoc(), diag::err_redefinition)
12088 << D.getIdentifier();
12089 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12090 Invalid = true;
12091 } else if (PrevDecl->isTemplateParameter())
Sebastian Redl54c04d42008-12-22 19:15:10 +000012092 // Maybe we will complain about the shadowed template parameter.
12093 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000012094 }
12095
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000012096 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000012097 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
12098 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000012099 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000012100 }
12101
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000012102 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012103 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000012104 D.getIdentifierLoc(),
12105 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000012106 if (Invalid)
12107 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000012108
Sebastian Redl54c04d42008-12-22 19:15:10 +000012109 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000012110 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000012111 PushOnScopeChains(ExDecl, S);
12112 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012113 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000012114
Douglas Gregor758a8692009-06-17 21:51:59 +000012115 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000012116 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000012117}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012118
Abramo Bagnaraea947882011-03-08 16:41:52 +000012119Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000012120 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000012121 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000012122 SourceLocation RParenLoc) {
Richard Smith085a64f2014-06-20 19:57:12 +000012123 StringLiteral *AssertMessage =
12124 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012125
Richard Smithded9c2e2012-07-11 22:37:56 +000012126 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
Craig Topperc3ec1492014-05-26 06:22:03 +000012127 return nullptr;
Richard Smithded9c2e2012-07-11 22:37:56 +000012128
12129 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
12130 AssertMessage, RParenLoc, false);
12131}
12132
12133Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12134 Expr *AssertExpr,
12135 StringLiteral *AssertMessage,
12136 SourceLocation RParenLoc,
12137 bool Failed) {
Richard Smith085a64f2014-06-20 19:57:12 +000012138 assert(AssertExpr != nullptr && "Expected non-null condition");
Richard Smithded9c2e2012-07-11 22:37:56 +000012139 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
12140 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000012141 // In a static_assert-declaration, the constant-expression shall be a
12142 // constant expression that can be contextually converted to bool.
12143 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
12144 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000012145 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000012146
Richard Smith902ca212011-12-14 23:32:26 +000012147 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000012148 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000012149 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000012150 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000012151 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012152
Richard Smithded9c2e2012-07-11 22:37:56 +000012153 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012154 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000012155 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith085a64f2014-06-20 19:57:12 +000012156 if (AssertMessage)
12157 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000012158 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith085a64f2014-06-20 19:57:12 +000012159 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000012160 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000012161 }
Anders Carlsson54b26982009-03-14 00:33:21 +000012162 }
Mike Stump11289f42009-09-09 15:08:12 +000012163
Abramo Bagnaraea947882011-03-08 16:41:52 +000012164 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000012165 AssertExpr, AssertMessage, RParenLoc,
12166 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000012167
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012168 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000012169 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000012170}
Sebastian Redlf769df52009-03-24 22:27:57 +000012171
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012172/// \brief Perform semantic analysis of the given friend type declaration.
12173///
12174/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000012175FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000012176 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012177 TypeSourceInfo *TSInfo) {
12178 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
12179
12180 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000012181 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012182
Richard Smithc8239732011-10-18 21:39:00 +000012183 // C++03 [class.friend]p2:
12184 // An elaborated-type-specifier shall be used in a friend declaration
12185 // for a class.*
12186 //
12187 // * The class-key of the elaborated-type-specifier is required.
12188 if (!ActiveTemplateInstantiations.empty()) {
12189 // Do not complain about the form of friend template types during
12190 // template instantiation; we will already have complained when the
12191 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000012192 } else {
12193 if (!T->isElaboratedTypeSpecifier()) {
12194 // If we evaluated the type to a record type, suggest putting
12195 // a tag in front.
12196 if (const RecordType *RT = T->getAs<RecordType>()) {
12197 RecordDecl *RD = RT->getDecl();
Alp Tokera030cd02014-05-05 12:38:48 +000012198
12199 SmallString<16> InsertionText(" ");
12200 InsertionText += RD->getKindName();
12201
Nick Lewycky36722d22013-02-06 05:59:33 +000012202 Diag(TypeRange.getBegin(),
12203 getLangOpts().CPlusPlus11 ?
12204 diag::warn_cxx98_compat_unelaborated_friend_type :
12205 diag::ext_unelaborated_friend_type)
12206 << (unsigned) RD->getTagKind()
12207 << T
12208 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
12209 InsertionText);
12210 } else {
12211 Diag(FriendLoc,
12212 getLangOpts().CPlusPlus11 ?
12213 diag::warn_cxx98_compat_nonclass_type_friend :
12214 diag::ext_nonclass_type_friend)
12215 << T
12216 << TypeRange;
12217 }
12218 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000012219 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012220 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000012221 diag::warn_cxx98_compat_enum_friend :
12222 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012223 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000012224 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012225 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012226
Nick Lewycky36722d22013-02-06 05:59:33 +000012227 // C++11 [class.friend]p3:
12228 // A friend declaration that does not declare a function shall have one
12229 // of the following forms:
12230 // friend elaborated-type-specifier ;
12231 // friend simple-type-specifier ;
12232 // friend typename-specifier ;
12233 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
12234 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
12235 }
Richard Smitha31a89a2012-09-20 01:31:00 +000012236
Douglas Gregor3b4abb62010-04-07 17:57:12 +000012237 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000012238 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000012239 // the friend declaration is ignored.
Nikola Smiljanic3a01af02014-05-23 12:48:27 +000012240 return FriendDecl::Create(Context, CurContext,
12241 TSInfo->getTypeLoc().getLocStart(), TSInfo,
12242 FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012243}
12244
John McCallace48cd2010-10-19 01:40:49 +000012245/// Handle a friend tag declaration where the scope specifier was
12246/// templated.
12247Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
12248 unsigned TagSpec, SourceLocation TagLoc,
12249 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012250 IdentifierInfo *Name,
12251 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000012252 AttributeList *Attr,
12253 MultiTemplateParamsArg TempParamLists) {
12254 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12255
12256 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000012257 bool Invalid = false;
12258
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000012259 if (TemplateParameterList *TemplateParams =
12260 MatchTemplateParametersToScopeSpecifier(
Craig Topperc3ec1492014-05-26 06:22:03 +000012261 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000012262 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000012263 if (TemplateParams->size() > 0) {
12264 // This is a declaration of a class template.
12265 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +000012266 return nullptr;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000012267
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000012268 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
12269 NameLoc, Attr, TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000012270 /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000012271 FriendLoc, TempParamLists.size() - 1,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012272 TempParamLists.data()).get();
John McCallace48cd2010-10-19 01:40:49 +000012273 } else {
12274 // The "template<>" header is extraneous.
12275 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12276 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12277 isExplicitSpecialization = true;
12278 }
12279 }
12280
Craig Topperc3ec1492014-05-26 06:22:03 +000012281 if (Invalid) return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000012282
John McCallace48cd2010-10-19 01:40:49 +000012283 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000012284 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012285 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000012286 isAllExplicitSpecializations = false;
12287 break;
12288 }
12289 }
12290
12291 // FIXME: don't ignore attributes.
12292
12293 // If it's explicit specializations all the way down, just forget
12294 // about the template header and build an appropriate non-templated
12295 // friend. TODO: for source fidelity, remember the headers.
12296 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012297 if (SS.isEmpty()) {
12298 bool Owned = false;
12299 bool IsDependent = false;
12300 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000012301 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012302 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000012303 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000012304 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012305 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000012306 /*UnderlyingType=*/TypeResult(),
12307 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012308 }
Richard Smith649c7b062014-01-08 00:56:48 +000012309
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012310 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000012311 ElaboratedTypeKeyword Keyword
12312 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012313 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000012314 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000012315 if (T.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +000012316 return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000012317
12318 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12319 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000012320 DependentNameTypeLoc TL =
12321 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012322 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012323 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000012324 TL.setNameLoc(NameLoc);
12325 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000012326 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012327 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000012328 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000012329 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000012330 }
12331
12332 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012333 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000012334 Friend->setAccess(AS_public);
12335 CurContext->addDecl(Friend);
12336 return Friend;
12337 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012338
12339 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
12340
12341
John McCallace48cd2010-10-19 01:40:49 +000012342
12343 // Handle the case of a templated-scope friend class. e.g.
12344 // template <class T> class A<T>::B;
12345 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000012346 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
12347 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000012348 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12349 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
12350 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000012351 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012352 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012353 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000012354 TL.setNameLoc(NameLoc);
12355
12356 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012357 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000012358 Friend->setAccess(AS_public);
12359 Friend->setUnsupportedFriend(true);
12360 CurContext->addDecl(Friend);
12361 return Friend;
12362}
12363
12364
John McCall11083da2009-09-16 22:47:08 +000012365/// Handle a friend type declaration. This works in tandem with
12366/// ActOnTag.
12367///
12368/// Notes on friend class templates:
12369///
12370/// We generally treat friend class declarations as if they were
12371/// declaring a class. So, for example, the elaborated type specifier
12372/// in a friend declaration is required to obey the restrictions of a
12373/// class-head (i.e. no typedefs in the scope chain), template
12374/// parameters are required to match up with simple template-ids, &c.
12375/// However, unlike when declaring a template specialization, it's
12376/// okay to refer to a template specialization without an empty
12377/// template parameter declaration, e.g.
12378/// friend class A<T>::B<unsigned>;
12379/// We permit this as a special case; if there are any template
12380/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000012381/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000012382Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000012383 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012384 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000012385
12386 assert(DS.isFriendSpecified());
12387 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12388
John McCall11083da2009-09-16 22:47:08 +000012389 // Try to convert the decl specifier to a type. This works for
12390 // friend templates because ActOnTag never produces a ClassTemplateDecl
12391 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000012392 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000012393 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
12394 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000012395 if (TheDeclarator.isInvalidType())
Craig Topperc3ec1492014-05-26 06:22:03 +000012396 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012397
Douglas Gregor6c110f32010-12-16 01:14:37 +000012398 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000012399 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000012400
John McCall11083da2009-09-16 22:47:08 +000012401 // This is definitely an error in C++98. It's probably meant to
12402 // be forbidden in C++0x, too, but the specification is just
12403 // poorly written.
12404 //
12405 // The problem is with declarations like the following:
12406 // template <T> friend A<T>::foo;
12407 // where deciding whether a class C is a friend or not now hinges
12408 // on whether there exists an instantiation of A that causes
12409 // 'foo' to equal C. There are restrictions on class-heads
12410 // (which we declare (by fiat) elaborated friend declarations to
12411 // be) that makes this tractable.
12412 //
12413 // FIXME: handle "template <> friend class A<T>;", which
12414 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000012415 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000012416 Diag(Loc, diag::err_tagless_friend_type_template)
12417 << DS.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000012418 return nullptr;
John McCall11083da2009-09-16 22:47:08 +000012419 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012420
John McCallaa74a0c2009-08-28 07:59:38 +000012421 // C++98 [class.friend]p1: A friend of a class is a function
12422 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000012423 // This is fixed in DR77, which just barely didn't make the C++03
12424 // deadline. It's also a very silly restriction that seriously
12425 // affects inner classes and which nobody else seems to implement;
12426 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000012427 //
12428 // But note that we could warn about it: it's always useless to
12429 // friend one of your own members (it's not, however, worthless to
12430 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000012431
John McCall11083da2009-09-16 22:47:08 +000012432 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012433 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000012434 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012435 NumTempParamLists,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000012436 TempParams.data(),
John McCall15ad0962010-03-25 18:04:51 +000012437 TSI,
John McCall11083da2009-09-16 22:47:08 +000012438 DS.getFriendSpecLoc());
12439 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000012440 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012441
12442 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +000012443 return nullptr;
12444
John McCall11083da2009-09-16 22:47:08 +000012445 D->setAccess(AS_public);
12446 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000012447
John McCall48871652010-08-21 09:40:31 +000012448 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000012449}
12450
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000012451NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
12452 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000012453 const DeclSpec &DS = D.getDeclSpec();
12454
12455 assert(DS.isFriendSpecified());
12456 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12457
12458 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000012459 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000012460
12461 // C++ [class.friend]p1
12462 // A friend of a class is a function or class....
12463 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000012464 // It *doesn't* see through dependent types, which is correct
12465 // according to [temp.arg.type]p3:
12466 // If a declaration acquires a function type through a
12467 // type dependent on a template-parameter and this causes
12468 // a declaration that does not use the syntactic form of a
12469 // function declarator to have a function type, the program
12470 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012471 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000012472 Diag(Loc, diag::err_unexpected_friend);
12473
12474 // It might be worthwhile to try to recover by creating an
12475 // appropriate declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000012476 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012477 }
12478
12479 // C++ [namespace.memdef]p3
12480 // - If a friend declaration in a non-local class first declares a
12481 // class or function, the friend class or function is a member
12482 // of the innermost enclosing namespace.
12483 // - The name of the friend is not found by simple name lookup
12484 // until a matching declaration is provided in that namespace
12485 // scope (either before or after the class declaration granting
12486 // friendship).
12487 // - If a friend function is called, its name may be found by the
12488 // name lookup that considers functions from namespaces and
12489 // classes associated with the types of the function arguments.
12490 // - When looking for a prior declaration of a class or a function
12491 // declared as a friend, scopes outside the innermost enclosing
12492 // namespace scope are not considered.
12493
John McCallde3fd222010-10-12 23:13:28 +000012494 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012495 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
12496 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000012497 assert(Name);
12498
Douglas Gregor6c110f32010-12-16 01:14:37 +000012499 // Check for unexpanded parameter packs.
12500 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
12501 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
12502 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000012503 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000012504
John McCall07e91c02009-08-06 02:15:43 +000012505 // The context we found the declaration in, or in which we should
12506 // create the declaration.
12507 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000012508 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012509 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000012510 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000012511
Richard Smith114394f2013-08-09 04:35:01 +000012512 // There are five cases here.
12513 // - There's no scope specifier and we're in a local class. Only look
12514 // for functions declared in the immediately-enclosing block scope.
12515 // We recover from invalid scope qualifiers as if they just weren't there.
Craig Topperc3ec1492014-05-26 06:22:03 +000012516 FunctionDecl *FunctionContainingLocalClass = nullptr;
Richard Smith114394f2013-08-09 04:35:01 +000012517 if ((SS.isInvalid() || !SS.isSet()) &&
12518 (FunctionContainingLocalClass =
12519 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
12520 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000012521 // If a friend declaration appears in a local class and the name
12522 // specified is an unqualified name, a prior declaration is
12523 // looked up without considering scopes that are outside the
12524 // innermost enclosing non-class scope. For a friend function
12525 // declaration, if there is no prior declaration, the program is
12526 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000012527
12528 // Find the innermost enclosing non-class scope. This is the block
12529 // scope containing the local class definition (or for a nested class,
12530 // the outer local class).
12531 DCScope = S->getFnParent();
12532
12533 // Look up the function name in the scope.
12534 Previous.clear(LookupLocalFriendName);
12535 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
12536
12537 if (!Previous.empty()) {
12538 // All possible previous declarations must have the same context:
12539 // either they were declared at block scope or they are members of
12540 // one of the enclosing local classes.
12541 DC = Previous.getRepresentativeDecl()->getDeclContext();
12542 } else {
12543 // This is ill-formed, but provide the context that we would have
12544 // declared the function in, if we were permitted to, for error recovery.
12545 DC = FunctionContainingLocalClass;
12546 }
Richard Smith541b38b2013-09-20 01:15:31 +000012547 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000012548
12549 // C++ [class.friend]p6:
12550 // A function can be defined in a friend declaration of a class if and
12551 // only if the class is a non-local class (9.8), the function name is
12552 // unqualified, and the function has namespace scope.
12553 if (D.isFunctionDefinition()) {
12554 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12555 }
12556
12557 // - There's no scope specifier, in which case we just go to the
12558 // appropriate scope and look for a function or function template
12559 // there as appropriate.
12560 } else if (SS.isInvalid() || !SS.isSet()) {
12561 // C++11 [namespace.memdef]p3:
12562 // If the name in a friend declaration is neither qualified nor
12563 // a template-id and the declaration is a function or an
12564 // elaborated-type-specifier, the lookup to determine whether
12565 // the entity has been previously declared shall not consider
12566 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000012567 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000012568
John McCallf7cfb222010-10-13 05:45:15 +000012569 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000012570 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000012571
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012572 // Skip class contexts. If someone can cite chapter and verse
12573 // for this behavior, that would be nice --- it's what GCC and
12574 // EDG do, and it seems like a reasonable intent, but the spec
12575 // really only says that checks for unqualified existing
12576 // declarations should stop at the nearest enclosing namespace,
12577 // not that they should only consider the nearest enclosing
12578 // namespace.
12579 while (DC->isRecord())
12580 DC = DC->getParent();
12581
12582 DeclContext *LookupDC = DC;
12583 while (LookupDC->isTransparentContext())
12584 LookupDC = LookupDC->getParent();
12585
12586 while (true) {
12587 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000012588
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012589 if (!Previous.empty()) {
12590 DC = LookupDC;
12591 break;
John McCallf4776592010-10-14 22:22:28 +000012592 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012593
12594 if (isTemplateId) {
12595 if (isa<TranslationUnitDecl>(LookupDC)) break;
12596 } else {
12597 if (LookupDC->isFileContext()) break;
12598 }
12599 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000012600 }
12601
John McCallccbc0322010-10-13 06:22:15 +000012602 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000012603
John McCallde3fd222010-10-12 23:13:28 +000012604 // - There's a non-dependent scope specifier, in which case we
12605 // compute it and do a previous lookup there for a function
12606 // or function template.
12607 } else if (!SS.getScopeRep()->isDependent()) {
12608 DC = computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +000012609 if (!DC) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012610
Craig Topperc3ec1492014-05-26 06:22:03 +000012611 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012612
12613 LookupQualifiedName(Previous, DC);
12614
12615 // Ignore things found implicitly in the wrong scope.
12616 // TODO: better diagnostics for this case. Suggesting the right
12617 // qualified scope would be nice...
12618 LookupResult::Filter F = Previous.makeFilter();
12619 while (F.hasNext()) {
12620 NamedDecl *D = F.next();
12621 if (!DC->InEnclosingNamespaceSetOf(
12622 D->getDeclContext()->getRedeclContext()))
12623 F.erase();
12624 }
12625 F.done();
12626
12627 if (Previous.empty()) {
12628 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012629 Diag(Loc, diag::err_qualified_friend_not_found)
12630 << Name << TInfo->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +000012631 return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012632 }
12633
12634 // C++ [class.friend]p1: A friend of a class is a function or
12635 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000012636 if (DC->Equals(CurContext))
12637 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012638 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000012639 diag::warn_cxx98_compat_friend_is_member :
12640 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000012641
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012642 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012643 // C++ [class.friend]p6:
12644 // A function can be defined in a friend declaration of a class if and
12645 // only if the class is a non-local class (9.8), the function name is
12646 // unqualified, and the function has namespace scope.
12647 SemaDiagnosticBuilder DB
12648 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12649
12650 DB << SS.getScopeRep();
12651 if (DC->isFileContext())
12652 DB << FixItHint::CreateRemoval(SS.getRange());
12653 SS.clear();
12654 }
John McCallde3fd222010-10-12 23:13:28 +000012655
12656 // - There's a scope specifier that does not match any template
12657 // parameter lists, in which case we use some arbitrary context,
12658 // create a method or method template, and wait for instantiation.
12659 // - There's a scope specifier that does match some template
12660 // parameter lists, which we don't handle right now.
12661 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012662 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012663 // C++ [class.friend]p6:
12664 // A function can be defined in a friend declaration of a class if and
12665 // only if the class is a non-local class (9.8), the function name is
12666 // unqualified, and the function has namespace scope.
12667 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12668 << SS.getScopeRep();
12669 }
12670
John McCallde3fd222010-10-12 23:13:28 +000012671 DC = CurContext;
12672 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000012673 }
Douglas Gregor16e65612011-10-10 01:11:59 +000012674
John McCallf7cfb222010-10-13 05:45:15 +000012675 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000012676 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000012677 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
12678 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
12679 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000012680 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000012681 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
12682 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
Craig Topperc3ec1492014-05-26 06:22:03 +000012683 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012684 }
John McCall07e91c02009-08-06 02:15:43 +000012685 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012686
Douglas Gregordd847ba2011-11-03 16:37:14 +000012687 // FIXME: This is an egregious hack to cope with cases where the scope stack
12688 // does not contain the declaration context, i.e., in an out-of-line
12689 // definition of a class.
12690 Scope FakeDCScope(S, Scope::DeclScope, Diags);
12691 if (!DCScope) {
12692 FakeDCScope.setEntity(DC);
12693 DCScope = &FakeDCScope;
12694 }
Richard Smith114394f2013-08-09 04:35:01 +000012695
Francois Pichet00c7e6c2011-08-14 03:52:19 +000012696 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012697 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012698 TemplateParams, AddToScope);
Craig Topperc3ec1492014-05-26 06:22:03 +000012699 if (!ND) return nullptr;
John McCall759e32b2009-08-31 22:39:49 +000012700
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012701 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000012702
Richard Smith114394f2013-08-09 04:35:01 +000012703 // If we performed typo correction, we might have added a scope specifier
12704 // and changed the decl context.
12705 DC = ND->getDeclContext();
12706
John McCall759e32b2009-08-31 22:39:49 +000012707 // Add the function declaration to the appropriate lookup tables,
12708 // adjusting the redeclarations list as necessary. We don't
12709 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000012710 //
John McCall759e32b2009-08-31 22:39:49 +000012711 // Also update the scope-based lookup if the target context's
12712 // lookup context is in lexical scope.
12713 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000012714 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000012715 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000012716 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012717 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000012718 }
John McCallaa74a0c2009-08-28 07:59:38 +000012719
12720 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012721 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000012722 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000012723 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000012724 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000012725
John McCalla0a96892012-08-10 03:15:35 +000012726 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000012727 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000012728 } else {
12729 if (DC->isRecord()) CheckFriendAccess(ND);
12730
John McCall2c2eb122010-10-16 06:59:13 +000012731 FunctionDecl *FD;
12732 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12733 FD = FTD->getTemplatedDecl();
12734 else
12735 FD = cast<FunctionDecl>(ND);
12736
David Majnemer502b0ed2013-06-25 23:09:30 +000012737 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12738 // default argument expression, that declaration shall be a definition
12739 // and shall be the only declaration of the function or function
12740 // template in the translation unit.
12741 if (functionDeclHasDefaultArgument(FD)) {
12742 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12743 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12744 Diag(OldFD->getLocation(), diag::note_previous_declaration);
12745 } else if (!D.isFunctionDefinition())
12746 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12747 }
12748
John McCall2c2eb122010-10-16 06:59:13 +000012749 // Mark templated-scope function declarations as unsupported.
Richard Smith04b35e92014-09-29 05:57:29 +000012750 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
12751 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
12752 << SS.getScopeRep() << SS.getRange()
12753 << cast<CXXRecordDecl>(CurContext);
John McCall2c2eb122010-10-16 06:59:13 +000012754 FrD->setUnsupportedFriend(true);
Richard Smith04b35e92014-09-29 05:57:29 +000012755 }
John McCall2c2eb122010-10-16 06:59:13 +000012756 }
John McCallde3fd222010-10-12 23:13:28 +000012757
John McCall48871652010-08-21 09:40:31 +000012758 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000012759}
12760
John McCall48871652010-08-21 09:40:31 +000012761void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12762 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000012763
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012764 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000012765 if (!Fn) {
12766 Diag(DelLoc, diag::err_deleted_non_function);
12767 return;
12768 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012769
Douglas Gregorec9fd132012-01-14 16:38:05 +000012770 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000012771 // Don't consider the implicit declaration we generate for explicit
12772 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000012773 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12774 Prev->getPreviousDecl()) &&
12775 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000012776 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000012777 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12778 Prev->isImplicit() ? diag::note_previous_implicit_declaration
12779 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000012780 }
Sebastian Redlf769df52009-03-24 22:27:57 +000012781 // If the declaration wasn't the first, we delete the function anyway for
12782 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000012783 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000012784 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012785
Nico Rieck9de0a572014-05-29 16:51:19 +000012786 // dllimport/dllexport cannot be deleted.
12787 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12788 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12789 Fn->setInvalidDecl();
12790 }
12791
Richard Smithb4d2a152013-04-02 19:38:47 +000012792 if (Fn->isDeleted())
12793 return;
12794
12795 // See if we're deleting a function which is already known to override a
12796 // non-deleted virtual function.
12797 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12798 bool IssuedDiagnostic = false;
12799 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12800 E = MD->end_overridden_methods();
12801 I != E; ++I) {
12802 if (!(*MD->begin_overridden_methods())->isDeleted()) {
12803 if (!IssuedDiagnostic) {
12804 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12805 IssuedDiagnostic = true;
12806 }
12807 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12808 }
12809 }
12810 }
12811
Richard Smithb63b6ee2014-01-22 01:43:19 +000012812 // C++11 [basic.start.main]p3:
12813 // A program that defines main as deleted [...] is ill-formed.
12814 if (Fn->isMain())
12815 Diag(DelLoc, diag::err_deleted_main);
12816
Alexis Hunt4a8ea102011-05-06 20:44:56 +000012817 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000012818}
Sebastian Redl4c018662009-04-27 21:33:24 +000012819
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012820void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012821 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012822
12823 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000012824 if (MD->getParent()->isDependentType()) {
12825 MD->setDefaulted();
12826 MD->setExplicitlyDefaulted();
12827 return;
12828 }
12829
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012830 CXXSpecialMember Member = getSpecialMember(MD);
12831 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000012832 if (!MD->isInvalidDecl())
12833 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012834 return;
12835 }
12836
12837 MD->setDefaulted();
12838 MD->setExplicitlyDefaulted();
12839
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012840 // If this definition appears within the record, do the checking when
12841 // the record is complete.
12842 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000012843 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012844 // Find the uninstantiated declaration that actually had the '= default'
12845 // on it.
Richard Smith802c4b72012-08-23 06:16:52 +000012846 Pattern->isDefined(Primary);
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012847
Richard Smith3901dfe2013-03-27 00:22:47 +000012848 // If the method was defaulted on its first declaration, we will have
12849 // already performed the checking in CheckCompletedCXXClass. Such a
12850 // declaration doesn't trigger an implicit definition.
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012851 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012852 return;
12853
Richard Smithd3b5c9082012-07-27 04:22:15 +000012854 CheckExplicitlyDefaultedSpecialMember(MD);
12855
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012856 if (MD->isInvalidDecl())
12857 return;
12858
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012859 switch (Member) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012860 case CXXDefaultConstructor:
12861 DefineImplicitDefaultConstructor(DefaultLoc,
12862 cast<CXXConstructorDecl>(MD));
Alexis Hunt913820d2011-05-13 06:10:58 +000012863 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012864 case CXXCopyConstructor:
12865 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012866 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012867 case CXXCopyAssignment:
12868 DefineImplicitCopyAssignment(DefaultLoc, MD);
Alexis Huntc9a55732011-05-14 05:23:28 +000012869 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012870 case CXXDestructor:
12871 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Alexis Huntf91729462011-05-12 22:46:25 +000012872 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012873 case CXXMoveConstructor:
12874 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt119c10e2011-05-25 23:16:36 +000012875 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012876 case CXXMoveAssignment:
12877 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012878 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000012879 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000012880 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012881 }
12882 } else {
12883 Diag(DefaultLoc, diag::err_default_special_members);
12884 }
12885}
12886
Sebastian Redl4c018662009-04-27 21:33:24 +000012887static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
Benjamin Kramer642f1732015-07-02 21:03:14 +000012888 for (Stmt *SubStmt : S->children()) {
Sebastian Redl4c018662009-04-27 21:33:24 +000012889 if (!SubStmt)
12890 continue;
12891 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012892 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000012893 diag::err_return_in_constructor_handler);
12894 if (!isa<Expr>(SubStmt))
12895 SearchForReturnInStmt(Self, SubStmt);
12896 }
12897}
12898
12899void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12900 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12901 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12902 SearchForReturnInStmt(*this, Handler);
12903 }
12904}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012905
David Blaikie68f71a32013-01-18 23:03:15 +000012906bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000012907 const CXXMethodDecl *Old) {
12908 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12909 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12910
12911 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12912
12913 // If the calling conventions match, everything is fine
12914 if (NewCC == OldCC)
12915 return false;
12916
Hans Wennborg2545efe2013-12-11 17:42:11 +000012917 // If the calling conventions mismatch because the new function is static,
12918 // suppress the calling convention mismatch error; the error about static
12919 // function override (err_static_overrides_virtual from
12920 // Sema::CheckFunctionDeclaration) is more clear.
12921 if (New->getStorageClass() == SC_Static)
12922 return false;
12923
Reid Kleckner78af0702013-08-27 23:08:25 +000012924 Diag(New->getLocation(),
12925 diag::err_conflicting_overriding_cc_attributes)
12926 << New->getDeclName() << New->getType() << Old->getType();
12927 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12928 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000012929}
12930
Mike Stump11289f42009-09-09 15:08:12 +000012931bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012932 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000012933 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12934 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012935
Chandler Carruth284bb2e2010-02-15 11:53:20 +000012936 if (Context.hasSameType(NewTy, OldTy) ||
12937 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012938 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012939
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012940 // Check if the return types are covariant
12941 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000012942
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012943 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012944 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12945 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012946 NewClassTy = NewPT->getPointeeType();
12947 OldClassTy = OldPT->getPointeeType();
12948 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012949 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12950 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12951 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12952 NewClassTy = NewRT->getPointeeType();
12953 OldClassTy = OldRT->getPointeeType();
12954 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012955 }
12956 }
Mike Stump11289f42009-09-09 15:08:12 +000012957
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012958 // The return types aren't either both pointers or references to a class type.
12959 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000012960 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012961 diag::err_different_return_type_for_overriding_virtual_function)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012962 << New->getDeclName() << NewTy << OldTy
12963 << New->getReturnTypeSourceRange();
12964 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12965 << Old->getReturnTypeSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000012966
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012967 return true;
12968 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012969
Anders Carlssone60365b2009-12-31 18:34:24 +000012970 // C++ [class.virtual]p6:
12971 // If the return type of D::f differs from the return type of B::f, the
12972 // class type in the return type of D::f shall be complete at the point of
12973 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012974 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12975 if (!RT->isBeingDefined() &&
12976 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012977 diag::err_covariant_return_incomplete,
12978 New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000012979 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012980 }
Anders Carlssone60365b2009-12-31 18:34:24 +000012981
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000012982 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012983 // Check if the new class derives from the old class.
12984 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
Alp Tokerd0787eb2014-07-02 01:47:15 +000012985 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
12986 << New->getDeclName() << NewTy << OldTy
12987 << New->getReturnTypeSourceRange();
12988 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12989 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012990 return true;
12991 }
Mike Stump11289f42009-09-09 15:08:12 +000012992
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012993 // Check if we the conversion from derived to base is valid.
Alp Tokerd0787eb2014-07-02 01:47:15 +000012994 if (CheckDerivedToBaseConversion(
12995 NewClassTy, OldClassTy,
12996 diag::err_covariant_return_inaccessible_base,
12997 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12998 New->getLocation(), New->getReturnTypeSourceRange(),
12999 New->getDeclName(), nullptr)) {
John McCallc1465822011-02-14 07:13:47 +000013000 // FIXME: this note won't trigger for delayed access control
13001 // diagnostics, and it's impossible to get an undelayed error
13002 // here from access control during the original parse because
13003 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Alp Tokerd0787eb2014-07-02 01:47:15 +000013004 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13005 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013006 return true;
13007 }
13008 }
Mike Stump11289f42009-09-09 15:08:12 +000013009
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013010 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000013011 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013012 Diag(New->getLocation(),
13013 diag::err_covariant_return_type_different_qualifications)
Alp Tokerd0787eb2014-07-02 01:47:15 +000013014 << New->getDeclName() << NewTy << OldTy
13015 << New->getReturnTypeSourceRange();
13016 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13017 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013018 return true;
13019 };
Mike Stump11289f42009-09-09 15:08:12 +000013020
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013021
13022 // The new class type must have the same or less qualifiers as the old type.
13023 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
13024 Diag(New->getLocation(),
13025 diag::err_covariant_return_type_class_type_more_qualified)
Alp Tokerd0787eb2014-07-02 01:47:15 +000013026 << New->getDeclName() << NewTy << OldTy
13027 << New->getReturnTypeSourceRange();
13028 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13029 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013030 return true;
13031 };
Mike Stump11289f42009-09-09 15:08:12 +000013032
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013033 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000013034}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013035
Douglas Gregor21920e372009-12-01 17:24:26 +000013036/// \brief Mark the given method pure.
13037///
13038/// \param Method the method to be marked pure.
13039///
13040/// \param InitRange the source range that covers the "0" initializer.
13041bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000013042 SourceLocation EndLoc = InitRange.getEnd();
13043 if (EndLoc.isValid())
13044 Method->setRangeEnd(EndLoc);
13045
Douglas Gregor21920e372009-12-01 17:24:26 +000013046 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
13047 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000013048 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000013049 }
Douglas Gregor21920e372009-12-01 17:24:26 +000013050
13051 if (!Method->isInvalidDecl())
13052 Diag(Method->getLocation(), diag::err_non_virtual_pure)
13053 << Method->getDeclName() << InitRange;
13054 return true;
13055}
13056
Richard Smith9ba0fec2015-06-30 01:28:56 +000013057void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
13058 if (D->getFriendObjectKind())
13059 Diag(D->getLocation(), diag::err_pure_friend);
13060 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
13061 CheckPureMethod(M, ZeroLoc);
13062 else
13063 Diag(D->getLocation(), diag::err_illegal_initializer);
13064}
13065
Douglas Gregor926410d2012-02-21 02:22:07 +000013066/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013067static bool isStaticDataMember(const Decl *D) {
13068 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
13069 return Var->isStaticDataMember();
13070
13071 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000013072}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013073
John McCall1f4ee7b2009-12-19 09:28:58 +000013074/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
13075/// an initializer for the out-of-line declaration 'Dcl'. The scope
13076/// is a fresh scope pushed for just this purpose.
13077///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013078/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
13079/// static data member of class X, names should be looked up in the scope of
13080/// class X.
John McCall48871652010-08-21 09:40:31 +000013081void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013082 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000013083 if (!D || D->isInvalidDecl())
13084 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013085
Richard Smitha2302242013-12-05 07:51:02 +000013086 // We will always have a nested name specifier here, but this declaration
13087 // might not be out of line if the specifier names the current namespace:
13088 // extern int n;
13089 // int ::n = 0;
13090 if (D->isOutOfLine())
13091 EnterDeclaratorContext(S, D->getDeclContext());
13092
Douglas Gregor926410d2012-02-21 02:22:07 +000013093 // If we are parsing the initializer for a static data member, push a
13094 // new expression evaluation context that is associated with this static
13095 // data member.
13096 if (isStaticDataMember(D))
13097 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013098}
13099
13100/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000013101/// initializer for the out-of-line declaration 'D'.
13102void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013103 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000013104 if (!D || D->isInvalidDecl())
13105 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013106
Douglas Gregor926410d2012-02-21 02:22:07 +000013107 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000013108 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000013109
Richard Smitha2302242013-12-05 07:51:02 +000013110 if (D->isOutOfLine())
13111 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000013112}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013113
13114/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
13115/// C++ if/switch/while/for statement.
13116/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000013117DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013118 // C++ 6.4p2:
13119 // The declarator shall not specify a function or an array.
13120 // The type-specifier-seq shall not contain typedef and shall not declare a
13121 // new class or enumeration.
13122 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
13123 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000013124
13125 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000013126 if (!Dcl)
13127 return true;
13128
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000013129 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
13130 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013131 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000013132 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013133 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013134
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000013135 return Dcl;
13136}
Anders Carlssonf98849e2009-12-02 17:15:43 +000013137
Douglas Gregor4daf6a32011-07-28 19:11:31 +000013138void Sema::LoadExternalVTableUses() {
13139 if (!ExternalSource)
13140 return;
13141
13142 SmallVector<ExternalVTableUse, 4> VTables;
13143 ExternalSource->ReadUsedVTables(VTables);
13144 SmallVector<VTableUse, 4> NewUses;
13145 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
13146 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
13147 = VTablesUsed.find(VTables[I].Record);
13148 // Even if a definition wasn't required before, it may be required now.
13149 if (Pos != VTablesUsed.end()) {
13150 if (!Pos->second && VTables[I].DefinitionRequired)
13151 Pos->second = true;
13152 continue;
13153 }
13154
13155 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
13156 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
13157 }
13158
13159 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
13160}
13161
Douglas Gregor88d292c2010-05-13 16:44:06 +000013162void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
13163 bool DefinitionRequired) {
13164 // Ignore any vtable uses in unevaluated operands or for classes that do
13165 // not have a vtable.
13166 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000013167 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000013168 return;
13169
Douglas Gregor88d292c2010-05-13 16:44:06 +000013170 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000013171 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013172 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13173 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
13174 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
13175 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000013176 // If we already had an entry, check to see if we are promoting this vtable
Nico Weberf1cebf02015-01-06 23:54:59 +000013177 // to require a definition. If so, we need to reappend to the VTableUses
Daniel Dunbar53217762010-05-25 00:33:13 +000013178 // list, since we may have already processed the first entry.
13179 if (DefinitionRequired && !Pos.first->second) {
13180 Pos.first->second = true;
13181 } else {
13182 // Otherwise, we can early exit.
13183 return;
13184 }
Hans Wennborg3d791542014-02-24 15:58:24 +000013185 } else {
13186 // The Microsoft ABI requires that we perform the destructor body
13187 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
13188 // the deleting destructor is emitted with the vtable, not with the
13189 // destructor definition as in the Itanium ABI.
13190 // If it has a definition, we do the check at that point instead.
13191 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13192 Class->hasUserDeclaredDestructor() &&
13193 !Class->getDestructor()->isDefined() &&
13194 !Class->getDestructor()->isDeleted()) {
Reid Kleckner67130862014-06-12 22:39:12 +000013195 CXXDestructorDecl *DD = Class->getDestructor();
13196 ContextRAII SavedContext(*this, DD);
13197 CheckDestructor(DD);
Hans Wennborg3d791542014-02-24 15:58:24 +000013198 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000013199 }
13200
13201 // Local classes need to have their virtual members marked
13202 // immediately. For all other classes, we mark their virtual members
13203 // at the end of the translation unit.
13204 if (Class->isLocalClass())
13205 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000013206 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000013207 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000013208}
13209
Douglas Gregor88d292c2010-05-13 16:44:06 +000013210bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000013211 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013212 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000013213 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000013214
Douglas Gregor88d292c2010-05-13 16:44:06 +000013215 // Note: The VTableUses vector could grow as a result of marking
13216 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000013217 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000013218 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000013219 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013220 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000013221 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013222 if (!Class)
13223 continue;
13224
13225 SourceLocation Loc = VTableUses[I].second;
13226
Richard Smithd3b5c9082012-07-27 04:22:15 +000013227 bool DefineVTable = true;
13228
Douglas Gregor88d292c2010-05-13 16:44:06 +000013229 // If this class has a key function, but that key function is
13230 // defined in another translation unit, we don't need to emit the
13231 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000013232 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000013233 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000013234 // The key function is in another translation unit.
13235 DefineVTable = false;
13236 TemplateSpecializationKind TSK =
13237 KeyFunction->getTemplateSpecializationKind();
13238 assert(TSK != TSK_ExplicitInstantiationDefinition &&
13239 TSK != TSK_ImplicitInstantiation &&
13240 "Instantiations don't have key functions");
13241 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013242 } else if (!KeyFunction) {
13243 // If we have a class with no key function that is the subject
13244 // of an explicit instantiation declaration, suppress the
13245 // vtable; it will live with the explicit instantiation
13246 // definition.
13247 bool IsExplicitInstantiationDeclaration
13248 = Class->getTemplateSpecializationKind()
13249 == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000013250 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000013251 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000013252 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000013253 if (TSK == TSK_ExplicitInstantiationDeclaration)
13254 IsExplicitInstantiationDeclaration = true;
13255 else if (TSK == TSK_ExplicitInstantiationDefinition) {
13256 IsExplicitInstantiationDeclaration = false;
13257 break;
13258 }
13259 }
13260
13261 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000013262 DefineVTable = false;
13263 }
13264
13265 // The exception specifications for all virtual members may be needed even
13266 // if we are not providing an authoritative form of the vtable in this TU.
13267 // We may choose to emit it available_externally anyway.
13268 if (!DefineVTable) {
13269 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
13270 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013271 }
13272
13273 // Mark all of the virtual members of this class as referenced, so
13274 // that we can build a vtable. Then, tell the AST consumer that a
13275 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000013276 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013277 MarkVirtualMembersReferenced(Loc, Class);
13278 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
Nico Weberb6a5d052015-01-15 04:07:35 +000013279 if (VTablesUsed[Canonical])
13280 Consumer.HandleVTable(Class);
Douglas Gregor88d292c2010-05-13 16:44:06 +000013281
13282 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000013283 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000013284 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013285 const FunctionDecl *KeyFunctionDef = nullptr;
Douglas Gregor34bc6e52011-09-23 19:04:03 +000013286 if (!KeyFunction ||
13287 (KeyFunction->hasBody(KeyFunctionDef) &&
13288 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000013289 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
13290 TSK_ExplicitInstantiationDefinition
13291 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
13292 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013293 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000013294 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000013295 VTableUses.clear();
13296
Douglas Gregor97509692011-04-22 22:25:37 +000013297 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000013298}
Anders Carlsson82fccd02009-12-07 08:24:59 +000013299
Richard Smithd3b5c9082012-07-27 04:22:15 +000013300void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
13301 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000013302 for (const auto *I : RD->methods())
13303 if (I->isVirtual() && !I->isPure())
13304 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000013305}
13306
Rafael Espindola5b334082010-03-26 00:36:59 +000013307void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
13308 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000013309 // Mark all functions which will appear in RD's vtable as used.
13310 CXXFinalOverriderMap FinalOverriders;
13311 RD->getFinalOverriders(FinalOverriders);
13312 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
13313 E = FinalOverriders.end();
13314 I != E; ++I) {
13315 for (OverridingMethods::const_iterator OI = I->second.begin(),
13316 OE = I->second.end();
13317 OI != OE; ++OI) {
13318 assert(OI->second.size() > 0 && "no final overrider");
13319 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000013320
Richard Smith4ff9ff92012-07-07 06:59:51 +000013321 // C++ [basic.def.odr]p2:
13322 // [...] A virtual member function is used if it is not pure. [...]
13323 if (!Overrider->isPure())
13324 MarkFunctionReferenced(Loc, Overrider);
13325 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000013326 }
Rafael Espindola5b334082010-03-26 00:36:59 +000013327
13328 // Only classes that have virtual bases need a VTT.
13329 if (RD->getNumVBases() == 0)
13330 return;
13331
Aaron Ballman574705e2014-03-13 15:41:46 +000013332 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000013333 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000013334 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000013335 if (Base->getNumVBases() == 0)
13336 continue;
13337 MarkVirtualMembersReferenced(Loc, Base);
13338 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000013339}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013340
13341/// SetIvarInitializers - This routine builds initialization ASTs for the
13342/// Objective-C implementation whose ivars need be initialized.
13343void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000013344 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013345 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000013346 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000013347 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013348 CollectIvarsToConstructOrDestruct(OID, ivars);
13349 if (ivars.empty())
13350 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000013351 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013352 for (unsigned i = 0; i < ivars.size(); i++) {
13353 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000013354 if (Field->isInvalidDecl())
13355 continue;
13356
Alexis Hunt1d792652011-01-08 20:30:50 +000013357 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013358 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
13359 InitializationKind InitKind =
13360 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000013361
13362 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
13363 ExprResult MemberInit =
13364 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000013365 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013366 // Note, MemberInit could actually come back empty if no initialization
13367 // is required (e.g., because it would call a trivial default constructor)
13368 if (!MemberInit.get() || MemberInit.isInvalid())
13369 continue;
John McCallacf0ee52010-10-08 02:01:28 +000013370
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013371 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000013372 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
13373 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013374 MemberInit.getAs<Expr>(),
Alexis Hunt1d792652011-01-08 20:30:50 +000013375 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013376 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000013377
13378 // Be sure that the destructor is accessible and is marked as referenced.
Nico Weberaa0117c2014-11-12 03:44:43 +000013379 if (const RecordType *RecordTy =
13380 Context.getBaseElementType(Field->getType())
13381 ->getAs<RecordType>()) {
13382 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000013383 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000013384 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000013385 CheckDestructorAccess(Field->getLocation(), Destructor,
13386 PDiag(diag::err_access_dtor_ivar)
13387 << Context.getBaseElementType(Field->getType()));
13388 }
13389 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013390 }
13391 ObjCImplementation->setIvarInitializers(Context,
13392 AllToInit.data(), AllToInit.size());
13393 }
13394}
Alexis Hunt6118d662011-05-04 05:57:24 +000013395
Alexis Hunt27a761d2011-05-04 23:29:54 +000013396static
13397void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
13398 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
13399 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
13400 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
13401 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000013402 if (Ctor->isInvalidDecl())
13403 return;
13404
Richard Smith802c4b72012-08-23 06:16:52 +000013405 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
13406
13407 // Target may not be determinable yet, for instance if this is a dependent
13408 // call in an uninstantiated template.
13409 if (Target) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013410 const FunctionDecl *FNTarget = nullptr;
Richard Smith802c4b72012-08-23 06:16:52 +000013411 (void)Target->hasBody(FNTarget);
13412 Target = const_cast<CXXConstructorDecl*>(
13413 cast_or_null<CXXConstructorDecl>(FNTarget));
13414 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000013415
13416 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
13417 // Avoid dereferencing a null pointer here.
Craig Topperc3ec1492014-05-26 06:22:03 +000013418 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000013419
David Blaikie82e95a32014-11-19 07:49:47 +000013420 if (!Current.insert(Canonical).second)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013421 return;
13422
13423 // We know that beyond here, we aren't chaining into a cycle.
13424 if (!Target || !Target->isDelegatingConstructor() ||
13425 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013426 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000013427 Current.clear();
13428 // We've hit a cycle.
13429 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
13430 Current.count(TCanonical)) {
13431 // If we haven't diagnosed this cycle yet, do so now.
13432 if (!Invalid.count(TCanonical)) {
13433 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000013434 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013435 << Ctor;
13436
Richard Smith802c4b72012-08-23 06:16:52 +000013437 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000013438 if (TCanonical != Canonical)
13439 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
13440
13441 CXXConstructorDecl *C = Target;
13442 while (C->getCanonicalDecl() != Canonical) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013443 const FunctionDecl *FNTarget = nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000013444 (void)C->getTargetConstructor()->hasBody(FNTarget);
13445 assert(FNTarget && "Ctor cycle through bodiless function");
13446
Richard Smith802c4b72012-08-23 06:16:52 +000013447 C = const_cast<CXXConstructorDecl*>(
13448 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000013449 S.Diag(C->getLocation(), diag::note_which_delegates_to);
13450 }
13451 }
13452
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013453 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000013454 Current.clear();
13455 } else {
13456 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
13457 }
13458}
13459
13460
Alexis Hunt6118d662011-05-04 05:57:24 +000013461void Sema::CheckDelegatingCtorCycles() {
13462 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
13463
Douglas Gregorbae31202011-07-27 21:57:17 +000013464 for (DelegatingCtorDeclsType::iterator
13465 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000013466 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000013467 I != E; ++I)
13468 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000013469
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013470 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
13471 CE = Invalid.end();
13472 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013473 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000013474}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000013475
Douglas Gregor3024f072012-04-16 07:05:22 +000013476namespace {
13477 /// \brief AST visitor that finds references to the 'this' expression.
13478 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
13479 Sema &S;
13480
13481 public:
13482 explicit FindCXXThisExpr(Sema &S) : S(S) { }
13483
13484 bool VisitCXXThisExpr(CXXThisExpr *E) {
13485 S.Diag(E->getLocation(), diag::err_this_static_member_func)
13486 << E->isImplicit();
13487 return false;
13488 }
13489 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000013490}
Douglas Gregor3024f072012-04-16 07:05:22 +000013491
13492bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
13493 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13494 if (!TSInfo)
13495 return false;
13496
13497 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000013498 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000013499 if (!ProtoTL)
13500 return false;
13501
13502 // C++11 [expr.prim.general]p3:
13503 // [The expression this] shall not appear before the optional
13504 // cv-qualifier-seq and it shall not appear within the declaration of a
13505 // static member function (although its type and value category are defined
13506 // within a static member function as they are within a non-static member
13507 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000013508 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000013509 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000013510 FindCXXThisExpr Finder(*this);
13511
13512 // If the return type came after the cv-qualifier-seq, check it now.
13513 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000013514 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000013515 return true;
13516
13517 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000013518 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
13519 return true;
13520
13521 return checkThisInStaticMemberFunctionAttributes(Method);
13522}
13523
13524bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
13525 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13526 if (!TSInfo)
13527 return false;
13528
13529 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000013530 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000013531 if (!ProtoTL)
13532 return false;
13533
David Blaikie6adc78e2013-02-18 22:06:02 +000013534 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000013535 FindCXXThisExpr Finder(*this);
13536
Douglas Gregor3024f072012-04-16 07:05:22 +000013537 switch (Proto->getExceptionSpecType()) {
Richard Smith0b3a4622014-11-13 20:01:57 +000013538 case EST_Unparsed:
Richard Smithf623c962012-04-17 00:58:00 +000013539 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000013540 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000013541 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000013542 case EST_DynamicNone:
13543 case EST_MSAny:
13544 case EST_None:
13545 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000013546
Douglas Gregor3024f072012-04-16 07:05:22 +000013547 case EST_ComputedNoexcept:
13548 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
13549 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000013550
Douglas Gregor3024f072012-04-16 07:05:22 +000013551 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000013552 for (const auto &E : Proto->exceptions()) {
13553 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000013554 return true;
13555 }
13556 break;
13557 }
Douglas Gregor433e0532012-04-16 18:27:27 +000013558
13559 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000013560}
13561
13562bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
13563 FindCXXThisExpr Finder(*this);
13564
13565 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013566 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013567 // FIXME: This should be emitted by tblgen.
Craig Topperc3ec1492014-05-26 06:22:03 +000013568 Expr *Arg = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +000013569 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013570 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013571 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013572 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013573 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013574 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013575 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013576 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013577 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013578 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013579 Arg = ETLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000013580 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013581 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013582 Arg = STLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000013583 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
Aaron Ballman18d85ae2014-03-20 16:02:49 +000013584 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013585 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013586 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013587 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013588 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013589 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013590 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013591 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013592 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013593 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013594 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013595 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000013596
13597 if (Arg && !Finder.TraverseStmt(Arg))
13598 return true;
13599
13600 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13601 if (!Finder.TraverseStmt(Args[I]))
13602 return true;
13603 }
13604 }
13605
13606 return false;
13607}
13608
Richard Smith2e321552014-11-12 02:00:47 +000013609void Sema::checkExceptionSpecification(
13610 bool IsTopLevel, ExceptionSpecificationType EST,
13611 ArrayRef<ParsedType> DynamicExceptions,
13612 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
13613 SmallVectorImpl<QualType> &Exceptions,
13614 FunctionProtoType::ExceptionSpecInfo &ESI) {
Douglas Gregor433e0532012-04-16 18:27:27 +000013615 Exceptions.clear();
Richard Smith8acb4282014-07-31 21:57:55 +000013616 ESI.Type = EST;
Douglas Gregor433e0532012-04-16 18:27:27 +000013617 if (EST == EST_Dynamic) {
13618 Exceptions.reserve(DynamicExceptions.size());
13619 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13620 // FIXME: Preserve type source info.
13621 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13622
Richard Smith2e321552014-11-12 02:00:47 +000013623 if (IsTopLevel) {
13624 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13625 collectUnexpandedParameterPacks(ET, Unexpanded);
13626 if (!Unexpanded.empty()) {
13627 DiagnoseUnexpandedParameterPacks(
13628 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
13629 Unexpanded);
13630 continue;
13631 }
Douglas Gregor433e0532012-04-16 18:27:27 +000013632 }
13633
13634 // Check that the type is valid for an exception spec, and
13635 // drop it if not.
13636 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13637 Exceptions.push_back(ET);
13638 }
Richard Smith8acb4282014-07-31 21:57:55 +000013639 ESI.Exceptions = Exceptions;
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 (EST == EST_ComputedNoexcept) {
13644 // If an error occurred, there's no expression here.
13645 if (NoexceptExpr) {
13646 assert((NoexceptExpr->isTypeDependent() ||
13647 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13648 Context.BoolTy) &&
13649 "Parser should have made sure that the expression is boolean");
Richard Smith2e321552014-11-12 02:00:47 +000013650 if (IsTopLevel && NoexceptExpr &&
13651 DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
Richard Smith8acb4282014-07-31 21:57:55 +000013652 ESI.Type = EST_BasicNoexcept;
Douglas Gregor433e0532012-04-16 18:27:27 +000013653 return;
13654 }
Richard Smith8acb4282014-07-31 21:57:55 +000013655
Douglas Gregor433e0532012-04-16 18:27:27 +000013656 if (!NoexceptExpr->isValueDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +000013657 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
Douglas Gregore2b37442012-05-04 22:38:52 +000013658 diag::err_noexcept_needs_constant_expression,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013659 /*AllowFold*/ false).get();
Richard Smith8acb4282014-07-31 21:57:55 +000013660 ESI.NoexceptExpr = NoexceptExpr;
Douglas Gregor433e0532012-04-16 18:27:27 +000013661 }
13662 return;
13663 }
13664}
13665
Richard Smith0b3a4622014-11-13 20:01:57 +000013666void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
13667 ExceptionSpecificationType EST,
13668 SourceRange SpecificationRange,
13669 ArrayRef<ParsedType> DynamicExceptions,
13670 ArrayRef<SourceRange> DynamicExceptionRanges,
13671 Expr *NoexceptExpr) {
13672 if (!MethodD)
13673 return;
13674
13675 // Dig out the method we're referring to.
13676 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
13677 MethodD = FunTmpl->getTemplatedDecl();
13678
13679 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
13680 if (!Method)
13681 return;
13682
13683 // Check the exception specification.
13684 llvm::SmallVector<QualType, 4> Exceptions;
13685 FunctionProtoType::ExceptionSpecInfo ESI;
13686 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
13687 DynamicExceptionRanges, NoexceptExpr, Exceptions,
13688 ESI);
13689
13690 // Update the exception specification on the function type.
13691 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
13692
13693 if (Method->isStatic())
13694 checkThisInStaticMemberFunctionExceptionSpec(Method);
13695
13696 if (Method->isVirtual()) {
13697 // Check overrides, which we previously had to delay.
13698 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
13699 OEnd = Method->end_overridden_methods();
13700 O != OEnd; ++O)
13701 CheckOverridingFunctionExceptionSpec(Method, *O);
13702 }
13703}
13704
John McCall5e77d762013-04-16 07:28:30 +000013705/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13706///
13707MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13708 SourceLocation DeclStart,
13709 Declarator &D, Expr *BitWidth,
13710 InClassInitStyle InitStyle,
13711 AccessSpecifier AS,
13712 AttributeList *MSPropertyAttr) {
13713 IdentifierInfo *II = D.getIdentifier();
13714 if (!II) {
13715 Diag(DeclStart, diag::err_anonymous_property);
Craig Topperc3ec1492014-05-26 06:22:03 +000013716 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013717 }
13718 SourceLocation Loc = D.getIdentifierLoc();
13719
13720 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13721 QualType T = TInfo->getType();
13722 if (getLangOpts().CPlusPlus) {
13723 CheckExtraCXXDefaultArguments(D);
13724
13725 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13726 UPPC_DataMemberType)) {
13727 D.setInvalidType();
13728 T = Context.IntTy;
13729 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13730 }
13731 }
13732
13733 DiagnoseFunctionSpecifiers(D.getDeclSpec());
13734
13735 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13736 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13737 diag::err_invalid_thread)
13738 << DeclSpec::getSpecifierName(TSCS);
13739
13740 // Check to see if this name was declared as a member previously
Craig Topperc3ec1492014-05-26 06:22:03 +000013741 NamedDecl *PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013742 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13743 LookupName(Previous, S);
13744 switch (Previous.getResultKind()) {
13745 case LookupResult::Found:
13746 case LookupResult::FoundUnresolvedValue:
13747 PrevDecl = Previous.getAsSingle<NamedDecl>();
13748 break;
13749
13750 case LookupResult::FoundOverloaded:
13751 PrevDecl = Previous.getRepresentativeDecl();
13752 break;
13753
13754 case LookupResult::NotFound:
13755 case LookupResult::NotFoundInCurrentInstantiation:
13756 case LookupResult::Ambiguous:
13757 break;
13758 }
13759
13760 if (PrevDecl && PrevDecl->isTemplateParameter()) {
13761 // Maybe we will complain about the shadowed template parameter.
13762 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13763 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000013764 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013765 }
13766
13767 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Craig Topperc3ec1492014-05-26 06:22:03 +000013768 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013769
13770 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000013771 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000013772 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13773 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000013774 ProcessDeclAttributes(TUScope, NewPD, D);
13775 NewPD->setAccess(AS);
13776
13777 if (NewPD->isInvalidDecl())
13778 Record->setInvalidDecl();
13779
13780 if (D.getDeclSpec().isModulePrivateSpecified())
13781 NewPD->setModulePrivate();
13782
13783 if (NewPD->isInvalidDecl() && PrevDecl) {
13784 // Don't introduce NewFD into scope; there's already something
13785 // with the same name in the same scope.
13786 } else if (II) {
13787 PushOnScopeChains(NewPD, S);
13788 } else
13789 Record->addDecl(NewPD);
13790
13791 return NewPD;
13792}