blob: 6a48162502cb670bb0f41a6270142d0bd1ebe634 [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"
Douglas Gregor55297ac2008-12-23 00:26:44 +000039#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "llvm/ADT/SmallString.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000041#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000042#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000043
44using namespace clang;
45
Chris Lattner58258242008-04-10 02:22:51 +000046//===----------------------------------------------------------------------===//
47// CheckDefaultArgumentVisitor
48//===----------------------------------------------------------------------===//
49
Chris Lattnerb0d38442008-04-12 23:52:44 +000050namespace {
51 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
52 /// the default argument of a parameter to determine whether it
53 /// contains any ill-formed subexpressions. For example, this will
54 /// diagnose the use of local variables or parameters within the
55 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000056 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000057 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000058 Expr *DefaultArg;
59 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000060
Chris Lattnerb0d38442008-04-12 23:52:44 +000061 public:
Mike Stump11289f42009-09-09 15:08:12 +000062 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000063 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000064
Chris Lattnerb0d38442008-04-12 23:52:44 +000065 bool VisitExpr(Expr *Node);
66 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000067 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0d49512012-02-10 23:30:22 +000068 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall7353c862013-04-09 01:56:28 +000069 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000070 };
Chris Lattner58258242008-04-10 02:22:51 +000071
Chris Lattnerb0d38442008-04-12 23:52:44 +000072 /// VisitExpr - Visit all of the children of this expression.
73 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
74 bool IsInvalid = false;
John McCall8322c3a2011-02-13 04:07:26 +000075 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattner574dee62008-07-26 22:17:49 +000076 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000077 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000078 }
79
Chris Lattnerb0d38442008-04-12 23:52:44 +000080 /// VisitDeclRefExpr - Visit a reference to a declaration, to
81 /// determine whether this declaration can be used in the default
82 /// argument expression.
83 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000084 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000085 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
86 // C++ [dcl.fct.default]p9
87 // Default arguments are evaluated each time the function is
88 // called. The order of evaluation of function arguments is
89 // unspecified. Consequently, parameters of a function shall not
90 // be used in default argument expressions, even if they are not
91 // evaluated. Parameters of a function declared before a default
92 // argument expression are in scope and can hide namespace and
93 // class member names.
Daniel Dunbar62ee6412012-03-09 18:35:03 +000094 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +000095 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000096 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000097 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000098 // C++ [dcl.fct.default]p7
99 // Local variables shall not be used in default argument
100 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +0000101 if (VDecl->isLocalVarDecl())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000102 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000103 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +0000104 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000105 }
Chris Lattner58258242008-04-10 02:22:51 +0000106
Douglas Gregor8e12c382008-11-04 13:41:56 +0000107 return false;
108 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000109
Douglas Gregor97a9c812008-11-04 14:32:21 +0000110 /// VisitCXXThisExpr - Visit a C++ "this" expression.
111 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
112 // C++ [dcl.fct.default]p8:
113 // The keyword this shall not be used in a default argument of a
114 // member function.
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000115 return S->Diag(ThisE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000116 diag::err_param_default_argument_references_this)
117 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000118 }
Douglas Gregorf0d49512012-02-10 23:30:22 +0000119
John McCall7353c862013-04-09 01:56:28 +0000120 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
121 bool Invalid = false;
122 for (PseudoObjectExpr::semantics_iterator
123 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
124 Expr *E = *i;
125
126 // Look through bindings.
127 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
128 E = OVE->getSourceExpr();
129 assert(E && "pseudo-object binding without source expression?");
130 }
131
132 Invalid |= Visit(E);
133 }
134 return Invalid;
135 }
136
Douglas Gregorf0d49512012-02-10 23:30:22 +0000137 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
138 // C++11 [expr.lambda.prim]p13:
139 // A lambda-expression appearing in a default argument shall not
140 // implicitly or explicitly capture any entity.
141 if (Lambda->capture_begin() == Lambda->capture_end())
142 return false;
143
144 return S->Diag(Lambda->getLocStart(),
145 diag::err_lambda_capture_default_arg);
146 }
Chris Lattner58258242008-04-10 02:22:51 +0000147}
148
Richard Smithb7151b92013-04-10 06:11:48 +0000149void
150Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
151 const CXXMethodDecl *Method) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000152 // If we have an MSAny spec already, don't bother.
153 if (!Method || ComputedEST == EST_MSAny)
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000154 return;
155
156 const FunctionProtoType *Proto
157 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +0000158 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
159 if (!Proto)
160 return;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000161
162 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
163
164 // If this function can throw any exceptions, make a note of that.
Richard Smithd3b5c9082012-07-27 04:22:15 +0000165 if (EST == EST_MSAny || EST == EST_None) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000166 ClearExceptions();
167 ComputedEST = EST;
168 return;
169 }
170
Richard Smith938f40b2011-06-11 17:19:42 +0000171 // FIXME: If the call to this decl is using any of its default arguments, we
172 // need to search them for potentially-throwing calls.
173
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000174 // If this function has a basic noexcept, it doesn't affect the outcome.
175 if (EST == EST_BasicNoexcept)
176 return;
177
178 // If we have a throw-all spec at this point, ignore the function.
179 if (ComputedEST == EST_None)
180 return;
181
182 // If we're still at noexcept(true) and there's a nothrow() callee,
183 // change to that specification.
184 if (EST == EST_DynamicNone) {
185 if (ComputedEST == EST_BasicNoexcept)
186 ComputedEST = EST_DynamicNone;
187 return;
188 }
189
190 // Check out noexcept specs.
191 if (EST == EST_ComputedNoexcept) {
Richard Smithf623c962012-04-17 00:58:00 +0000192 FunctionProtoType::NoexceptResult NR =
193 Proto->getNoexceptSpec(Self->Context);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000194 assert(NR != FunctionProtoType::NR_NoNoexcept &&
195 "Must have noexcept result for EST_ComputedNoexcept.");
196 assert(NR != FunctionProtoType::NR_Dependent &&
197 "Should not generate implicit declarations for dependent cases, "
198 "and don't know how to handle them anyway.");
199
200 // noexcept(false) -> no spec on the new function
201 if (NR == FunctionProtoType::NR_Throw) {
202 ClearExceptions();
203 ComputedEST = EST_None;
204 }
205 // noexcept(true) won't change anything either.
206 return;
207 }
208
209 assert(EST == EST_Dynamic && "EST case not considered earlier.");
210 assert(ComputedEST != EST_None &&
211 "Shouldn't collect exceptions when throw-all is guaranteed.");
212 ComputedEST = EST_Dynamic;
213 // Record the exceptions in this function's exception specification.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000214 for (const auto &E : Proto->exceptions())
215 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)))
216 Exceptions.push_back(E);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000217}
218
Richard Smith938f40b2011-06-11 17:19:42 +0000219void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000220 if (!E || ComputedEST == EST_MSAny)
Richard Smith938f40b2011-06-11 17:19:42 +0000221 return;
222
223 // FIXME:
224 //
225 // C++0x [except.spec]p14:
NAKAMURA Takumi53648472011-06-21 03:19:28 +0000226 // [An] implicit exception-specification specifies the type-id T if and
227 // only if T is allowed by the exception-specification of a function directly
228 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith938f40b2011-06-11 17:19:42 +0000229 // function it directly invokes allows all exceptions, and f shall allow no
230 // exceptions if every function it directly invokes allows no exceptions.
231 //
232 // Note in particular that if an implicit exception-specification is generated
233 // for a function containing a throw-expression, that specification can still
234 // be noexcept(true).
235 //
236 // Note also that 'directly invoked' is not defined in the standard, and there
237 // is no indication that we should only consider potentially-evaluated calls.
238 //
239 // Ultimately we should implement the intent of the standard: the exception
240 // specification should be the set of exceptions which can be thrown by the
241 // implicit definition. For now, we assume that any non-nothrow expression can
242 // throw any exception.
243
Richard Smithf623c962012-04-17 00:58:00 +0000244 if (Self->canThrow(E))
Richard Smith938f40b2011-06-11 17:19:42 +0000245 ComputedEST = EST_None;
246}
247
Anders Carlssonc80a1272009-08-25 02:29:20 +0000248bool
John McCallb268a282010-08-23 23:25:46 +0000249Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000250 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000251 if (RequireCompleteType(Param->getLocation(), Param->getType(),
252 diag::err_typecheck_decl_incomplete_type)) {
253 Param->setInvalidDecl();
254 return true;
255 }
256
Anders Carlssonc80a1272009-08-25 02:29:20 +0000257 // C++ [dcl.fct.default]p5
258 // A default argument expression is implicitly converted (clause
259 // 4) to the parameter type. The default argument expression has
260 // the same semantic constraints as the initializer expression in
261 // a declaration of a variable of the parameter type, using the
262 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000263 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
264 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000265 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
266 EqualLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000267 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000268 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman5f101b92009-12-22 02:46:13 +0000269 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000270 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000271 Arg = Result.getAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000272
Richard Smithc406cb72013-01-17 01:17:56 +0000273 CheckCompletedExpr(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000274 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000275
Anders Carlssonc80a1272009-08-25 02:29:20 +0000276 // Okay: add the default argument to the parameter
277 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000278
Douglas Gregor758cb672010-10-12 18:23:32 +0000279 // We have already instantiated this parameter; provide each of the
280 // instantiations with the uninstantiated default argument.
281 UnparsedDefaultArgInstantiationsMap::iterator InstPos
282 = UnparsedDefaultArgInstantiations.find(Param);
283 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
284 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
285 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
286
287 // We're done tracking this parameter's instantiations.
288 UnparsedDefaultArgInstantiations.erase(InstPos);
289 }
290
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000291 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000292}
293
Chris Lattner58258242008-04-10 02:22:51 +0000294/// ActOnParamDefaultArgument - Check whether the default argument
295/// provided for a function parameter is well-formed. If so, attach it
296/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000297void
John McCall48871652010-08-21 09:40:31 +0000298Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000299 Expr *DefaultArg) {
300 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000301 return;
Mike Stump11289f42009-09-09 15:08:12 +0000302
John McCall48871652010-08-21 09:40:31 +0000303 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000304 UnparsedDefaultArgLocs.erase(Param);
305
Chris Lattner199abbc2008-04-08 05:04:30 +0000306 // Default arguments are only permitted in C++
David Blaikiebbafb8a2012-03-11 07:00:24 +0000307 if (!getLangOpts().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000308 Diag(EqualLoc, diag::err_param_default_argument)
309 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000310 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000311 return;
312 }
313
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000314 // Check for unexpanded parameter packs.
315 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
316 Param->setInvalidDecl();
317 return;
318 }
319
Anders Carlssonf1c26952009-08-25 01:02:06 +0000320 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000321 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
322 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000323 Param->setInvalidDecl();
324 return;
325 }
Mike Stump11289f42009-09-09 15:08:12 +0000326
John McCallb268a282010-08-23 23:25:46 +0000327 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000328}
329
Douglas Gregor58354032008-12-24 00:01:03 +0000330/// ActOnParamUnparsedDefaultArgument - We've seen a default
331/// argument for a function parameter, but we can't parse it yet
332/// because we're inside a class definition. Note that this default
333/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000334void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000335 SourceLocation EqualLoc,
336 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000337 if (!param)
338 return;
Mike Stump11289f42009-09-09 15:08:12 +0000339
John McCall48871652010-08-21 09:40:31 +0000340 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Nick Lewycky0f292892013-09-22 10:06:57 +0000341 Param->setUnparsedDefaultArg();
Anders Carlsson84613c42009-06-12 16:51:40 +0000342 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000343}
344
Douglas Gregor4d87df52008-12-16 21:30:33 +0000345/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
346/// the default argument for the parameter param failed.
Serge Pavlovb4b35782014-07-22 01:54:49 +0000347void Sema::ActOnParamDefaultArgumentError(Decl *param,
348 SourceLocation EqualLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000349 if (!param)
350 return;
Mike Stump11289f42009-09-09 15:08:12 +0000351
John McCall48871652010-08-21 09:40:31 +0000352 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000353 Param->setInvalidDecl();
Anders Carlsson84613c42009-06-12 16:51:40 +0000354 UnparsedDefaultArgLocs.erase(Param);
Serge Pavlovb4b35782014-07-22 01:54:49 +0000355 Param->setDefaultArg(new(Context)
356 OpaqueValueExpr(EqualLoc, Param->getType(), VK_RValue));
Douglas Gregor4d87df52008-12-16 21:30:33 +0000357}
358
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000359/// CheckExtraCXXDefaultArguments - Check for any extra default
360/// arguments in the declarator, which is not a function declaration
361/// or definition and therefore is not permitted to have default
362/// arguments. This routine should be invoked for every declarator
363/// that is not a function declaration or definition.
364void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
365 // C++ [dcl.fct.default]p3
366 // A default argument expression shall be specified only in the
367 // parameter-declaration-clause of a function declaration or in a
368 // template-parameter (14.1). It shall not be specified for a
369 // parameter pack. If it is specified in a
370 // parameter-declaration-clause, it shall not occur within a
371 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000372 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattner83f095c2009-03-28 19:18:32 +0000373 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000374 DeclaratorChunk &chunk = D.getTypeObject(i);
375 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000376 if (MightBeFunction) {
377 // This is a function declaration. It can have default arguments, but
378 // keep looking in case its return type is a function type with default
379 // arguments.
380 MightBeFunction = false;
381 continue;
382 }
Alp Tokerc5350722014-02-26 22:27:52 +0000383 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
384 ++argIdx) {
385 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000386 if (Param->hasUnparsedDefaultArg()) {
Alp Tokerc5350722014-02-26 22:27:52 +0000387 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000388 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000389 << SourceRange((*Toks)[1].getLocation(),
390 Toks->back().getLocation());
Douglas Gregor4d87df52008-12-16 21:30:33 +0000391 delete Toks;
Craig Topperc3ec1492014-05-26 06:22:03 +0000392 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
Douglas Gregor58354032008-12-24 00:01:03 +0000393 } else if (Param->getDefaultArg()) {
394 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
395 << Param->getDefaultArg()->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +0000396 Param->setDefaultArg(nullptr);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000397 }
398 }
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000399 } else if (chunk.Kind != DeclaratorChunk::Paren) {
400 MightBeFunction = false;
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000401 }
402 }
403}
404
David Majnemer502b0ed2013-06-25 23:09:30 +0000405static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
406 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
407 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
408 if (!PVD->hasDefaultArg())
409 return false;
410 if (!PVD->hasInheritedDefaultArg())
411 return true;
412 }
413 return false;
414}
415
Craig Toppere4794282012-09-21 04:33:26 +0000416/// MergeCXXFunctionDecl - Merge two declarations of the same C++
417/// function, once we already know that they have the same
418/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
419/// error, false otherwise.
James Molloye9430032012-03-13 08:55:35 +0000420bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
421 Scope *S) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000422 bool Invalid = false;
423
Chris Lattner199abbc2008-04-08 05:04:30 +0000424 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000425 // For non-template functions, default arguments can be added in
426 // later declarations of a function in the same
427 // scope. Declarations in different scopes have completely
428 // distinct sets of default arguments. That is, declarations in
429 // inner scopes do not acquire default arguments from
430 // declarations in outer scopes, and vice versa. In a given
431 // function declaration, all parameters subsequent to a
432 // parameter with a default argument shall have default
433 // arguments supplied in this or previous declarations. A
434 // default argument shall not be redefined by a later
435 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000436 //
437 // C++ [dcl.fct.default]p6:
Richard Smith541b38b2013-09-20 01:15:31 +0000438 // Except for member functions of class templates, the default arguments
439 // in a member function definition that appears outside of the class
440 // definition are added to the set of default arguments provided by the
Douglas Gregorc732aba2009-09-11 18:44:32 +0000441 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000442 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
443 ParmVarDecl *OldParam = Old->getParamDecl(p);
444 ParmVarDecl *NewParam = New->getParamDecl(p);
445
James Molloye9430032012-03-13 08:55:35 +0000446 bool OldParamHasDfl = OldParam->hasDefaultArg();
447 bool NewParamHasDfl = NewParam->hasDefaultArg();
448
449 NamedDecl *ND = Old;
Richard Smith541b38b2013-09-20 01:15:31 +0000450
451 // The declaration context corresponding to the scope is the semantic
452 // parent, unless this is a local function declaration, in which case
453 // it is that surrounding function.
454 DeclContext *ScopeDC = New->getLexicalDeclContext();
455 if (!ScopeDC->isFunctionOrMethod())
456 ScopeDC = New->getDeclContext();
457 if (S && !isDeclInScope(ND, ScopeDC, S) &&
458 !New->getDeclContext()->isRecord())
James Molloye9430032012-03-13 08:55:35 +0000459 // Ignore default parameters of old decl if they are not in
Richard Smith541b38b2013-09-20 01:15:31 +0000460 // the same scope and this is not an out-of-line definition of
461 // a member function.
James Molloye9430032012-03-13 08:55:35 +0000462 OldParamHasDfl = false;
463
464 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000465
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000466 unsigned DiagDefaultParamID =
467 diag::err_param_default_argument_redefinition;
468
469 // MSVC accepts that default parameters be redefined for member functions
470 // of template class. The new default parameter's value is ignored.
471 Invalid = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000472 if (getLangOpts().MicrosoftExt) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000473 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
474 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000475 // Merge the old default argument into the new parameter.
476 NewParam->setHasInheritedDefaultArg();
477 if (OldParam->hasUninstantiatedDefaultArg())
478 NewParam->setUninstantiatedDefaultArg(
479 OldParam->getUninstantiatedDefaultArg());
480 else
481 NewParam->setDefaultArg(OldParam->getInit());
Richard Smith1b98ccc2014-07-19 01:39:17 +0000482 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000483 Invalid = false;
484 }
485 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000486
Francois Pichet8cb243a2011-04-10 04:58:30 +0000487 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
488 // hint here. Alternatively, we could walk the type-source information
489 // for NewParam to find the last source location in the type... but it
490 // isn't worth the effort right now. This is the kind of test case that
491 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000492 // int f(int);
493 // void g(int (*fp)(int) = f);
494 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000495 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000496 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000497
498 // Look for the function declaration where the default argument was
499 // actually written, which may be a declaration prior to Old.
Douglas Gregorec9fd132012-01-14 16:38:05 +0000500 for (FunctionDecl *Older = Old->getPreviousDecl();
501 Older; Older = Older->getPreviousDecl()) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000502 if (!Older->getParamDecl(p)->hasDefaultArg())
503 break;
504
505 OldParam = Older->getParamDecl(p);
506 }
507
508 Diag(OldParam->getLocation(), diag::note_previous_definition)
509 << OldParam->getDefaultArgRange();
James Molloye9430032012-03-13 08:55:35 +0000510 } else if (OldParamHasDfl) {
John McCalle61b02b2010-05-04 01:53:42 +0000511 // Merge the old default argument into the new parameter.
512 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000513 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000514 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000515 if (OldParam->hasUninstantiatedDefaultArg())
516 NewParam->setUninstantiatedDefaultArg(
517 OldParam->getUninstantiatedDefaultArg());
518 else
John McCalle61b02b2010-05-04 01:53:42 +0000519 NewParam->setDefaultArg(OldParam->getInit());
James Molloye9430032012-03-13 08:55:35 +0000520 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000521 if (New->getDescribedFunctionTemplate()) {
522 // Paragraph 4, quoted above, only applies to non-template functions.
523 Diag(NewParam->getLocation(),
524 diag::err_param_default_argument_template_redecl)
525 << NewParam->getDefaultArgRange();
526 Diag(Old->getLocation(), diag::note_template_prev_declaration)
527 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000528 } else if (New->getTemplateSpecializationKind()
529 != TSK_ImplicitInstantiation &&
530 New->getTemplateSpecializationKind() != TSK_Undeclared) {
531 // C++ [temp.expr.spec]p21:
532 // Default function arguments shall not be specified in a declaration
533 // or a definition for one of the following explicit specializations:
534 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000535 // - the explicit specialization of a member function template;
536 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000537 // template where the class template specialization to which the
538 // member function specialization belongs is implicitly
539 // instantiated.
540 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
541 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
542 << New->getDeclName()
543 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000544 } else if (New->getDeclContext()->isDependentContext()) {
545 // C++ [dcl.fct.default]p6 (DR217):
546 // Default arguments for a member function of a class template shall
547 // be specified on the initial declaration of the member function
548 // within the class template.
549 //
550 // Reading the tea leaves a bit in DR217 and its reference to DR205
551 // leads me to the conclusion that one cannot add default function
552 // arguments for an out-of-line definition of a member function of a
553 // dependent type.
554 int WhichKind = 2;
555 if (CXXRecordDecl *Record
556 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
557 if (Record->getDescribedClassTemplate())
558 WhichKind = 0;
559 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
560 WhichKind = 1;
561 else
562 WhichKind = 2;
563 }
564
565 Diag(NewParam->getLocation(),
566 diag::err_param_default_argument_member_template_redecl)
567 << WhichKind
568 << NewParam->getDefaultArgRange();
569 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000570 }
571 }
572
Richard Smith58c3cc12012-11-28 03:45:24 +0000573 // DR1344: If a default argument is added outside a class definition and that
574 // default argument makes the function a special member function, the program
575 // is ill-formed. This can only happen for constructors.
576 if (isa<CXXConstructorDecl>(New) &&
577 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
578 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
579 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
580 if (NewSM != OldSM) {
581 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
582 assert(NewParam->hasDefaultArg());
583 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
584 << NewParam->getDefaultArgRange() << NewSM;
585 Diag(Old->getLocation(), diag::note_previous_declaration);
586 }
587 }
588
David Majnemeree4f4022014-03-30 06:44:54 +0000589 const FunctionDecl *Def;
Richard Smith5b8b3db2012-02-20 23:28:05 +0000590 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000591 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000592 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000593 if (New->isConstexpr() != Old->isConstexpr()) {
594 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
595 << New << New->isConstexpr();
596 Diag(Old->getLocation(), diag::note_previous_declaration);
597 Invalid = true;
David Majnemeree4f4022014-03-30 06:44:54 +0000598 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) {
599 // C++11 [dcl.fcn.spec]p4:
600 // If the definition of a function appears in a translation unit before its
601 // first declaration as inline, the program is ill-formed.
602 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
603 Diag(Def->getLocation(), diag::note_previous_definition);
604 Invalid = true;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000605 }
606
David Majnemer502b0ed2013-06-25 23:09:30 +0000607 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000608 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000609 // the only declaration of the function or function template in the
610 // translation unit.
611 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
612 functionDeclHasDefaultArgument(Old)) {
613 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
614 Diag(Old->getLocation(), diag::note_previous_declaration);
615 Invalid = true;
616 }
617
Douglas Gregorf40863c2010-02-12 07:32:17 +0000618 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000619 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000620
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000621 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000622}
623
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000624/// \brief Merge the exception specifications of two variable declarations.
625///
626/// This is called when there's a redeclaration of a VarDecl. The function
627/// checks if the redeclaration might have an exception specification and
628/// validates compatibility and merges the specs if necessary.
629void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
630 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000631 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000632 return;
633
634 assert(Context.hasSameType(New->getType(), Old->getType()) &&
635 "Should only be called if types are otherwise the same.");
636
637 QualType NewType = New->getType();
638 QualType OldType = Old->getType();
639
640 // We're only interested in pointers and references to functions, as well
641 // as pointers to member functions.
642 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
643 NewType = R->getPointeeType();
644 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
645 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
646 NewType = P->getPointeeType();
647 OldType = OldType->getAs<PointerType>()->getPointeeType();
648 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
649 NewType = M->getPointeeType();
650 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
651 }
652
653 if (!NewType->isFunctionProtoType())
654 return;
655
656 // There's lots of special cases for functions. For function pointers, system
657 // libraries are hopefully not as broken so that we don't need these
658 // workarounds.
659 if (CheckEquivalentExceptionSpec(
660 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
661 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
662 New->setInvalidDecl();
663 }
664}
665
Chris Lattner199abbc2008-04-08 05:04:30 +0000666/// CheckCXXDefaultArguments - Verify that the default arguments for a
667/// function declaration are well-formed according to C++
668/// [dcl.fct.default].
669void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
670 unsigned NumParams = FD->getNumParams();
671 unsigned p;
672
673 // Find first parameter with a default argument
674 for (p = 0; p < NumParams; ++p) {
675 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +0000676 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000677 break;
678 }
679
680 // C++ [dcl.fct.default]p4:
681 // In a given function declaration, all parameters
682 // subsequent to a parameter with a default argument shall
683 // have default arguments supplied in this or previous
684 // declarations. A default argument shall not be redefined
685 // by a later declaration (not even to the same value).
686 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000687 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000688 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000689 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000690 if (Param->isInvalidDecl())
691 /* We already complained about this parameter. */;
692 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000693 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000694 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000695 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000696 else
Mike Stump11289f42009-09-09 15:08:12 +0000697 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000698 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000699
Chris Lattner199abbc2008-04-08 05:04:30 +0000700 LastMissingDefaultArg = p;
701 }
702 }
703
704 if (LastMissingDefaultArg > 0) {
705 // Some default arguments were missing. Clear out all of the
706 // default arguments up to (and including) the last missing
707 // default argument, so that we leave the function parameters
708 // in a semantically valid state.
709 for (p = 0; p <= LastMissingDefaultArg; ++p) {
710 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000711 if (Param->hasDefaultArg()) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000712 Param->setDefaultArg(nullptr);
Chris Lattner199abbc2008-04-08 05:04:30 +0000713 }
714 }
715 }
716}
Douglas Gregor556877c2008-04-13 21:30:24 +0000717
Richard Smitheb3c10c2011-10-01 02:31:28 +0000718// CheckConstexprParameterTypes - Check whether a function's parameter types
719// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +0000720// diagnostic and return false.
721static bool CheckConstexprParameterTypes(Sema &SemaRef,
722 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000723 unsigned ArgIndex = 0;
724 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +0000725 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
726 e = FT->param_type_end();
727 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000728 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
729 SourceLocation ParamLoc = PD->getLocation();
730 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000731 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000732 diag::err_constexpr_non_literal_param,
733 ArgIndex+1, PD->getSourceRange(),
734 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000735 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000736 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000737 return true;
738}
739
740/// \brief Get diagnostic %select index for tag kind for
741/// record diagnostic message.
742/// WARNING: Indexes apply to particular diagnostics only!
743///
744/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +0000745static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +0000746 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +0000747 case TTK_Struct: return 0;
748 case TTK_Interface: return 1;
749 case TTK_Class: return 2;
750 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +0000751 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000752}
753
754// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
755// the requirements of a constexpr function definition or a constexpr
756// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +0000757// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000758//
Richard Smith3607ffe2012-02-13 03:54:03 +0000759// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
760bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +0000761 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
762 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000763 // C++11 [dcl.constexpr]p4:
764 // The definition of a constexpr constructor shall satisfy the following
765 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000766 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +0000767 const CXXRecordDecl *RD = MD->getParent();
768 if (RD->getNumVBases()) {
769 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
770 << isa<CXXConstructorDecl>(NewFD)
771 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Aaron Ballman445a9392014-03-13 16:15:17 +0000772 for (const auto &I : RD->vbases())
773 Diag(I.getLocStart(),
774 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000775 return false;
776 }
Richard Smith7971b692012-01-13 04:54:00 +0000777 }
778
779 if (!isa<CXXConstructorDecl>(NewFD)) {
780 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000781 // The definition of a constexpr function shall satisfy the following
782 // constraints:
783 // - it shall not be virtual;
784 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
785 if (Method && Method->isVirtual()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000786 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000787
Richard Smith3607ffe2012-02-13 03:54:03 +0000788 // If it's not obvious why this function is virtual, find an overridden
789 // function which uses the 'virtual' keyword.
790 const CXXMethodDecl *WrittenVirtual = Method;
791 while (!WrittenVirtual->isVirtualAsWritten())
792 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
793 if (WrittenVirtual != Method)
794 Diag(WrittenVirtual->getLocation(),
795 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000796 return false;
797 }
798
799 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +0000800 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000801 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000802 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000803 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000804 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000805 }
806
Richard Smith7971b692012-01-13 04:54:00 +0000807 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +0000808 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +0000809 return false;
810
Richard Smitheb3c10c2011-10-01 02:31:28 +0000811 return true;
812}
813
814/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +0000815/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000816///
Richard Smithd9f663b2013-04-22 15:31:51 +0000817/// \return true if the body is OK (maybe only as an extension), false if we
818/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000819static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +0000820 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
821 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000822 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
823 // contain only
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000824 for (const auto *DclIt : DS->decls()) {
825 switch (DclIt->getKind()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000826 case Decl::StaticAssert:
827 case Decl::Using:
828 case Decl::UsingShadow:
829 case Decl::UsingDirective:
830 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +0000831 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000832 // - static_assert-declarations
833 // - using-declarations,
834 // - using-directives,
835 continue;
836
837 case Decl::Typedef:
838 case Decl::TypeAlias: {
839 // - typedef declarations and alias-declarations that do not define
840 // classes or enumerations,
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000841 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000842 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
843 // Don't allow variably-modified types in constexpr functions.
844 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
845 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
846 << TL.getSourceRange() << TL.getType()
847 << isa<CXXConstructorDecl>(Dcl);
848 return false;
849 }
850 continue;
851 }
852
853 case Decl::Enum:
854 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +0000855 // C++1y allows types to be defined, not just declared.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000856 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smithd9f663b2013-04-22 15:31:51 +0000857 SemaRef.Diag(DS->getLocStart(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000858 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +0000859 ? diag::warn_cxx11_compat_constexpr_type_definition
860 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000861 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000862 continue;
863
Richard Smithd9f663b2013-04-22 15:31:51 +0000864 case Decl::EnumConstant:
865 case Decl::IndirectField:
866 case Decl::ParmVar:
867 // These can only appear with other declarations which are banned in
868 // C++11 and permitted in C++1y, so ignore them.
869 continue;
870
871 case Decl::Var: {
872 // C++1y [dcl.constexpr]p3 allows anything except:
873 // a definition of a variable of non-literal type or of static or
874 // thread storage duration or for which no initialization is performed.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000875 const auto *VD = cast<VarDecl>(DclIt);
Richard Smithd9f663b2013-04-22 15:31:51 +0000876 if (VD->isThisDeclarationADefinition()) {
877 if (VD->isStaticLocal()) {
878 SemaRef.Diag(VD->getLocation(),
879 diag::err_constexpr_local_var_static)
880 << isa<CXXConstructorDecl>(Dcl)
881 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
882 return false;
883 }
Richard Smith3da88fa2013-04-26 14:36:30 +0000884 if (!VD->getType()->isDependentType() &&
885 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +0000886 VD->getLocation(), VD->getType(),
887 diag::err_constexpr_local_var_non_literal_type,
888 isa<CXXConstructorDecl>(Dcl)))
889 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +0000890 if (!VD->getType()->isDependentType() &&
891 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000892 SemaRef.Diag(VD->getLocation(),
893 diag::err_constexpr_local_var_no_init)
894 << isa<CXXConstructorDecl>(Dcl);
895 return false;
896 }
897 }
898 SemaRef.Diag(VD->getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000899 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +0000900 ? diag::warn_cxx11_compat_constexpr_local_var
901 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000902 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +0000903 continue;
904 }
905
906 case Decl::NamespaceAlias:
907 case Decl::Function:
908 // These are disallowed in C++11 and permitted in C++1y. Allow them
909 // everywhere as an extension.
910 if (!Cxx1yLoc.isValid())
911 Cxx1yLoc = DS->getLocStart();
912 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000913
914 default:
915 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
916 << isa<CXXConstructorDecl>(Dcl);
917 return false;
918 }
919 }
920
921 return true;
922}
923
924/// Check that the given field is initialized within a constexpr constructor.
925///
926/// \param Dcl The constexpr constructor being checked.
927/// \param Field The field being checked. This may be a member of an anonymous
928/// struct or union nested within the class being checked.
929/// \param Inits All declarations, including anonymous struct/union members and
930/// indirect members, for which any initialization was provided.
931/// \param Diagnosed Set to true if an error is produced.
932static void CheckConstexprCtorInitializer(Sema &SemaRef,
933 const FunctionDecl *Dcl,
934 FieldDecl *Field,
935 llvm::SmallSet<Decl*, 16> &Inits,
936 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +0000937 if (Field->isInvalidDecl())
938 return;
939
Douglas Gregor556e5862011-10-10 17:22:13 +0000940 if (Field->isUnnamedBitfield())
941 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +0000942
Richard Smithab44d5b2013-12-10 08:25:00 +0000943 // Anonymous unions with no variant members and empty anonymous structs do not
944 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
945 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +0000946 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +0000947 (Field->getType()->isUnionType()
948 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
949 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +0000950 return;
951
Richard Smitheb3c10c2011-10-01 02:31:28 +0000952 if (!Inits.count(Field)) {
953 if (!Diagnosed) {
954 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
955 Diagnosed = true;
956 }
957 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
958 } else if (Field->isAnonymousStructOrUnion()) {
959 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000960 for (auto *I : RD->fields())
Richard Smitheb3c10c2011-10-01 02:31:28 +0000961 // If an anonymous union contains an anonymous struct of which any member
962 // is initialized, all members must be initialized.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000963 if (!RD->isUnion() || Inits.count(I))
964 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000965 }
966}
967
Richard Smithd9f663b2013-04-22 15:31:51 +0000968/// Check the provided statement is allowed in a constexpr function
969/// definition.
970static bool
971CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +0000972 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +0000973 SourceLocation &Cxx1yLoc) {
974 // - its function-body shall be [...] a compound-statement that contains only
975 switch (S->getStmtClass()) {
976 case Stmt::NullStmtClass:
977 // - null statements,
978 return true;
979
980 case Stmt::DeclStmtClass:
981 // - static_assert-declarations
982 // - using-declarations,
983 // - using-directives,
984 // - typedef declarations and alias-declarations that do not define
985 // classes or enumerations,
986 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
987 return false;
988 return true;
989
990 case Stmt::ReturnStmtClass:
991 // - and exactly one return statement;
992 if (isa<CXXConstructorDecl>(Dcl)) {
993 // C++1y allows return statements in constexpr constructors.
994 if (!Cxx1yLoc.isValid())
995 Cxx1yLoc = S->getLocStart();
996 return true;
997 }
998
999 ReturnStmts.push_back(S->getLocStart());
1000 return true;
1001
1002 case Stmt::CompoundStmtClass: {
1003 // C++1y allows compound-statements.
1004 if (!Cxx1yLoc.isValid())
1005 Cxx1yLoc = S->getLocStart();
1006
1007 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001008 for (auto *BodyIt : CompStmt->body()) {
1009 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001010 Cxx1yLoc))
1011 return false;
1012 }
1013 return true;
1014 }
1015
1016 case Stmt::AttributedStmtClass:
1017 if (!Cxx1yLoc.isValid())
1018 Cxx1yLoc = S->getLocStart();
1019 return true;
1020
1021 case Stmt::IfStmtClass: {
1022 // C++1y allows if-statements.
1023 if (!Cxx1yLoc.isValid())
1024 Cxx1yLoc = S->getLocStart();
1025
1026 IfStmt *If = cast<IfStmt>(S);
1027 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1028 Cxx1yLoc))
1029 return false;
1030 if (If->getElse() &&
1031 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1032 Cxx1yLoc))
1033 return false;
1034 return true;
1035 }
1036
1037 case Stmt::WhileStmtClass:
1038 case Stmt::DoStmtClass:
1039 case Stmt::ForStmtClass:
1040 case Stmt::CXXForRangeStmtClass:
1041 case Stmt::ContinueStmtClass:
1042 // C++1y allows all of these. We don't allow them as extensions in C++11,
1043 // because they don't make sense without variable mutation.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001044 if (!SemaRef.getLangOpts().CPlusPlus14)
Richard Smithd9f663b2013-04-22 15:31:51 +00001045 break;
1046 if (!Cxx1yLoc.isValid())
1047 Cxx1yLoc = S->getLocStart();
1048 for (Stmt::child_range Children = S->children(); Children; ++Children)
1049 if (*Children &&
1050 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1051 Cxx1yLoc))
1052 return false;
1053 return true;
1054
1055 case Stmt::SwitchStmtClass:
1056 case Stmt::CaseStmtClass:
1057 case Stmt::DefaultStmtClass:
1058 case Stmt::BreakStmtClass:
1059 // C++1y allows switch-statements, and since they don't need variable
1060 // mutation, we can reasonably allow them in C++11 as an extension.
1061 if (!Cxx1yLoc.isValid())
1062 Cxx1yLoc = S->getLocStart();
1063 for (Stmt::child_range Children = S->children(); Children; ++Children)
1064 if (*Children &&
1065 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1066 Cxx1yLoc))
1067 return false;
1068 return true;
1069
1070 default:
1071 if (!isa<Expr>(S))
1072 break;
1073
1074 // C++1y allows expression-statements.
1075 if (!Cxx1yLoc.isValid())
1076 Cxx1yLoc = S->getLocStart();
1077 return true;
1078 }
1079
1080 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1081 << isa<CXXConstructorDecl>(Dcl);
1082 return false;
1083}
1084
Richard Smitheb3c10c2011-10-01 02:31:28 +00001085/// Check the body for the given constexpr function declaration only contains
1086/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1087///
1088/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001089bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001090 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001091 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001092 // The definition of a constexpr function shall satisfy the following
1093 // constraints: [...]
1094 // - its function-body shall be = delete, = default, or a
1095 // compound-statement
1096 //
Richard Smith74388b42012-02-04 00:33:54 +00001097 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001098 // In the definition of a constexpr constructor, [...]
1099 // - its function-body shall not be a function-try-block;
1100 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1101 << isa<CXXConstructorDecl>(Dcl);
1102 return false;
1103 }
1104
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001105 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001106
1107 // - its function-body shall be [...] a compound-statement that contains only
1108 // [... list of cases ...]
1109 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1110 SourceLocation Cxx1yLoc;
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001111 for (auto *BodyIt : CompBody->body()) {
1112 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smithd9f663b2013-04-22 15:31:51 +00001113 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001114 }
1115
Richard Smithd9f663b2013-04-22 15:31:51 +00001116 if (Cxx1yLoc.isValid())
1117 Diag(Cxx1yLoc,
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001118 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001119 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1120 : diag::ext_constexpr_body_invalid_stmt)
1121 << isa<CXXConstructorDecl>(Dcl);
1122
Richard Smitheb3c10c2011-10-01 02:31:28 +00001123 if (const CXXConstructorDecl *Constructor
1124 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1125 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001126 // DR1359:
1127 // - every non-variant non-static data member and base class sub-object
1128 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001129 // DR1460:
1130 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001131 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001132 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001133 if (Constructor->getNumCtorInitializers() == 0 &&
1134 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001135 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1136 return false;
1137 }
Richard Smithf368fb42011-10-10 16:38:04 +00001138 } else if (!Constructor->isDependentContext() &&
1139 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001140 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1141
1142 // Skip detailed checking if we have enough initializers, and we would
1143 // allow at most one initializer per member.
1144 bool AnyAnonStructUnionMembers = false;
1145 unsigned Fields = 0;
1146 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1147 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001148 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001149 AnyAnonStructUnionMembers = true;
1150 break;
1151 }
1152 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001153 // DR1460:
1154 // - if the class is a union-like class, but is not a union, for each of
1155 // its anonymous union members having variant members, exactly one of
1156 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001157 if (AnyAnonStructUnionMembers ||
1158 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1159 // Check initialization of non-static data members. Base classes are
1160 // always initialized so do not need to be checked. Dependent bases
1161 // might not have initializers in the member initializer list.
1162 llvm::SmallSet<Decl*, 16> Inits;
Aaron Ballman0ad78302014-03-13 17:34:31 +00001163 for (const auto *I: Constructor->inits()) {
1164 if (FieldDecl *FD = I->getMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001165 Inits.insert(FD);
Aaron Ballman0ad78302014-03-13 17:34:31 +00001166 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001167 Inits.insert(ID->chain_begin(), ID->chain_end());
1168 }
1169
1170 bool Diagnosed = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001171 for (auto *I : RD->fields())
1172 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001173 if (Diagnosed)
1174 return false;
1175 }
1176 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001177 } else {
1178 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001179 // C++1y doesn't require constexpr functions to contain a 'return'
Richard Smith06ffb452014-04-22 23:14:23 +00001180 // statement. We still do, unless the return type might be void, because
Richard Smithd9f663b2013-04-22 15:31:51 +00001181 // otherwise if there's no return statement, the function cannot
1182 // be used in a core constant expression.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001183 bool OK = getLangOpts().CPlusPlus14 &&
Richard Smith06ffb452014-04-22 23:14:23 +00001184 (Dcl->getReturnType()->isVoidType() ||
1185 Dcl->getReturnType()->isDependentType());
Richard Smithd9f663b2013-04-22 15:31:51 +00001186 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00001187 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1188 : diag::err_constexpr_body_no_return);
1189 return OK;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001190 }
1191 if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001192 Diag(ReturnStmts.back(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001193 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001194 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1195 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001196 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1197 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001198 }
1199 }
1200
Richard Smith74388b42012-02-04 00:33:54 +00001201 // C++11 [dcl.constexpr]p5:
1202 // if no function argument values exist such that the function invocation
1203 // substitution would produce a constant expression, the program is
1204 // ill-formed; no diagnostic required.
1205 // C++11 [dcl.constexpr]p3:
1206 // - every constructor call and implicit conversion used in initializing the
1207 // return value shall be one of those allowed in a constant expression.
1208 // C++11 [dcl.constexpr]p4:
1209 // - every constructor involved in initializing non-static data members and
1210 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001211 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00001212 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00001213 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00001214 << isa<CXXConstructorDecl>(Dcl);
1215 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1216 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00001217 // Don't return false here: we allow this for compatibility in
1218 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00001219 }
1220
Richard Smitheb3c10c2011-10-01 02:31:28 +00001221 return true;
1222}
1223
Douglas Gregor61956c42008-10-31 09:07:45 +00001224/// isCurrentClassName - Determine whether the identifier II is the
1225/// name of the class type currently being defined. In the case of
1226/// nested classes, this will only return true if II is the name of
1227/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001228bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1229 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001230 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00001231
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001232 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00001233 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00001234 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001235 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1236 } else
1237 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1238
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00001239 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00001240 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00001241 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00001242}
1243
Richard Smithfb8b7b92013-10-15 00:00:26 +00001244/// \brief Determine whether the identifier II is a typo for the name of
1245/// the class type currently being defined. If so, update it to the identifier
1246/// that should have been used.
1247bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1248 assert(getLangOpts().CPlusPlus && "No class names in C!");
1249
1250 if (!getLangOpts().SpellChecking)
1251 return false;
1252
1253 CXXRecordDecl *CurDecl;
1254 if (SS && SS->isSet() && !SS->isInvalid()) {
1255 DeclContext *DC = computeDeclContext(*SS, true);
1256 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1257 } else
1258 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1259
1260 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1261 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1262 < II->getLength()) {
1263 II = CurDecl->getIdentifier();
1264 return true;
1265 }
1266
1267 return false;
1268}
1269
Douglas Gregordc974572012-11-10 07:24:09 +00001270/// \brief Determine whether the given class is a base class of the given
1271/// class, including looking at dependent bases.
1272static bool findCircularInheritance(const CXXRecordDecl *Class,
1273 const CXXRecordDecl *Current) {
1274 SmallVector<const CXXRecordDecl*, 8> Queue;
1275
1276 Class = Class->getCanonicalDecl();
1277 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001278 for (const auto &I : Current->bases()) {
1279 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregordc974572012-11-10 07:24:09 +00001280 if (!Base)
1281 continue;
1282
1283 Base = Base->getDefinition();
1284 if (!Base)
1285 continue;
1286
1287 if (Base->getCanonicalDecl() == Class)
1288 return true;
1289
1290 Queue.push_back(Base);
1291 }
1292
1293 if (Queue.empty())
1294 return false;
1295
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001296 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00001297 }
1298
1299 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00001300}
1301
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00001302/// \brief Perform propagation of DLL attributes from a derived class to a
1303/// templated base class for MS compatibility.
1304static void propagateDLLAttrToBaseClassTemplate(
1305 Sema &S, CXXRecordDecl *Class, Attr *ClassAttr,
1306 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
1307 if (getDLLAttr(
1308 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
1309 // If the base class template has a DLL attribute, don't try to change it.
1310 return;
1311 }
1312
1313 if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
1314 // If the base class is not already specialized, we can do the propagation.
1315 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
1316 NewAttr->setInherited(true);
1317 BaseTemplateSpec->addAttr(NewAttr);
1318 return;
1319 }
1320
1321 bool DifferentAttribute = false;
1322 if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) {
1323 if (!SpecializationAttr->isInherited()) {
1324 // The template has previously been specialized or instantiated with an
1325 // explicit attribute. We should not try to change it.
1326 return;
1327 }
1328 if (SpecializationAttr->getKind() == ClassAttr->getKind()) {
1329 // The specialization already has the right attribute.
1330 return;
1331 }
1332 DifferentAttribute = true;
1333 }
1334
1335 // The template was previously instantiated or explicitly specialized without
1336 // a dll attribute, or the template was previously instantiated with a
1337 // different inherited attribute. It's too late for us to change the
1338 // attribute, so warn that this is unsupported.
1339 S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
1340 << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute;
1341 S.Diag(ClassAttr->getLocation(), diag::note_attribute);
1342 if (BaseTemplateSpec->isExplicitSpecialization()) {
1343 S.Diag(BaseTemplateSpec->getLocation(),
1344 diag::note_template_class_explicit_specialization_was_here)
1345 << BaseTemplateSpec;
1346 } else {
1347 S.Diag(BaseTemplateSpec->getPointOfInstantiation(),
1348 diag::note_template_class_instantiation_was_here)
1349 << BaseTemplateSpec;
1350 }
1351}
1352
Mike Stump11289f42009-09-09 15:08:12 +00001353/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001354///
1355/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1356/// and returns NULL otherwise.
1357CXXBaseSpecifier *
1358Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1359 SourceRange SpecifierRange,
1360 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001361 TypeSourceInfo *TInfo,
1362 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001363 QualType BaseType = TInfo->getType();
1364
Douglas Gregor463421d2009-03-03 04:44:36 +00001365 // C++ [class.union]p1:
1366 // A union shall not have base classes.
1367 if (Class->isUnion()) {
1368 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1369 << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001370 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001371 }
1372
Douglas Gregor752a5952011-01-03 22:36:02 +00001373 if (EllipsisLoc.isValid() &&
1374 !TInfo->getType()->containsUnexpandedParameterPack()) {
1375 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1376 << TInfo->getTypeLoc().getSourceRange();
1377 EllipsisLoc = SourceLocation();
1378 }
Douglas Gregor62004702012-11-10 01:18:17 +00001379
1380 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1381
1382 if (BaseType->isDependentType()) {
1383 // Make sure that we don't have circular inheritance among our dependent
1384 // bases. For non-dependent bases, the check for completeness below handles
1385 // this.
1386 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1387 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1388 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00001389 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00001390 Diag(BaseLoc, diag::err_circular_inheritance)
1391 << BaseType << Context.getTypeDeclType(Class);
1392
1393 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1394 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1395 << BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00001396
1397 return nullptr;
Douglas Gregor62004702012-11-10 01:18:17 +00001398 }
1399 }
1400
Mike Stump11289f42009-09-09 15:08:12 +00001401 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001402 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001403 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00001404 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001405
1406 // Base specifiers must be record types.
1407 if (!BaseType->isRecordType()) {
1408 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001409 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001410 }
1411
1412 // C++ [class.union]p1:
1413 // A union shall not be used as a base class.
1414 if (BaseType->isUnionType()) {
1415 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001416 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001417 }
1418
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00001419 // For the MS ABI, propagate DLL attributes to base class templates.
1420 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1421 if (Attr *ClassAttr = getDLLAttr(Class)) {
1422 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1423 BaseType->getAsCXXRecordDecl())) {
1424 propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr,
1425 BaseTemplate, BaseLoc);
1426 }
1427 }
1428 }
1429
Douglas Gregor463421d2009-03-03 04:44:36 +00001430 // C++ [class.derived]p2:
1431 // The class-name in a base-specifier shall not be an incompletely
1432 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001433 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001434 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00001435 Class->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00001436 return nullptr;
John McCall3696dcb2010-08-17 07:23:57 +00001437 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001438
Eli Friedmanc96d4962009-08-15 21:55:26 +00001439 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001440 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001441 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001442 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001443 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00001444 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00001445 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001446
David Majnemer9b1754d2013-11-02 12:00:36 +00001447 // A class which contains a flexible array member is not suitable for use as a
1448 // base class:
1449 // - If the layout determines that a base comes before another base,
1450 // the flexible array member would index into the subsequent base.
1451 // - If the layout determines that base comes before the derived class,
1452 // the flexible array member would index into the derived class.
1453 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1454 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1455 << CXXBaseDecl->getDeclName();
Craig Topperc3ec1492014-05-26 06:22:03 +00001456 return nullptr;
David Majnemer9b1754d2013-11-02 12:00:36 +00001457 }
1458
Anders Carlsson65c76d32011-03-25 14:55:14 +00001459 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00001460 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00001461 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00001462 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00001463 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00001464 << CXXBaseDecl->getDeclName()
1465 << FA->isSpelledAsSealed();
Alp Toker2afa8782014-05-28 12:20:14 +00001466 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1467 << CXXBaseDecl->getDeclName() << FA->getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00001468 return nullptr;
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001469 }
1470
John McCall3696dcb2010-08-17 07:23:57 +00001471 if (BaseDecl->isInvalidDecl())
1472 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00001473
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001474 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001475 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001476 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001477 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001478}
1479
Douglas Gregor556877c2008-04-13 21:30:24 +00001480/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1481/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001482/// example:
1483/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001484/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001485BaseResult
John McCall48871652010-08-21 09:40:31 +00001486Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00001487 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00001488 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001489 ParsedType basetype, SourceLocation BaseLoc,
1490 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001491 if (!classdecl)
1492 return true;
1493
Douglas Gregorc40290e2009-03-09 23:48:35 +00001494 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001495 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001496 if (!Class)
1497 return true;
1498
David Majnemer5ef4fe72014-06-13 06:43:46 +00001499 // We haven't yet attached the base specifiers.
1500 Class->setIsParsingBaseSpecifiers();
1501
Richard Smith4c96e992013-02-19 23:47:15 +00001502 // We do not support any C++11 attributes on base-specifiers yet.
1503 // Diagnose any attributes we see.
1504 if (!Attributes.empty()) {
1505 for (AttributeList *Attr = Attributes.getList(); Attr;
1506 Attr = Attr->getNext()) {
1507 if (Attr->isInvalid() ||
1508 Attr->getKind() == AttributeList::IgnoredAttribute)
1509 continue;
1510 Diag(Attr->getLoc(),
1511 Attr->getKind() == AttributeList::UnknownAttribute
1512 ? diag::warn_unknown_attribute_ignored
1513 : diag::err_base_specifier_attribute)
1514 << Attr->getName();
1515 }
1516 }
1517
Craig Topperc3ec1492014-05-26 06:22:03 +00001518 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001519 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001520
Douglas Gregor752a5952011-01-03 22:36:02 +00001521 if (EllipsisLoc.isInvalid() &&
1522 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001523 UPPC_BaseType))
1524 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001525
Douglas Gregor463421d2009-03-03 04:44:36 +00001526 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001527 Virtual, Access, TInfo,
1528 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001529 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001530 else
1531 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001532
Douglas Gregor463421d2009-03-03 04:44:36 +00001533 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001534}
Douglas Gregor556877c2008-04-13 21:30:24 +00001535
Douglas Gregor463421d2009-03-03 04:44:36 +00001536/// \brief Performs the actual work of attaching the given base class
1537/// specifiers to a C++ class.
1538bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1539 unsigned NumBases) {
1540 if (NumBases == 0)
1541 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001542
1543 // Used to keep track of which base types we have already seen, so
1544 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001545 // that the key is always the unqualified canonical type of the base
1546 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001547 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1548
1549 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001550 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001551 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001552 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001553 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001554 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001555 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001556
1557 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1558 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00001559 // C++ [class.mi]p3:
1560 // A class shall not be specified as a direct base class of a
1561 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001562 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001563 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001564 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001565 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001566
1567 // Delete the duplicate base class specifier; we're going to
1568 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001569 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001570
1571 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001572 } else {
1573 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001574 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00001575 Bases[NumGoodBases++] = Bases[idx];
John McCalldb632ac2012-09-25 07:32:39 +00001576 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1577 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1578 if (Class->isInterface() &&
1579 (!RD->isInterface() ||
1580 KnownBase->getAccessSpecifier() != AS_public)) {
1581 // The Microsoft extension __interface does not permit bases that
1582 // are not themselves public interfaces.
1583 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1584 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1585 << RD->getSourceRange();
1586 Invalid = true;
1587 }
1588 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00001589 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00001590 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001591 }
1592 }
1593
1594 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001595 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001596
1597 // Delete the remaining (good) base class specifiers, since their
1598 // data has been copied into the CXXRecordDecl.
1599 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001600 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001601
1602 return Invalid;
1603}
1604
1605/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1606/// class, after checking whether there are any duplicate base
1607/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001608void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001609 unsigned NumBases) {
1610 if (!ClassDecl || !Bases || !NumBases)
1611 return;
1612
1613 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelme3cea802013-07-22 05:04:01 +00001614 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001615}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001616
Douglas Gregor36d1b142009-10-06 17:59:45 +00001617/// \brief Determine whether the type \p Derived is a C++ class that is
1618/// derived from the type \p Base.
1619bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001620 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001621 return false;
John McCalle78aac42010-03-10 03:28:59 +00001622
Douglas Gregor45bb4832013-03-26 23:36:30 +00001623 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001624 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001625 return false;
1626
Douglas Gregor45bb4832013-03-26 23:36:30 +00001627 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001628 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001629 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00001630
1631 // If either the base or the derived type is invalid, don't try to
1632 // check whether one is derived from the other.
1633 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1634 return false;
1635
John McCall67da35c2010-02-04 22:26:26 +00001636 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1637 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001638}
1639
1640/// \brief Determine whether the type \p Derived is a C++ class that is
1641/// derived from the type \p Base.
1642bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001643 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001644 return false;
1645
Douglas Gregor45bb4832013-03-26 23:36:30 +00001646 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001647 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001648 return false;
1649
Douglas Gregor45bb4832013-03-26 23:36:30 +00001650 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001651 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001652 return false;
1653
Douglas Gregor36d1b142009-10-06 17:59:45 +00001654 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1655}
1656
Anders Carlssona70cff62010-04-24 19:06:50 +00001657void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001658 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001659 assert(BasePathArray.empty() && "Base path array must be empty!");
1660 assert(Paths.isRecordingPaths() && "Must record paths!");
1661
1662 const CXXBasePath &Path = Paths.front();
1663
1664 // We first go backward and check if we have a virtual base.
1665 // FIXME: It would be better if CXXBasePath had the base specifier for
1666 // the nearest virtual base.
1667 unsigned Start = 0;
1668 for (unsigned I = Path.size(); I != 0; --I) {
1669 if (Path[I - 1].Base->isVirtual()) {
1670 Start = I - 1;
1671 break;
1672 }
1673 }
1674
1675 // Now add all bases.
1676 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001677 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001678}
1679
Douglas Gregor88d292c2010-05-13 16:44:06 +00001680/// \brief Determine whether the given base path includes a virtual
1681/// base class.
John McCallcf142162010-08-07 06:22:56 +00001682bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1683 for (CXXCastPath::const_iterator B = BasePath.begin(),
1684 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +00001685 B != BEnd; ++B)
1686 if ((*B)->isVirtual())
1687 return true;
1688
1689 return false;
1690}
1691
Douglas Gregor36d1b142009-10-06 17:59:45 +00001692/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1693/// conversion (where Derived and Base are class types) is
1694/// well-formed, meaning that the conversion is unambiguous (and
1695/// that all of the base classes are accessible). Returns true
1696/// and emits a diagnostic if the code is ill-formed, returns false
1697/// otherwise. Loc is the location where this routine should point to
1698/// if there is an error, and Range is the source range to highlight
1699/// if there is an error.
1700bool
1701Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001702 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001703 unsigned AmbigiousBaseConvID,
1704 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001705 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001706 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001707 // First, determine whether the path from Derived to Base is
1708 // ambiguous. This is slightly more expensive than checking whether
1709 // the Derived to Base conversion exists, because here we need to
1710 // explore multiple paths to determine if there is an ambiguity.
1711 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1712 /*DetectVirtual=*/false);
1713 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1714 assert(DerivationOkay &&
1715 "Can only be used with a derived-to-base conversion");
1716 (void)DerivationOkay;
1717
1718 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001719 if (InaccessibleBaseID) {
1720 // Check that the base class can be accessed.
1721 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1722 InaccessibleBaseID)) {
1723 case AR_inaccessible:
1724 return true;
1725 case AR_accessible:
1726 case AR_dependent:
1727 case AR_delayed:
1728 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001729 }
John McCall5b0829a2010-02-10 09:31:12 +00001730 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001731
1732 // Build a base path if necessary.
1733 if (BasePath)
1734 BuildBasePathArray(Paths, *BasePath);
1735 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001736 }
1737
David Majnemer626032f2013-06-22 06:43:58 +00001738 if (AmbigiousBaseConvID) {
1739 // We know that the derived-to-base conversion is ambiguous, and
1740 // we're going to produce a diagnostic. Perform the derived-to-base
1741 // search just one more time to compute all of the possible paths so
1742 // that we can print them out. This is more expensive than any of
1743 // the previous derived-to-base checks we've done, but at this point
1744 // performance isn't as much of an issue.
1745 Paths.clear();
1746 Paths.setRecordingPaths(true);
1747 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1748 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1749 (void)StillOkay;
1750
1751 // Build up a textual representation of the ambiguous paths, e.g.,
1752 // D -> B -> A, that will be used to illustrate the ambiguous
1753 // conversions in the diagnostic. We only print one of the paths
1754 // to each base class subobject.
1755 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1756
1757 Diag(Loc, AmbigiousBaseConvID)
1758 << Derived << Base << PathDisplayStr << Range << Name;
1759 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00001760 return true;
1761}
1762
1763bool
1764Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001765 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001766 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001767 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001768 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001769 IgnoreAccess ? 0
1770 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001771 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001772 Loc, Range, DeclarationName(),
1773 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001774}
1775
1776
1777/// @brief Builds a string representing ambiguous paths from a
1778/// specific derived class to different subobjects of the same base
1779/// class.
1780///
1781/// This function builds a string that can be used in error messages
1782/// to show the different paths that one can take through the
1783/// inheritance hierarchy to go from the derived class to different
1784/// subobjects of a base class. The result looks something like this:
1785/// @code
1786/// struct D -> struct B -> struct A
1787/// struct D -> struct C -> struct A
1788/// @endcode
1789std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1790 std::string PathDisplayStr;
1791 std::set<unsigned> DisplayedPaths;
1792 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1793 Path != Paths.end(); ++Path) {
1794 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1795 // We haven't displayed a path to this particular base
1796 // class subobject yet.
1797 PathDisplayStr += "\n ";
1798 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1799 for (CXXBasePath::const_iterator Element = Path->begin();
1800 Element != Path->end(); ++Element)
1801 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1802 }
1803 }
1804
1805 return PathDisplayStr;
1806}
1807
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001808//===----------------------------------------------------------------------===//
1809// C++ class member Handling
1810//===----------------------------------------------------------------------===//
1811
Abramo Bagnarad7340582010-06-05 05:09:32 +00001812/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001813bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1814 SourceLocation ASLoc,
1815 SourceLocation ColonLoc,
1816 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001817 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001818 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001819 ASLoc, ColonLoc);
1820 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001821 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001822}
1823
Richard Smith18f07db2012-08-06 03:25:17 +00001824/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001825void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00001826 if (D->isInvalidDecl())
1827 return;
1828
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001829 // We only care about "override" and "final" declarations.
1830 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1831 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00001832
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001833 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001834
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001835 // We can't check dependent instance methods.
1836 if (MD && MD->isInstance() &&
1837 (MD->getParent()->hasAnyDependentBases() ||
1838 MD->getType()->isDependentType()))
1839 return;
1840
1841 if (MD && !MD->isVirtual()) {
1842 // If we have a non-virtual method, check if if hides a virtual method.
1843 // (In that case, it's most likely the method has the wrong type.)
1844 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1845 FindHiddenVirtualMethods(MD, OverloadedMethods);
1846
1847 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001848 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1849 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001850 diag::override_keyword_hides_virtual_member_function)
1851 << "override" << (OverloadedMethods.size() > 1);
1852 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001853 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001854 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00001855 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1856 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00001857 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001858 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1859 MD->setInvalidDecl();
1860 return;
1861 }
1862 // Fall through into the general case diagnostic.
1863 // FIXME: We might want to attempt typo correction here.
1864 }
1865
1866 if (!MD || !MD->isVirtual()) {
1867 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1868 Diag(OA->getLocation(),
1869 diag::override_keyword_only_allowed_on_virtual_member_functions)
1870 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1871 D->dropAttr<OverrideAttr>();
1872 }
1873 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1874 Diag(FA->getLocation(),
1875 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00001876 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1877 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001878 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00001879 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001880 return;
1881 }
Richard Smith18f07db2012-08-06 03:25:17 +00001882
Richard Smith18f07db2012-08-06 03:25:17 +00001883 // C++11 [class.virtual]p5:
1884 // If a virtual function is marked with the virt-specifier override and
1885 // does not override a member function of a base class, the program is
1886 // ill-formed.
1887 bool HasOverriddenMethods =
1888 MD->begin_overridden_methods() != MD->end_overridden_methods();
1889 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1890 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1891 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00001892}
1893
Richard Smith18f07db2012-08-06 03:25:17 +00001894/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00001895/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00001896/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00001897bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1898 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00001899 FinalAttr *FA = Old->getAttr<FinalAttr>();
1900 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00001901 return false;
1902
1903 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00001904 << New->getDeclName()
1905 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00001906 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1907 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001908}
1909
Daniel Jasper0baec5492012-06-06 08:32:04 +00001910static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00001911 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1912 // FIXME: Destruction of ObjC lifetime types has side-effects.
1913 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1914 return !RD->isCompleteDefinition() ||
1915 !RD->hasTrivialDefaultConstructor() ||
1916 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00001917 return false;
1918}
1919
John McCall5e77d762013-04-16 07:28:30 +00001920static AttributeList *getMSPropertyAttr(AttributeList *list) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001921 for (AttributeList *it = list; it != nullptr; it = it->getNext())
John McCall5e77d762013-04-16 07:28:30 +00001922 if (it->isDeclspecPropertyAttribute())
1923 return it;
Craig Topperc3ec1492014-05-26 06:22:03 +00001924 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +00001925}
1926
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001927/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1928/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001929/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00001930/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1931/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001932NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001933Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001934 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001935 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00001936 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001937 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001938 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1939 DeclarationName Name = NameInfo.getName();
1940 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001941
1942 // For anonymous bitfields, the location should point to the type.
1943 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001944 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001945
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001946 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001947
John McCallb1cd7da2010-06-04 08:34:12 +00001948 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001949 assert(!DS.isFriendSpecified());
1950
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001951 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001952
John McCalldb632ac2012-09-25 07:32:39 +00001953 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1954 // The Microsoft extension __interface only permits public member functions
1955 // and prohibits constructors, destructors, operators, non-public member
1956 // functions, static methods and data members.
1957 unsigned InvalidDecl;
1958 bool ShowDeclName = true;
1959 if (!isFunc)
1960 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1961 else if (AS != AS_public)
1962 InvalidDecl = 2;
1963 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1964 InvalidDecl = 3;
1965 else switch (Name.getNameKind()) {
1966 case DeclarationName::CXXConstructorName:
1967 InvalidDecl = 4;
1968 ShowDeclName = false;
1969 break;
1970
1971 case DeclarationName::CXXDestructorName:
1972 InvalidDecl = 5;
1973 ShowDeclName = false;
1974 break;
1975
1976 case DeclarationName::CXXOperatorName:
1977 case DeclarationName::CXXConversionFunctionName:
1978 InvalidDecl = 6;
1979 break;
1980
1981 default:
1982 InvalidDecl = 0;
1983 break;
1984 }
1985
1986 if (InvalidDecl) {
1987 if (ShowDeclName)
1988 Diag(Loc, diag::err_invalid_member_in_interface)
1989 << (InvalidDecl-1) << Name;
1990 else
1991 Diag(Loc, diag::err_invalid_member_in_interface)
1992 << (InvalidDecl-1) << "";
Craig Topperc3ec1492014-05-26 06:22:03 +00001993 return nullptr;
John McCalldb632ac2012-09-25 07:32:39 +00001994 }
1995 }
1996
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001997 // C++ 9.2p6: A member shall not be declared to have automatic storage
1998 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001999 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2000 // data members and cannot be applied to names declared const or static,
2001 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002002 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00002003 case DeclSpec::SCS_unspecified:
2004 case DeclSpec::SCS_typedef:
2005 case DeclSpec::SCS_static:
2006 break;
2007 case DeclSpec::SCS_mutable:
2008 if (isFunc) {
2009 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00002010
Richard Smithb4a9e862013-04-12 22:46:28 +00002011 // FIXME: It would be nicer if the keyword was ignored only for this
2012 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002013 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00002014 }
2015 break;
2016 default:
2017 Diag(DS.getStorageClassSpecLoc(),
2018 diag::err_storageclass_invalid_for_member);
2019 D.getMutableDeclSpec().ClearStorageClassSpecs();
2020 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002021 }
2022
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002023 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2024 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00002025 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002026
David Blaikie35506f82013-01-30 01:22:18 +00002027 if (DS.isConstexprSpecified() && isInstField) {
2028 SemaDiagnosticBuilder B =
2029 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2030 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2031 if (InitStyle == ICIS_NoInit) {
Richard Smith82dce552014-04-14 21:00:40 +00002032 B << 0 << 0;
2033 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2034 B << FixItHint::CreateRemoval(ConstexprLoc);
2035 else {
2036 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2037 D.getMutableDeclSpec().ClearConstexprSpec();
2038 const char *PrevSpec;
2039 unsigned DiagID;
2040 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2041 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2042 (void)Failed;
2043 assert(!Failed && "Making a constexpr member const shouldn't fail");
2044 }
David Blaikie35506f82013-01-30 01:22:18 +00002045 } else {
2046 B << 1;
2047 const char *PrevSpec;
2048 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00002049 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002050 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2051 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00002052 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00002053 "This is the only DeclSpec that should fail to be applied");
2054 B << 1;
2055 } else {
2056 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2057 isInstField = false;
2058 }
2059 }
2060 }
2061
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002062 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00002063 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00002064 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002065
2066 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00002067 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002068 Diag(Loc, diag::err_bad_variable_name)
2069 << Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002070 return nullptr;
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002071 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002072
Benjamin Kramer365082d2012-05-19 16:34:46 +00002073 IdentifierInfo *II = Name.getAsIdentifierInfo();
2074
Douglas Gregor7c26c042011-09-21 14:40:46 +00002075 // Member field could not be with "template" keyword.
2076 // So TemplateParameterLists should be empty in this case.
2077 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002078 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002079 if (TemplateParams->size()) {
2080 // There is no such thing as a member field template.
2081 Diag(D.getIdentifierLoc(), diag::err_template_member)
2082 << II
2083 << SourceRange(TemplateParams->getTemplateLoc(),
2084 TemplateParams->getRAngleLoc());
2085 } else {
2086 // There is an extraneous 'template<>' for this member.
2087 Diag(TemplateParams->getTemplateLoc(),
2088 diag::err_template_member_noparams)
2089 << II
2090 << SourceRange(TemplateParams->getTemplateLoc(),
2091 TemplateParams->getRAngleLoc());
2092 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002093 return nullptr;
Douglas Gregor7c26c042011-09-21 14:40:46 +00002094 }
2095
Douglas Gregora007d362010-10-13 22:19:53 +00002096 if (SS.isSet() && !SS.isInvalid()) {
2097 // The user provided a superfluous scope specifier inside a class
2098 // definition:
2099 //
2100 // class X {
2101 // int X::member;
2102 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002103 if (DeclContext *DC = computeDeclContext(SS, false))
2104 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002105 else
2106 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2107 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002108
Douglas Gregora007d362010-10-13 22:19:53 +00002109 SS.clear();
2110 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002111
John McCall5e77d762013-04-16 07:28:30 +00002112 AttributeList *MSPropertyAttr =
2113 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002114 if (MSPropertyAttr) {
2115 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2116 BitWidth, InitStyle, AS, MSPropertyAttr);
2117 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002118 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002119 isInstField = false;
2120 } else {
2121 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2122 BitWidth, InitStyle, AS);
2123 assert(Member && "HandleField never returns null");
2124 }
2125 } else {
2126 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2127
2128 Member = HandleDeclarator(S, D, TemplateParameterLists);
2129 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002130 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002131
2132 // Non-instance-fields can't have a bitfield.
2133 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002134 if (Member->isInvalidDecl()) {
2135 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00002136 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002137 // C++ 9.6p3: A bit-field shall not be a static member.
2138 // "static member 'A' cannot be a bit-field"
2139 Diag(Loc, diag::err_static_not_bitfield)
2140 << Name << BitWidth->getSourceRange();
2141 } else if (isa<TypedefDecl>(Member)) {
2142 // "typedef member 'x' cannot be a bit-field"
2143 Diag(Loc, diag::err_typedef_not_bitfield)
2144 << Name << BitWidth->getSourceRange();
2145 } else {
2146 // A function typedef ("typedef int f(); f a;").
2147 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2148 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002149 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002150 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002151 }
Mike Stump11289f42009-09-09 15:08:12 +00002152
Craig Topperc3ec1492014-05-26 06:22:03 +00002153 BitWidth = nullptr;
Chris Lattnerd26760a2009-03-05 23:01:03 +00002154 Member->setInvalidDecl();
2155 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002156
2157 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002158
Larisse Voufo39a1e502013-08-06 01:03:05 +00002159 // If we have declared a member function template or static data member
2160 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002161 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2162 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002163 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2164 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00002165 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002166
Richard Smith18f07db2012-08-06 03:25:17 +00002167 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00002168 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00002169 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00002170 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2171 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00002172
Douglas Gregorf2f08062011-03-08 17:10:18 +00002173 if (VS.getLastLocation().isValid()) {
2174 // Update the end location of a method that has a virt-specifiers.
2175 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2176 MD->setRangeEnd(VS.getLastLocation());
2177 }
Richard Smith18f07db2012-08-06 03:25:17 +00002178
Anders Carlssonc87f8612011-01-20 06:29:02 +00002179 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00002180
Douglas Gregor92751d42008-11-17 22:58:34 +00002181 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002182
Daniel Jasper0baec5492012-06-06 08:32:04 +00002183 if (isInstField) {
2184 FieldDecl *FD = cast<FieldDecl>(Member);
2185 FieldCollector->Add(FD);
2186
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002187 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
Daniel Jasper0baec5492012-06-06 08:32:04 +00002188 // Remember all explicit private FieldDecls that have a name, no side
2189 // effects and are not part of a dependent type declaration.
2190 if (!FD->isImplicit() && FD->getDeclName() &&
2191 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00002192 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00002193 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00002194 !InitializationHasSideEffects(*FD))
2195 UnusedPrivateFields.insert(FD);
2196 }
2197 }
2198
John McCall48871652010-08-21 09:40:31 +00002199 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002200}
2201
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002202namespace {
2203 class UninitializedFieldVisitor
2204 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2205 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00002206 // List of Decls to generate a warning on. Also remove Decls that become
2207 // initialized.
Craig Topper4dd9b432014-08-17 23:49:53 +00002208 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
Richard Trieu406e65c2013-09-20 03:03:06 +00002209 // If non-null, add a note to the warning pointing back to the constructor.
2210 const CXXConstructorDecl *Constructor;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002211 public:
2212 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00002213 UninitializedFieldVisitor(Sema &S,
Craig Topper4dd9b432014-08-17 23:49:53 +00002214 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
Richard Trieu406e65c2013-09-20 03:03:06 +00002215 const CXXConstructorDecl *Constructor)
Richard Trieuef64e942013-10-25 00:56:00 +00002216 : Inherited(S.Context), S(S), Decls(Decls),
2217 Constructor(Constructor) { }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002218
Richard Trieufd687772013-09-16 20:46:50 +00002219 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002220 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2221 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002222
Richard Trieu1bc22c12013-09-13 03:20:53 +00002223 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2224 // or union.
2225 MemberExpr *FieldME = ME;
2226
2227 Expr *Base = ME;
2228 while (isa<MemberExpr>(Base)) {
2229 ME = cast<MemberExpr>(Base);
2230
2231 if (isa<VarDecl>(ME->getMemberDecl()))
2232 return;
2233
2234 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2235 if (!FD->isAnonymousStructOrUnion())
2236 FieldME = ME;
2237
2238 Base = ME->getBase();
2239 }
2240
Richard Trieufd687772013-09-16 20:46:50 +00002241 if (!isa<CXXThisExpr>(Base))
2242 return;
2243
Richard Trieu406e65c2013-09-20 03:03:06 +00002244 ValueDecl* FoundVD = FieldME->getMemberDecl();
2245
Richard Trieuef64e942013-10-25 00:56:00 +00002246 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00002247 return;
2248
Richard Trieuef64e942013-10-25 00:56:00 +00002249 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00002250
Richard Trieuef64e942013-10-25 00:56:00 +00002251 // Prevent double warnings on use of unbounded references.
2252 if (IsReference != CheckReferenceOnly)
2253 return;
2254
2255 unsigned diag = IsReference
2256 ? diag::warn_reference_field_is_uninit
2257 : diag::warn_field_is_uninit;
2258 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2259 if (Constructor)
2260 S.Diag(Constructor->getLocation(),
2261 diag::note_uninit_in_this_constructor)
2262 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2263
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002264 }
2265
2266 void HandleValue(Expr *E) {
2267 E = E->IgnoreParens();
2268
2269 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieufd687772013-09-16 20:46:50 +00002270 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002271 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002272 }
2273
2274 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2275 HandleValue(CO->getTrueExpr());
2276 HandleValue(CO->getFalseExpr());
2277 return;
2278 }
2279
2280 if (BinaryConditionalOperator *BCO =
2281 dyn_cast<BinaryConditionalOperator>(E)) {
2282 HandleValue(BCO->getCommon());
2283 HandleValue(BCO->getFalseExpr());
2284 return;
2285 }
2286
2287 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2288 switch (BO->getOpcode()) {
2289 default:
2290 return;
2291 case(BO_PtrMemD):
2292 case(BO_PtrMemI):
2293 HandleValue(BO->getLHS());
2294 return;
2295 case(BO_Comma):
2296 HandleValue(BO->getRHS());
2297 return;
2298 }
2299 }
2300 }
2301
Richard Trieu1bc22c12013-09-13 03:20:53 +00002302 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00002303 // All uses of unbounded reference fields will warn.
Richard Trieufd687772013-09-16 20:46:50 +00002304 HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002305
2306 Inherited::VisitMemberExpr(ME);
2307 }
2308
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002309 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2310 if (E->getCastKind() == CK_LValueToRValue)
2311 HandleValue(E->getSubExpr());
2312
2313 Inherited::VisitImplicitCastExpr(E);
2314 }
2315
Richard Trieu1bc22c12013-09-13 03:20:53 +00002316 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu4834ad22014-08-12 21:05:04 +00002317 if (E->getConstructor()->isCopyConstructor()) {
2318 Expr *ArgExpr = E->getArg(0);
2319 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) {
2320 if (ICE->getCastKind() == CK_NoOp) {
2321 ArgExpr = ICE->getSubExpr();
2322 }
2323 }
2324
2325 if (MemberExpr *ME = dyn_cast<MemberExpr>(ArgExpr)) {
2326 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
2327 }
2328 }
Richard Trieu1bc22c12013-09-13 03:20:53 +00002329 Inherited::VisitCXXConstructExpr(E);
2330 }
2331
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002332 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2333 Expr *Callee = E->getCallee();
2334 if (isa<MemberExpr>(Callee))
2335 HandleValue(Callee);
2336
2337 Inherited::VisitCXXMemberCallExpr(E);
2338 }
Richard Trieu406e65c2013-09-20 03:03:06 +00002339
2340 void VisitBinaryOperator(BinaryOperator *E) {
2341 // If a field assignment is detected, remove the field from the
2342 // uninitiailized field set.
2343 if (E->getOpcode() == BO_Assign)
2344 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2345 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00002346 if (!FD->getType()->isReferenceType())
2347 Decls.erase(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00002348
2349 Inherited::VisitBinaryOperator(E);
2350 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002351 };
Richard Trieu406e65c2013-09-20 03:03:06 +00002352 static void CheckInitExprContainsUninitializedFields(
Craig Topper4dd9b432014-08-17 23:49:53 +00002353 Sema &S, Expr *E, llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
Richard Trieuef64e942013-10-25 00:56:00 +00002354 const CXXConstructorDecl *Constructor) {
2355 if (Decls.size() == 0)
Richard Trieu406e65c2013-09-20 03:03:06 +00002356 return;
2357
Richard Trieuef64e942013-10-25 00:56:00 +00002358 if (!E)
2359 return;
2360
2361 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) {
2362 E = Default->getExpr();
2363 if (!E)
2364 return;
2365 // In class initializers will point to the constructor.
2366 UninitializedFieldVisitor(S, Decls, Constructor).Visit(E);
2367 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00002368 UninitializedFieldVisitor(S, Decls, nullptr).Visit(E);
Richard Trieuef64e942013-10-25 00:56:00 +00002369 }
2370 }
2371
2372 // Diagnose value-uses of fields to initialize themselves, e.g.
2373 // foo(foo)
2374 // where foo is not also a parameter to the constructor.
2375 // Also diagnose across field uninitialized use such as
2376 // x(y), y(x)
2377 // TODO: implement -Wuninitialized and fold this into that framework.
2378 static void DiagnoseUninitializedFields(
2379 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2380
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002381 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2382 Constructor->getLocation())) {
Richard Trieuef64e942013-10-25 00:56:00 +00002383 return;
2384 }
2385
2386 if (Constructor->isInvalidDecl())
2387 return;
2388
2389 const CXXRecordDecl *RD = Constructor->getParent();
2390
2391 // Holds fields that are uninitialized.
2392 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2393
2394 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00002395 for (auto *I : RD->decls()) {
2396 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002397 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00002398 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002399 UninitializedFields.insert(IFD->getAnonField());
2400 }
2401 }
2402
Aaron Ballman0ad78302014-03-13 17:34:31 +00002403 for (const auto *FieldInit : Constructor->inits()) {
2404 Expr *InitExpr = FieldInit->getInit();
Richard Trieuef64e942013-10-25 00:56:00 +00002405
2406 CheckInitExprContainsUninitializedFields(
2407 SemaRef, InitExpr, UninitializedFields, Constructor);
2408
Aaron Ballman0ad78302014-03-13 17:34:31 +00002409 if (FieldDecl *Field = FieldInit->getAnyMember())
Richard Trieuef64e942013-10-25 00:56:00 +00002410 UninitializedFields.erase(Field);
2411 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002412 }
2413} // namespace
2414
Richard Smith74108172014-01-17 03:11:34 +00002415/// \brief Enter a new C++ default initializer scope. After calling this, the
2416/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2417/// parsing or instantiating the initializer failed.
2418void Sema::ActOnStartCXXInClassMemberInitializer() {
2419 // Create a synthetic function scope to represent the call to the constructor
2420 // that notionally surrounds a use of this initializer.
2421 PushFunctionScope();
2422}
2423
2424/// \brief This is invoked after parsing an in-class initializer for a
2425/// non-static C++ class member, and after instantiating an in-class initializer
2426/// in a class template. Such actions are deferred until the class is complete.
2427void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2428 SourceLocation InitLoc,
2429 Expr *InitExpr) {
2430 // Pop the notional constructor scope we created earlier.
Craig Topperc3ec1492014-05-26 06:22:03 +00002431 PopFunctionScopeInfo(nullptr, D);
Richard Smith74108172014-01-17 03:11:34 +00002432
Richard Smith938f40b2011-06-11 17:19:42 +00002433 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smith2b013182012-06-10 03:12:00 +00002434 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2435 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00002436
2437 if (!InitExpr) {
2438 FD->setInvalidDecl();
2439 FD->removeInClassInitializer();
2440 return;
2441 }
2442
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002443 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2444 FD->setInvalidDecl();
2445 FD->removeInClassInitializer();
2446 return;
2447 }
2448
Richard Smith938f40b2011-06-11 17:19:42 +00002449 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00002450 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002451 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00002452 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00002453 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00002454 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002455 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2456 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00002457 if (Init.isInvalid()) {
2458 FD->setInvalidDecl();
2459 return;
2460 }
Richard Smith938f40b2011-06-11 17:19:42 +00002461 }
2462
Richard Smith945f8d32013-01-14 22:39:08 +00002463 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00002464 // The initialization of each base and member constitutes a
2465 // full-expression.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002466 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00002467 if (Init.isInvalid()) {
2468 FD->setInvalidDecl();
2469 return;
2470 }
2471
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002472 InitExpr = Init.get();
Richard Smith938f40b2011-06-11 17:19:42 +00002473
2474 FD->setInClassInitializer(InitExpr);
2475}
2476
Douglas Gregor15e77a22009-12-31 09:10:24 +00002477/// \brief Find the direct and/or virtual base specifiers that
2478/// correspond to the given base type, for use in base initialization
2479/// within a constructor.
2480static bool FindBaseInitializer(Sema &SemaRef,
2481 CXXRecordDecl *ClassDecl,
2482 QualType BaseType,
2483 const CXXBaseSpecifier *&DirectBaseSpec,
2484 const CXXBaseSpecifier *&VirtualBaseSpec) {
2485 // First, check for a direct base class.
Craig Topperc3ec1492014-05-26 06:22:03 +00002486 DirectBaseSpec = nullptr;
Aaron Ballman574705e2014-03-13 15:41:46 +00002487 for (const auto &Base : ClassDecl->bases()) {
2488 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002489 // We found a direct base of this type. That's what we're
2490 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00002491 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002492 break;
2493 }
2494 }
2495
2496 // Check for a virtual base class.
2497 // FIXME: We might be able to short-circuit this if we know in advance that
2498 // there are no virtual bases.
Craig Topperc3ec1492014-05-26 06:22:03 +00002499 VirtualBaseSpec = nullptr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002500 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2501 // We haven't found a base yet; search the class hierarchy for a
2502 // virtual base class.
2503 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2504 /*DetectVirtual=*/false);
2505 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2506 BaseType, Paths)) {
2507 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2508 Path != Paths.end(); ++Path) {
2509 if (Path->back().Base->isVirtual()) {
2510 VirtualBaseSpec = Path->back().Base;
2511 break;
2512 }
2513 }
2514 }
2515 }
2516
2517 return DirectBaseSpec || VirtualBaseSpec;
2518}
2519
Sebastian Redla74948d2011-09-24 17:48:25 +00002520/// \brief Handle a C++ member initializer using braced-init-list syntax.
2521MemInitResult
2522Sema::ActOnMemInitializer(Decl *ConstructorD,
2523 Scope *S,
2524 CXXScopeSpec &SS,
2525 IdentifierInfo *MemberOrBase,
2526 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002527 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002528 SourceLocation IdLoc,
2529 Expr *InitList,
2530 SourceLocation EllipsisLoc) {
2531 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002532 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00002533 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002534}
2535
2536/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00002537MemInitResult
John McCall48871652010-08-21 09:40:31 +00002538Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00002539 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002540 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002541 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00002542 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002543 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002544 SourceLocation IdLoc,
2545 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002546 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002547 SourceLocation RParenLoc,
2548 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00002549 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002550 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002551 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002552 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002553}
2554
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002555namespace {
2556
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00002557// Callback to only accept typo corrections that can be a valid C++ member
2558// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002559class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002560public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002561 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2562 : ClassDecl(ClassDecl) {}
2563
Craig Toppera798a9d2014-03-02 09:32:10 +00002564 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002565 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2566 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2567 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002568 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002569 }
2570 return false;
2571 }
2572
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002573private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002574 CXXRecordDecl *ClassDecl;
2575};
2576
2577}
2578
Sebastian Redla74948d2011-09-24 17:48:25 +00002579/// \brief Handle a C++ member initializer.
2580MemInitResult
2581Sema::BuildMemInitializer(Decl *ConstructorD,
2582 Scope *S,
2583 CXXScopeSpec &SS,
2584 IdentifierInfo *MemberOrBase,
2585 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002586 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002587 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00002588 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002589 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002590 if (!ConstructorD)
2591 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002592
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002593 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00002594
2595 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002596 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00002597 if (!Constructor) {
2598 // The user wrote a constructor initializer on a function that is
2599 // not a C++ constructor. Ignore the error for now, because we may
2600 // have more member initializers coming; we'll diagnose it just
2601 // once in ActOnMemInitializers.
2602 return true;
2603 }
2604
2605 CXXRecordDecl *ClassDecl = Constructor->getParent();
2606
2607 // C++ [class.base.init]p2:
2608 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00002609 // constructor's class and, if not found in that scope, are looked
2610 // up in the scope containing the constructor's definition.
2611 // [Note: if the constructor's class contains a member with the
2612 // same name as a direct or virtual base class of the class, a
2613 // mem-initializer-id naming the member or base class and composed
2614 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00002615 // mem-initializer-id for the hidden base class may be specified
2616 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00002617 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002618 // Look for a member, first.
Mike Stump11289f42009-09-09 15:08:12 +00002619 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002620 = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00002621 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00002622 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00002623 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2624 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00002625 if (EllipsisLoc.isValid())
2626 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00002627 << MemberOrBase
2628 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002629
Sebastian Redla9351792012-02-11 23:51:47 +00002630 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00002631 }
Francois Pichetd583da02010-12-04 09:14:42 +00002632 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002633 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002634 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002635 QualType BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002636 TypeSourceInfo *TInfo = nullptr;
John McCallb5a0d312009-12-21 10:41:20 +00002637
2638 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00002639 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00002640 } else if (DS.getTypeSpecType() == TST_decltype) {
2641 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00002642 } else {
2643 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2644 LookupParsedName(R, S, &SS);
2645
2646 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2647 if (!TyD) {
2648 if (R.isAmbiguous()) return true;
2649
John McCallda6841b2010-04-09 19:01:14 +00002650 // We don't want access-control diagnostics here.
2651 R.suppressDiagnostics();
2652
Douglas Gregora3b624a2010-01-19 06:46:48 +00002653 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2654 bool NotUnknownSpecialization = false;
2655 DeclContext *DC = computeDeclContext(SS, false);
2656 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2657 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2658
2659 if (!NotUnknownSpecialization) {
2660 // When the scope specifier can refer to a member of an unknown
2661 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00002662 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2663 SS.getWithLocInContext(Context),
2664 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00002665 if (BaseType.isNull())
2666 return true;
2667
Douglas Gregora3b624a2010-01-19 06:46:48 +00002668 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002669 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002670 }
2671 }
2672
Douglas Gregor15e77a22009-12-31 09:10:24 +00002673 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002674 TypoCorrection Corr;
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002675 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002676 if (R.empty() && BaseType.isNull() &&
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002677 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
John Thompson2255f2c2014-04-23 12:57:01 +00002678 Validator, CTK_ErrorRecovery, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002679 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002680 // We have found a non-static data member with a similar
2681 // name to what was typed; complain and initialize that
2682 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00002683 diagnoseTypo(Corr,
2684 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2685 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00002686 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002687 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002688 const CXXBaseSpecifier *DirectBaseSpec;
2689 const CXXBaseSpecifier *VirtualBaseSpec;
2690 if (FindBaseInitializer(*this, ClassDecl,
2691 Context.getTypeDeclType(Type),
2692 DirectBaseSpec, VirtualBaseSpec)) {
2693 // We have found a direct or virtual base class with a
2694 // similar name to what was typed; complain and initialize
2695 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00002696 diagnoseTypo(Corr,
2697 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2698 << MemberOrBase << false,
2699 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00002700
Richard Smithf9b15102013-08-17 00:46:16 +00002701 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2702 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002703 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00002704 diag::note_base_class_specified_here)
2705 << BaseSpec->getType()
2706 << BaseSpec->getSourceRange();
2707
Douglas Gregor15e77a22009-12-31 09:10:24 +00002708 TyD = Type;
2709 }
2710 }
2711 }
2712
Douglas Gregora3b624a2010-01-19 06:46:48 +00002713 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002714 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00002715 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00002716 return true;
2717 }
John McCallb5a0d312009-12-21 10:41:20 +00002718 }
2719
Douglas Gregora3b624a2010-01-19 06:46:48 +00002720 if (BaseType.isNull()) {
2721 BaseType = Context.getTypeDeclType(TyD);
Aaron Ballman4a979672014-01-03 13:56:08 +00002722 if (SS.isSet())
Douglas Gregora3b624a2010-01-19 06:46:48 +00002723 // FIXME: preserve source range information
Aaron Ballman4a979672014-01-03 13:56:08 +00002724 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2725 BaseType);
John McCallb5a0d312009-12-21 10:41:20 +00002726 }
2727 }
Mike Stump11289f42009-09-09 15:08:12 +00002728
John McCallbcd03502009-12-07 02:54:59 +00002729 if (!TInfo)
2730 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002731
Sebastian Redla9351792012-02-11 23:51:47 +00002732 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00002733}
2734
Chandler Carruth599deef2011-09-03 01:14:15 +00002735/// Checks a member initializer expression for cases where reference (or
2736/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00002737static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2738 Expr *Init,
2739 SourceLocation IdLoc) {
2740 QualType MemberTy = Member->getType();
2741
2742 // We only handle pointers and references currently.
2743 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2744 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2745 return;
2746
2747 const bool IsPointer = MemberTy->isPointerType();
2748 if (IsPointer) {
2749 if (const UnaryOperator *Op
2750 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2751 // The only case we're worried about with pointers requires taking the
2752 // address.
2753 if (Op->getOpcode() != UO_AddrOf)
2754 return;
2755
2756 Init = Op->getSubExpr();
2757 } else {
2758 // We only handle address-of expression initializers for pointers.
2759 return;
2760 }
2761 }
2762
Richard Smithe3b28bc2013-06-12 21:51:50 +00002763 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002764 // We only warn when referring to a non-reference parameter declaration.
2765 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2766 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00002767 return;
2768
2769 S.Diag(Init->getExprLoc(),
2770 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2771 : diag::warn_bind_ref_member_to_parameter)
2772 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002773 } else {
2774 // Other initializers are fine.
2775 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00002776 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002777
2778 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2779 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00002780}
2781
John McCallfaf5fb42010-08-26 23:41:50 +00002782MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002783Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002784 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002785 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2786 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2787 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00002788 "Member must be a FieldDecl or IndirectFieldDecl");
2789
Sebastian Redla9351792012-02-11 23:51:47 +00002790 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002791 return true;
2792
Douglas Gregor266bb5f2010-11-05 22:21:31 +00002793 if (Member->isInvalidDecl())
2794 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00002795
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002796 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00002797 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002798 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00002799 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002800 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00002801 } else {
2802 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002803 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002804 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00002805
Sebastian Redla9351792012-02-11 23:51:47 +00002806 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002807
Sebastian Redla9351792012-02-11 23:51:47 +00002808 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002809 // Can't check initialization for a member of dependent type or when
2810 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00002811 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00002812 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00002813 bool InitList = false;
2814 if (isa<InitListExpr>(Init)) {
2815 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002816 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002817 }
2818
Chandler Carruthd44c3102010-12-06 09:23:57 +00002819 // Initialize the member.
2820 InitializedEntity MemberEntity =
Craig Topperc3ec1492014-05-26 06:22:03 +00002821 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
2822 : InitializedEntity::InitializeMember(IndirectMember,
2823 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002824 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002825 InitList ? InitializationKind::CreateDirectList(IdLoc)
2826 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2827 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00002828
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002829 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00002830 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
2831 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002832 if (MemberInit.isInvalid())
2833 return true;
2834
Richard Smith736a9472013-06-12 20:42:33 +00002835 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2836
Richard Smith945f8d32013-01-14 22:39:08 +00002837 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00002838 // The initialization of each base and member constitutes a
2839 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002840 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002841 if (MemberInit.isInvalid())
2842 return true;
2843
Richard Smithd59b8322012-12-19 01:39:02 +00002844 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002845 }
2846
Chandler Carruthd44c3102010-12-06 09:23:57 +00002847 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00002848 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2849 InitRange.getBegin(), Init,
2850 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002851 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00002852 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2853 InitRange.getBegin(), Init,
2854 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002855 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00002856}
2857
John McCallfaf5fb42010-08-26 23:41:50 +00002858MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002859Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002860 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002861 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002862 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002863 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002864 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002865 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00002866
Sebastian Redl0501c632012-02-12 16:37:36 +00002867 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002868 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002869 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2870 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002871 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00002872 }
2873
Sebastian Redla9351792012-02-11 23:51:47 +00002874 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00002875 // Initialize the object.
2876 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2877 QualType(ClassDecl->getTypeForDecl(), 0));
2878 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002879 InitList ? InitializationKind::CreateDirectList(NameLoc)
2880 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2881 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002882 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00002883 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Craig Topperc3ec1492014-05-26 06:22:03 +00002884 Args, nullptr);
Alexis Huntc5575cc2011-02-26 19:13:13 +00002885 if (DelegationInit.isInvalid())
2886 return true;
2887
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00002888 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2889 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00002890
Richard Smith945f8d32013-01-14 22:39:08 +00002891 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00002892 // The initialization of each base and member constitutes a
2893 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002894 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2895 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002896 if (DelegationInit.isInvalid())
2897 return true;
2898
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00002899 // If we are in a dependent context, template instantiation will
2900 // perform this type-checking again. Just save the arguments that we
2901 // received in a ParenListExpr.
2902 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2903 // of the information that we have about the base
2904 // initializer. However, deconstructing the ASTs is a dicey process,
2905 // and this approach is far more likely to get the corner cases right.
2906 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002907 DelegationInit = Init;
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00002908
Sebastian Redla9351792012-02-11 23:51:47 +00002909 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002910 DelegationInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002911 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002912}
2913
2914MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00002915Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00002916 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002917 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002918 SourceLocation BaseLoc
2919 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00002920
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002921 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2922 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2923 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2924
2925 // C++ [class.base.init]p2:
2926 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00002927 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002928 // of that class, the mem-initializer is ill-formed. A
2929 // mem-initializer-list can initialize a base class using any
2930 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00002931 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002932
Sebastian Redla9351792012-02-11 23:51:47 +00002933 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00002934 if (EllipsisLoc.isValid()) {
2935 // This is a pack expansion.
2936 if (!BaseType->containsUnexpandedParameterPack()) {
2937 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00002938 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002939
Douglas Gregor44e7df62011-01-04 00:32:56 +00002940 EllipsisLoc = SourceLocation();
2941 }
2942 } else {
2943 // Check for any unexpanded parameter packs.
2944 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2945 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00002946
Sebastian Redla9351792012-02-11 23:51:47 +00002947 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00002948 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00002949 }
Sebastian Redla74948d2011-09-24 17:48:25 +00002950
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002951 // Check for direct and virtual base classes.
Craig Topperc3ec1492014-05-26 06:22:03 +00002952 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
2953 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002954 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002955 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2956 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00002957 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002958
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002959 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2960 VirtualBaseSpec);
2961
2962 // C++ [base.class.init]p2:
2963 // Unless the mem-initializer-id names a nonstatic data member of the
2964 // constructor's class or a direct or virtual base of that class, the
2965 // mem-initializer is ill-formed.
2966 if (!DirectBaseSpec && !VirtualBaseSpec) {
2967 // If the class has any dependent bases, then it's possible that
2968 // one of those types will resolve to the same type as
2969 // BaseType. Therefore, just treat this as a dependent base
2970 // class initialization. FIXME: Should we try to check the
2971 // initialization anyway? It seems odd.
2972 if (ClassDecl->hasAnyDependentBases())
2973 Dependent = true;
2974 else
2975 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2976 << BaseType << Context.getTypeDeclType(ClassDecl)
2977 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2978 }
2979 }
2980
2981 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00002982 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002983
Sebastian Redla74948d2011-09-24 17:48:25 +00002984 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2985 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00002986 InitRange.getBegin(), Init,
2987 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002988 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002989
2990 // C++ [base.class.init]p2:
2991 // If a mem-initializer-id is ambiguous because it designates both
2992 // a direct non-virtual base class and an inherited virtual base
2993 // class, the mem-initializer is ill-formed.
2994 if (DirectBaseSpec && VirtualBaseSpec)
2995 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002996 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002997
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002998 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002999 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003000 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003001
3002 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00003003 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003004 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003005 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00003006 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003007 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00003008 }
Sebastian Redl0501c632012-02-12 16:37:36 +00003009
3010 InitializedEntity BaseEntity =
3011 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3012 InitializationKind Kind =
3013 InitList ? InitializationKind::CreateDirectList(BaseLoc)
3014 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3015 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003016 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003017 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003018 if (BaseInit.isInvalid())
3019 return true;
John McCallacf0ee52010-10-08 02:01:28 +00003020
Richard Smith945f8d32013-01-14 22:39:08 +00003021 // C++11 [class.base.init]p7:
3022 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003023 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003024 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003025 if (BaseInit.isInvalid())
3026 return true;
3027
3028 // If we are in a dependent context, template instantiation will
3029 // perform this type-checking again. Just save the arguments that we
3030 // received in a ParenListExpr.
3031 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3032 // of the information that we have about the base
3033 // initializer. However, deconstructing the ASTs is a dicey process,
3034 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00003035 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003036 BaseInit = Init;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003037
Alexis Hunt1d792652011-01-08 20:30:50 +00003038 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00003039 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00003040 InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003041 BaseInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003042 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003043}
3044
Sebastian Redl22653ba2011-08-30 19:58:05 +00003045// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00003046static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3047 if (T.isNull()) T = E->getType();
3048 QualType TargetType = SemaRef.BuildReferenceType(
3049 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003050 SourceLocation ExprLoc = E->getLocStart();
3051 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3052 TargetType, ExprLoc);
3053
3054 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3055 SourceRange(ExprLoc, ExprLoc),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003056 E->getSourceRange()).get();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003057}
3058
Anders Carlsson1b00e242010-04-23 03:10:23 +00003059/// ImplicitInitializerKind - How an implicit base or member initializer should
3060/// initialize its base or member.
3061enum ImplicitInitializerKind {
3062 IIK_Default,
3063 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00003064 IIK_Move,
3065 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00003066};
3067
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003068static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00003069BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003070 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00003071 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003072 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00003073 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003074 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00003075 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3076 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003077
John McCalldadc5752010-08-24 06:29:42 +00003078 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003079
3080 switch (ImplicitInitKind) {
Richard Smithc2bc61b2013-03-18 21:12:30 +00003081 case IIK_Inherit: {
3082 const CXXRecordDecl *Inherited =
3083 Constructor->getInheritedConstructor()->getParent();
3084 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3085 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3086 // C++11 [class.inhctor]p8:
3087 // Each expression in the expression-list is of the form
3088 // static_cast<T&&>(p), where p is the name of the corresponding
3089 // constructor parameter and T is the declared type of p.
3090 SmallVector<Expr*, 16> Args;
3091 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3092 ParmVarDecl *PD = Constructor->getParamDecl(I);
3093 ExprResult ArgExpr =
3094 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3095 VK_LValue, SourceLocation());
3096 if (ArgExpr.isInvalid())
3097 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003098 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
Richard Smithc2bc61b2013-03-18 21:12:30 +00003099 }
3100
3101 InitializationKind InitKind = InitializationKind::CreateDirect(
3102 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003103 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smithc2bc61b2013-03-18 21:12:30 +00003104 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3105 break;
3106 }
3107 }
3108 // Fall through.
Anders Carlsson1b00e242010-04-23 03:10:23 +00003109 case IIK_Default: {
3110 InitializationKind InitKind
3111 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003112 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3113 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003114 break;
3115 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003116
Sebastian Redl22653ba2011-08-30 19:58:05 +00003117 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00003118 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003119 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003120 ParmVarDecl *Param = Constructor->getParamDecl(0);
3121 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00003122
Anders Carlsson1b00e242010-04-23 03:10:23 +00003123 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003124 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003125 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003126 Constructor->getLocation(), ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003127 VK_LValue, nullptr);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003128
Eli Friedmanfa0df832012-02-02 03:46:19 +00003129 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3130
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003131 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00003132 QualType ArgTy =
3133 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3134 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00003135
Sebastian Redl22653ba2011-08-30 19:58:05 +00003136 if (Moving) {
3137 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3138 }
3139
John McCallcf142162010-08-07 06:22:56 +00003140 CXXCastPath BasePath;
3141 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00003142 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3143 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003144 Moving ? VK_XValue : VK_LValue,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003145 &BasePath).get();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003146
Anders Carlsson1b00e242010-04-23 03:10:23 +00003147 InitializationKind InitKind
3148 = InitializationKind::CreateDirect(Constructor->getLocation(),
3149 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003150 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3151 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003152 break;
3153 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00003154 }
John McCallb268a282010-08-23 23:25:46 +00003155
Douglas Gregora40433a2010-12-07 00:41:46 +00003156 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003157 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003158 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003159
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003160 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00003161 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003162 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3163 SourceLocation()),
3164 BaseSpec->isVirtual(),
3165 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003166 BaseInit.getAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003167 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003168 SourceLocation());
3169
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003170 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003171}
3172
Sebastian Redl22653ba2011-08-30 19:58:05 +00003173static bool RefersToRValueRef(Expr *MemRef) {
3174 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3175 return Referenced->getType()->isRValueReferenceType();
3176}
3177
Anders Carlsson3c1db572010-04-23 02:15:47 +00003178static bool
3179BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003180 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00003181 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00003182 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003183 if (Field->isInvalidDecl())
3184 return true;
3185
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003186 SourceLocation Loc = Constructor->getLocation();
3187
Sebastian Redl22653ba2011-08-30 19:58:05 +00003188 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3189 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00003190 ParmVarDecl *Param = Constructor->getParamDecl(0);
3191 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00003192
3193 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00003194 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3195 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003196
Anders Carlsson423f5d82010-04-23 16:04:08 +00003197 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003198 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003199 SourceLocation(), Param, false,
Craig Topperc3ec1492014-05-26 06:22:03 +00003200 Loc, ParamType, VK_LValue, nullptr);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003201
Eli Friedmanfa0df832012-02-02 03:46:19 +00003202 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3203
Sebastian Redl22653ba2011-08-30 19:58:05 +00003204 if (Moving) {
3205 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3206 }
3207
Douglas Gregor94f9a482010-05-05 05:51:00 +00003208 // Build a reference to this field within the parameter.
3209 CXXScopeSpec SS;
3210 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3211 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003212 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3213 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003214 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00003215 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00003216 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003217 ParamType, Loc,
3218 /*IsArrow=*/false,
3219 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003220 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003221 /*FirstQualifierInScope=*/nullptr,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003222 MemberLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00003223 /*TemplateArgs=*/nullptr);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003224 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00003225 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003226
3227 // C++11 [class.copy]p15:
3228 // - if a member m has rvalue reference type T&&, it is direct-initialized
3229 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003230 if (RefersToRValueRef(CtorArg.get())) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003231 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003232 }
3233
Douglas Gregor94f9a482010-05-05 05:51:00 +00003234 // When the field we are copying is an array, create index variables for
3235 // each dimension of the array. We use these index variables to subscript
3236 // the source array, and other clients (e.g., CodeGen) will perform the
3237 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003238 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003239 QualType BaseType = Field->getType();
3240 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003241 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003242 while (const ConstantArrayType *Array
3243 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003244 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003245 // Create the iteration variable for this array index.
Craig Topperc3ec1492014-05-26 06:22:03 +00003246 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003247 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003248 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003249 llvm::raw_svector_ostream OS(Str);
3250 OS << "__i" << IndexVariables.size();
3251 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3252 }
3253 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00003254 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003255 IterationVarName, SizeType,
3256 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003257 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003258 IndexVariables.push_back(IterationVar);
3259
3260 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00003261 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00003262 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003263 assert(!IterationVarRef.isInvalid() &&
3264 "Reference to invented variable cannot fail!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003265 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
Eli Friedman844f9452012-01-23 02:35:22 +00003266 assert(!IterationVarRef.isInvalid() &&
3267 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00003268
Douglas Gregor94f9a482010-05-05 05:51:00 +00003269 // Subscript the array with this iteration variable.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003270 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3271 IterationVarRef.get(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00003272 Loc);
3273 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00003274 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003275
Douglas Gregor94f9a482010-05-05 05:51:00 +00003276 BaseType = Array->getElementType();
3277 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00003278
3279 // The array subscript expression is an lvalue, which is wrong for moving.
3280 if (Moving && InitializingArray)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003281 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003282
Douglas Gregor94f9a482010-05-05 05:51:00 +00003283 // Construct the entity that we will be initializing. For an array, this
3284 // will be first element in the array, which may require several levels
3285 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003286 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003287 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00003288 if (Indirect)
3289 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3290 else
3291 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00003292 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3293 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3294 0,
3295 Entities.back()));
3296
3297 // Direct-initialize to use the copy constructor.
3298 InitializationKind InitKind =
3299 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3300
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003301 Expr *CtorArgE = CtorArg.getAs<Expr>();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003302 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003303
John McCalldadc5752010-08-24 06:29:42 +00003304 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00003305 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003306 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00003307 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003308 if (MemberInit.isInvalid())
3309 return true;
3310
Douglas Gregor493627b2011-08-10 15:22:55 +00003311 if (Indirect) {
3312 assert(IndexVariables.size() == 0 &&
3313 "Indirect field improperly initialized");
3314 CXXMemberInit
3315 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3316 Loc, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003317 MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003318 Loc);
3319 } else
3320 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003321 Loc, MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003322 Loc,
3323 IndexVariables.data(),
3324 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00003325 return false;
3326 }
3327
Richard Smithc2bc61b2013-03-18 21:12:30 +00003328 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3329 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00003330
Anders Carlsson3c1db572010-04-23 02:15:47 +00003331 QualType FieldBaseElementType =
3332 SemaRef.Context.getBaseElementType(Field->getType());
3333
Anders Carlsson3c1db572010-04-23 02:15:47 +00003334 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003335 InitializedEntity InitEntity
3336 = Indirect? InitializedEntity::InitializeMember(Indirect)
3337 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00003338 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003339 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003340
3341 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3342 ExprResult MemberInit =
3343 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00003344
Douglas Gregora40433a2010-12-07 00:41:46 +00003345 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003346 if (MemberInit.isInvalid())
3347 return true;
3348
Douglas Gregor493627b2011-08-10 15:22:55 +00003349 if (Indirect)
3350 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3351 Indirect, Loc,
3352 Loc,
3353 MemberInit.get(),
3354 Loc);
3355 else
3356 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3357 Field, Loc, Loc,
3358 MemberInit.get(),
3359 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003360 return false;
3361 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003362
Alexis Hunt8b455182011-05-17 00:19:05 +00003363 if (!Field->getParent()->isUnion()) {
3364 if (FieldBaseElementType->isReferenceType()) {
3365 SemaRef.Diag(Constructor->getLocation(),
3366 diag::err_uninitialized_member_in_ctor)
3367 << (int)Constructor->isImplicit()
3368 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3369 << 0 << Field->getDeclName();
3370 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3371 return true;
3372 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003373
Alexis Hunt8b455182011-05-17 00:19:05 +00003374 if (FieldBaseElementType.isConstQualified()) {
3375 SemaRef.Diag(Constructor->getLocation(),
3376 diag::err_uninitialized_member_in_ctor)
3377 << (int)Constructor->isImplicit()
3378 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3379 << 1 << Field->getDeclName();
3380 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3381 return true;
3382 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003383 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00003384
David Blaikiebbafb8a2012-03-11 07:00:24 +00003385 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003386 FieldBaseElementType->isObjCRetainableType() &&
3387 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3388 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00003389 // ARC:
John McCall31168b02011-06-15 23:02:42 +00003390 // Default-initialize Objective-C pointers to NULL.
3391 CXXMemberInit
3392 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3393 Loc, Loc,
3394 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3395 Loc);
3396 return false;
3397 }
3398
Anders Carlsson3c1db572010-04-23 02:15:47 +00003399 // Nothing to initialize.
Craig Topperc3ec1492014-05-26 06:22:03 +00003400 CXXMemberInit = nullptr;
Anders Carlsson3c1db572010-04-23 02:15:47 +00003401 return false;
3402}
John McCallbc83b3f2010-05-20 23:23:51 +00003403
3404namespace {
3405struct BaseAndFieldInfo {
3406 Sema &S;
3407 CXXConstructorDecl *Ctor;
3408 bool AnyErrorsInInits;
3409 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00003410 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003411 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00003412 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00003413
3414 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3415 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003416 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3417 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00003418 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003419 else if (Generated && Ctor->isMoveConstructor())
3420 IIK = IIK_Move;
Richard Smithc2bc61b2013-03-18 21:12:30 +00003421 else if (Ctor->getInheritedConstructor())
3422 IIK = IIK_Inherit;
John McCallbc83b3f2010-05-20 23:23:51 +00003423 else
3424 IIK = IIK_Default;
3425 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00003426
3427 bool isImplicitCopyOrMove() const {
3428 switch (IIK) {
3429 case IIK_Copy:
3430 case IIK_Move:
3431 return true;
3432
3433 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00003434 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00003435 return false;
3436 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003437
3438 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00003439 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00003440
3441 bool addFieldInitializer(CXXCtorInitializer *Init) {
3442 AllToInit.push_back(Init);
3443
3444 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00003445 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003446 S.UnusedPrivateFields.remove(Init->getAnyMember());
3447
3448 return false;
3449 }
John McCallbc83b3f2010-05-20 23:23:51 +00003450
Richard Smithab44d5b2013-12-10 08:25:00 +00003451 bool isInactiveUnionMember(FieldDecl *Field) {
3452 RecordDecl *Record = Field->getParent();
3453 if (!Record->isUnion())
3454 return false;
3455
Richard Smith8d183852013-12-10 20:56:03 +00003456 if (FieldDecl *Active =
3457 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00003458 return Active != Field->getCanonicalDecl();
3459
3460 // In an implicit copy or move constructor, ignore any in-class initializer.
3461 if (isImplicitCopyOrMove())
3462 return true;
3463
3464 // If there's no explicit initialization, the field is active only if it
3465 // has an in-class initializer...
3466 if (Field->hasInClassInitializer())
3467 return false;
3468 // ... or it's an anonymous struct or union whose class has an in-class
3469 // initializer.
3470 if (!Field->isAnonymousStructOrUnion())
3471 return true;
3472 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3473 return !FieldRD->hasInClassInitializer();
3474 }
3475
3476 /// \brief Determine whether the given field is, or is within, a union member
3477 /// that is inactive (because there was an initializer given for a different
3478 /// member of the union, or because the union was not initialized at all).
3479 bool isWithinInactiveUnionMember(FieldDecl *Field,
3480 IndirectFieldDecl *Indirect) {
3481 if (!Indirect)
3482 return isInactiveUnionMember(Field);
3483
Aaron Ballman29c94602014-03-07 18:36:15 +00003484 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003485 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003486 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00003487 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00003488 }
3489 return false;
3490 }
3491};
Richard Smithc94ec842011-09-19 13:34:43 +00003492}
3493
Douglas Gregor10f939c2011-11-02 23:04:16 +00003494/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3495/// array type.
3496static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3497 if (T->isIncompleteArrayType())
3498 return true;
3499
3500 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3501 if (!ArrayT->getSize())
3502 return true;
3503
3504 T = ArrayT->getElementType();
3505 }
3506
3507 return false;
3508}
3509
Richard Smith938f40b2011-06-11 17:19:42 +00003510static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00003511 FieldDecl *Field,
Craig Topperc3ec1492014-05-26 06:22:03 +00003512 IndirectFieldDecl *Indirect = nullptr) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003513 if (Field->isInvalidDecl())
3514 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00003515
Chandler Carruth139e9622010-06-30 02:59:29 +00003516 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smithcd45dbc2014-04-19 03:48:30 +00003517 if (CXXCtorInitializer *Init =
3518 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003519 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003520
Richard Smithab44d5b2013-12-10 08:25:00 +00003521 // C++11 [class.base.init]p8:
3522 // if the entity is a non-static data member that has a
3523 // brace-or-equal-initializer and either
3524 // -- the constructor's class is a union and no other variant member of that
3525 // union is designated by a mem-initializer-id or
3526 // -- the constructor's class is not a union, and, if the entity is a member
3527 // of an anonymous union, no other member of that union is designated by
3528 // a mem-initializer-id,
3529 // the entity is initialized as specified in [dcl.init].
3530 //
3531 // We also apply the same rules to handle anonymous structs within anonymous
3532 // unions.
3533 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3534 return false;
3535
Douglas Gregor7db3e952011-11-28 20:03:15 +00003536 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smith852c9db2013-04-20 22:23:05 +00003537 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3538 Info.Ctor->getLocation(), Field);
Douglas Gregor493627b2011-08-10 15:22:55 +00003539 CXXCtorInitializer *Init;
3540 if (Indirect)
3541 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3542 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003543 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003544 SourceLocation());
3545 else
3546 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3547 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003548 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003549 SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00003550 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003551 }
3552
Douglas Gregor10f939c2011-11-02 23:04:16 +00003553 // Don't initialize incomplete or zero-length arrays.
3554 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3555 return false;
3556
John McCallbc83b3f2010-05-20 23:23:51 +00003557 // Don't try to build an implicit initializer if there were semantic
3558 // errors in any of the initializers (and therefore we might be
3559 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003560 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00003561 return false;
3562
Craig Topperc3ec1492014-05-26 06:22:03 +00003563 CXXCtorInitializer *Init = nullptr;
Douglas Gregor493627b2011-08-10 15:22:55 +00003564 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3565 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00003566 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00003567
Richard Smith0a8cfc72012-08-07 21:30:42 +00003568 if (!Init)
3569 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00003570
Richard Smith0a8cfc72012-08-07 21:30:42 +00003571 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003572}
Alexis Hunt61bc1732011-05-01 07:04:31 +00003573
3574bool
3575Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3576 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00003577 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00003578 Constructor->setNumCtorInitializers(1);
3579 CXXCtorInitializer **initializer =
3580 new (Context) CXXCtorInitializer*[1];
3581 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3582 Constructor->setCtorInitializers(initializer);
3583
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003584 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003585 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003586 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3587 }
3588
Alexis Hunte2622992011-05-05 00:05:47 +00003589 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00003590
Alexis Hunt61bc1732011-05-01 07:04:31 +00003591 return false;
3592}
Douglas Gregor493627b2011-08-10 15:22:55 +00003593
David Blaikie3fc2f912013-01-17 05:26:25 +00003594bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3595 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00003596 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003597 // Just store the initializers as written, they will be checked during
3598 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00003599 if (!Initializers.empty()) {
3600 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00003601 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00003602 new (Context) CXXCtorInitializer*[Initializers.size()];
3603 memcpy(baseOrMemberInitializers, Initializers.data(),
3604 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00003605 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003606 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00003607
3608 // Let template instantiation know whether we had errors.
3609 if (AnyErrors)
3610 Constructor->setInvalidDecl();
3611
Anders Carlssondb0a9652010-04-02 06:26:44 +00003612 return false;
3613 }
3614
John McCallbc83b3f2010-05-20 23:23:51 +00003615 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003616
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003617 // We need to build the initializer AST according to order of construction
3618 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003619 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00003620 if (!ClassDecl)
3621 return true;
3622
Eli Friedman9cf6b592009-11-09 19:20:36 +00003623 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00003624
David Blaikie3fc2f912013-01-17 05:26:25 +00003625 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003626 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00003627
Anders Carlssondb0a9652010-04-02 06:26:44 +00003628 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00003629 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003630 else {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003631 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003632
3633 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00003634 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003635 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003636 if (FD && FD->getParent()->isUnion())
3637 Info.ActiveUnionMember.insert(std::make_pair(
3638 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3639 }
3640 } else if (FieldDecl *FD = Member->getMember()) {
3641 if (FD->getParent()->isUnion())
3642 Info.ActiveUnionMember.insert(std::make_pair(
3643 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3644 }
3645 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00003646 }
3647
Anders Carlsson43c64af2010-04-21 19:52:01 +00003648 // Keep track of the direct virtual bases.
3649 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00003650 for (auto &I : ClassDecl->bases()) {
3651 if (I.isVirtual())
3652 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00003653 }
3654
Anders Carlssondb0a9652010-04-02 06:26:44 +00003655 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00003656 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003657 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00003658 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00003659 // [class.base.init]p7, per DR257:
3660 // A mem-initializer where the mem-initializer-id names a virtual base
3661 // class is ignored during execution of a constructor of any class that
3662 // is not the most derived class.
3663 if (ClassDecl->isAbstract()) {
3664 // FIXME: Provide a fixit to remove the base specifier. This requires
3665 // tracking the location of the associated comma for a base specifier.
3666 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00003667 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00003668 DiagnoseAbstractType(ClassDecl);
3669 }
3670
John McCallbc83b3f2010-05-20 23:23:51 +00003671 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00003672 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3673 // [class.base.init]p8, per DR257:
3674 // If a given [...] base class is not named by a mem-initializer-id
3675 // [...] and the entity is not a virtual base class of an abstract
3676 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00003677 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00003678 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003679 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00003680 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003681 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003682 HadError = true;
3683 continue;
3684 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003685
John McCallbc83b3f2010-05-20 23:23:51 +00003686 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003687 }
3688 }
Mike Stump11289f42009-09-09 15:08:12 +00003689
John McCallbc83b3f2010-05-20 23:23:51 +00003690 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003691 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003692 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00003693 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00003694 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003695
Alexis Hunt1d792652011-01-08 20:30:50 +00003696 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00003697 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00003698 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003699 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003700 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003701 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00003702 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003703 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003704 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003705 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003706 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00003707
John McCallbc83b3f2010-05-20 23:23:51 +00003708 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003709 }
3710 }
Mike Stump11289f42009-09-09 15:08:12 +00003711
John McCallbc83b3f2010-05-20 23:23:51 +00003712 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00003713 for (auto *Mem : ClassDecl->decls()) {
3714 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003715 // C++ [class.bit]p2:
3716 // A declaration for a bit-field that omits the identifier declares an
3717 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3718 // initialized.
3719 if (F->isUnnamedBitfield())
3720 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003721
Sebastian Redl22653ba2011-08-30 19:58:05 +00003722 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00003723 // handle anonymous struct/union fields based on their individual
3724 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003725 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003726 continue;
3727
3728 if (CollectFieldInitializer(*this, Info, F))
3729 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003730 continue;
3731 }
Douglas Gregor493627b2011-08-10 15:22:55 +00003732
3733 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003734 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003735 continue;
3736
Aaron Ballman629afae2014-03-07 19:56:05 +00003737 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003738 if (F->getType()->isIncompleteArrayType()) {
3739 assert(ClassDecl->hasFlexibleArrayMember() &&
3740 "Incomplete array type is not valid");
3741 continue;
3742 }
3743
Douglas Gregor493627b2011-08-10 15:22:55 +00003744 // Initialize each field of an anonymous struct individually.
3745 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3746 HadError = true;
3747
3748 continue;
3749 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003750 }
Mike Stump11289f42009-09-09 15:08:12 +00003751
David Blaikie3fc2f912013-01-17 05:26:25 +00003752 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003753 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003754 Constructor->setNumCtorInitializers(NumInitializers);
3755 CXXCtorInitializer **baseOrMemberInitializers =
3756 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00003757 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00003758 NumInitializers * sizeof(CXXCtorInitializer*));
3759 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00003760
John McCalla6309952010-03-16 21:39:52 +00003761 // Constructors implicitly reference the base and member
3762 // destructors.
3763 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3764 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003765 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00003766
3767 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003768}
3769
David Blaikieb61b8152013-01-17 08:49:22 +00003770static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003771 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00003772 const RecordDecl *RD = RT->getDecl();
3773 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003774 for (auto *Field : RD->fields())
3775 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00003776 return;
3777 }
Eli Friedman952c15d2009-07-21 19:28:10 +00003778 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003779 IdealInits.push_back(Field->getCanonicalDecl());
Eli Friedman952c15d2009-07-21 19:28:10 +00003780}
3781
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003782static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3783 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00003784}
3785
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003786static const void *GetKeyForMember(ASTContext &Context,
3787 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00003788 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003789 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00003790
Richard Smithcd45dbc2014-04-19 03:48:30 +00003791 return Member->getAnyMember()->getCanonicalDecl();
Eli Friedman952c15d2009-07-21 19:28:10 +00003792}
3793
David Blaikie3fc2f912013-01-17 05:26:25 +00003794static void DiagnoseBaseOrMemInitializerOrder(
3795 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3796 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00003797 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00003798 return;
Mike Stump11289f42009-09-09 15:08:12 +00003799
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003800 // Don't check initializers order unless the warning is enabled at the
3801 // location of at least one initializer.
3802 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003803 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003804 CXXCtorInitializer *Init = Inits[InitIndex];
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00003805 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
3806 Init->getSourceLocation())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003807 ShouldCheckOrder = true;
3808 break;
3809 }
3810 }
3811 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00003812 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003813
John McCallbb7b6582010-04-10 07:37:23 +00003814 // Build the list of bases and members in the order that they'll
3815 // actually be initialized. The explicit initializers should be in
3816 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003817 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00003818
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003819 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3820
John McCallbb7b6582010-04-10 07:37:23 +00003821 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00003822 for (const auto &VBase : ClassDecl->vbases())
3823 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00003824
John McCallbb7b6582010-04-10 07:37:23 +00003825 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003826 for (const auto &Base : ClassDecl->bases()) {
3827 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00003828 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00003829 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00003830 }
Mike Stump11289f42009-09-09 15:08:12 +00003831
John McCallbb7b6582010-04-10 07:37:23 +00003832 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003833 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003834 if (Field->isUnnamedBitfield())
3835 continue;
3836
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003837 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00003838 }
3839
John McCallbb7b6582010-04-10 07:37:23 +00003840 unsigned NumIdealInits = IdealInitKeys.size();
3841 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00003842
Craig Topperc3ec1492014-05-26 06:22:03 +00003843 CXXCtorInitializer *PrevInit = nullptr;
David Blaikie3fc2f912013-01-17 05:26:25 +00003844 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003845 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003846 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00003847
3848 // Scan forward to try to find this initializer in the idealized
3849 // initializers list.
3850 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3851 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003852 break;
John McCallbb7b6582010-04-10 07:37:23 +00003853
3854 // If we didn't find this initializer, it must be because we
3855 // scanned past it on a previous iteration. That can only
3856 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00003857 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00003858 Sema::SemaDiagnosticBuilder D =
3859 SemaRef.Diag(PrevInit->getSourceLocation(),
3860 diag::warn_initializer_out_of_order);
3861
Francois Pichetd583da02010-12-04 09:14:42 +00003862 if (PrevInit->isAnyMemberInitializer())
3863 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003864 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003865 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003866
Francois Pichetd583da02010-12-04 09:14:42 +00003867 if (Init->isAnyMemberInitializer())
3868 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003869 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003870 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003871
3872 // Move back to the initializer's location in the ideal list.
3873 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3874 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003875 break;
John McCallbb7b6582010-04-10 07:37:23 +00003876
3877 assert(IdealIndex != NumIdealInits &&
3878 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003879 }
John McCallbb7b6582010-04-10 07:37:23 +00003880
3881 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003882 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00003883}
3884
John McCall23eebd92010-04-10 09:28:51 +00003885namespace {
3886bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003887 CXXCtorInitializer *Init,
3888 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00003889 if (!PrevInit) {
3890 PrevInit = Init;
3891 return false;
3892 }
3893
Douglas Gregorea306a12013-03-25 23:28:23 +00003894 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00003895 S.Diag(Init->getSourceLocation(),
3896 diag::err_multiple_mem_initialization)
3897 << Field->getDeclName()
3898 << Init->getSourceRange();
3899 else {
John McCall424cec92011-01-19 06:33:43 +00003900 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00003901 assert(BaseClass && "neither field nor base");
3902 S.Diag(Init->getSourceLocation(),
3903 diag::err_multiple_base_initialization)
3904 << QualType(BaseClass, 0)
3905 << Init->getSourceRange();
3906 }
3907 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3908 << 0 << PrevInit->getSourceRange();
3909
3910 return true;
3911}
3912
Alexis Hunt1d792652011-01-08 20:30:50 +00003913typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00003914typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3915
3916bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003917 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00003918 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00003919 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003920 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00003921 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00003922
3923 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00003924 if (Parent->isUnion()) {
3925 UnionEntry &En = Unions[Parent];
3926 if (En.first && En.first != Child) {
3927 S.Diag(Init->getSourceLocation(),
3928 diag::err_multiple_mem_union_initialization)
3929 << Field->getDeclName()
3930 << Init->getSourceRange();
3931 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3932 << 0 << En.second->getSourceRange();
3933 return true;
David Blaikie256ee192011-11-12 20:54:14 +00003934 }
3935 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00003936 En.first = Child;
3937 En.second = Init;
3938 }
David Blaikie0f65d592011-11-17 06:01:57 +00003939 if (!Parent->isAnonymousStructOrUnion())
3940 return false;
John McCall23eebd92010-04-10 09:28:51 +00003941 }
3942
3943 Child = Parent;
3944 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00003945 }
John McCall23eebd92010-04-10 09:28:51 +00003946
3947 return false;
3948}
3949}
3950
Anders Carlssone857b292010-04-02 03:37:03 +00003951/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00003952void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00003953 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00003954 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00003955 bool AnyErrors) {
3956 if (!ConstructorDecl)
3957 return;
3958
3959 AdjustDeclIfTemplate(ConstructorDecl);
3960
3961 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003962 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00003963
3964 if (!Constructor) {
3965 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3966 return;
3967 }
3968
John McCall23eebd92010-04-10 09:28:51 +00003969 // Mapping for the duplicate initializers check.
3970 // For member initializers, this is keyed with a FieldDecl*.
3971 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003972 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00003973
3974 // Mapping for the inconsistent anonymous-union initializers check.
3975 RedundantUnionMap MemberUnions;
3976
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003977 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003978 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003979 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00003980
Abramo Bagnara341d7832010-05-26 18:09:23 +00003981 // Set the source order index.
3982 Init->setSourceOrder(i);
3983
Francois Pichetd583da02010-12-04 09:14:42 +00003984 if (Init->isAnyMemberInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003985 const void *Key = GetKeyForMember(Context, Init);
3986 if (CheckRedundantInit(*this, Init, Members[Key]) ||
John McCall23eebd92010-04-10 09:28:51 +00003987 CheckRedundantUnionInit(*this, Init, MemberUnions))
3988 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003989 } else if (Init->isBaseInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003990 const void *Key = GetKeyForMember(Context, Init);
John McCall23eebd92010-04-10 09:28:51 +00003991 if (CheckRedundantInit(*this, Init, Members[Key]))
3992 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003993 } else {
3994 assert(Init->isDelegatingInitializer());
3995 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00003996 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00003997 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00003998 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00003999 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00004000 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00004001 }
Alexis Hunt6118d662011-05-04 05:57:24 +00004002 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00004003 // Return immediately as the initializer is set.
4004 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004005 }
Anders Carlssone857b292010-04-02 03:37:03 +00004006 }
4007
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004008 if (HadError)
4009 return;
4010
David Blaikie3fc2f912013-01-17 05:26:25 +00004011 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00004012
David Blaikie3fc2f912013-01-17 05:26:25 +00004013 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00004014
Richard Trieuef64e942013-10-25 00:56:00 +00004015 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00004016}
4017
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004018void
John McCalla6309952010-03-16 21:39:52 +00004019Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4020 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00004021 // Ignore dependent contexts. Also ignore unions, since their members never
4022 // have destructors implicitly called.
4023 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00004024 return;
John McCall1064d7e2010-03-16 05:22:47 +00004025
4026 // FIXME: all the access-control diagnostics are positioned on the
4027 // field/base declaration. That's probably good; that said, the
4028 // user might reasonably want to know why the destructor is being
4029 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00004030
Anders Carlssondee9a302009-11-17 04:44:12 +00004031 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004032 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00004033 if (Field->isInvalidDecl())
4034 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004035
4036 // Don't destroy incomplete or zero-length arrays.
4037 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4038 continue;
4039
Anders Carlssondee9a302009-11-17 04:44:12 +00004040 QualType FieldType = Context.getBaseElementType(Field->getType());
4041
4042 const RecordType* RT = FieldType->getAs<RecordType>();
4043 if (!RT)
4044 continue;
4045
4046 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004047 if (FieldClassDecl->isInvalidDecl())
4048 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004049 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004050 continue;
Richard Smith921bd202012-02-26 09:11:52 +00004051 // The destructor for an implicit anonymous union member is never invoked.
4052 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4053 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00004054
Douglas Gregore71edda2010-07-01 22:47:18 +00004055 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004056 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004057 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004058 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00004059 << Field->getDeclName()
4060 << FieldType);
4061
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004062 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004063 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004064 }
4065
John McCall1064d7e2010-03-16 05:22:47 +00004066 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4067
Anders Carlssondee9a302009-11-17 04:44:12 +00004068 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004069 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004070 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00004071 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004072
4073 // Remember direct virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004074 if (Base.isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00004075 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00004076
John McCall1064d7e2010-03-16 05:22:47 +00004077 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004078 // If our base class is invalid, we probably can't get its dtor anyway.
4079 if (BaseClassDecl->isInvalidDecl())
4080 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004081 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004082 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004083
Douglas Gregore71edda2010-07-01 22:47:18 +00004084 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004085 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004086
4087 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00004088 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004089 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00004090 << Base.getType()
4091 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00004092 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00004093
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004094 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004095 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004096 }
4097
4098 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004099 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004100 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00004101 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004102
4103 // Ignore direct virtual bases.
4104 if (DirectVirtualBases.count(RT))
4105 continue;
4106
John McCall1064d7e2010-03-16 05:22:47 +00004107 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004108 // If our base class is invalid, we probably can't get its dtor anyway.
4109 if (BaseClassDecl->isInvalidDecl())
4110 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004111 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004112 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004113
Douglas Gregore71edda2010-07-01 22:47:18 +00004114 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004115 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00004116 if (CheckDestructorAccess(
4117 ClassDecl->getLocation(), Dtor,
4118 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00004119 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004120 Context.getTypeDeclType(ClassDecl)) ==
4121 AR_accessible) {
4122 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00004123 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004124 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00004125 SourceRange(), DeclarationName(), nullptr);
David Majnemer626032f2013-06-22 06:43:58 +00004126 }
John McCall1064d7e2010-03-16 05:22:47 +00004127
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004128 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004129 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004130 }
4131}
4132
John McCall48871652010-08-21 09:40:31 +00004133void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00004134 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004135 return;
Mike Stump11289f42009-09-09 15:08:12 +00004136
Mike Stump11289f42009-09-09 15:08:12 +00004137 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00004138 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00004139 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00004140 DiagnoseUninitializedFields(*this, Constructor);
4141 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004142}
4143
Mike Stump11289f42009-09-09 15:08:12 +00004144bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00004145 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregorae298422012-05-04 17:09:59 +00004146 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4147 unsigned DiagID;
4148 AbstractDiagSelID SelID;
4149
4150 public:
4151 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4152 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004153
Craig Toppera798a9d2014-03-02 09:32:10 +00004154 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004155 if (Suppressed) return;
Douglas Gregorae298422012-05-04 17:09:59 +00004156 if (SelID == -1)
4157 S.Diag(Loc, DiagID) << T;
4158 else
4159 S.Diag(Loc, DiagID) << SelID << T;
4160 }
4161 } Diagnoser(DiagID, SelID);
4162
4163 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004164}
4165
Anders Carlssoneabf7702009-08-27 00:13:57 +00004166bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregorae298422012-05-04 17:09:59 +00004167 TypeDiagnoser &Diagnoser) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004168 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004169 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004170
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004171 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregorae298422012-05-04 17:09:59 +00004172 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004173
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004174 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004175 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004176 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004177 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00004178
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004179 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregorae298422012-05-04 17:09:59 +00004180 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004181 }
Mike Stump11289f42009-09-09 15:08:12 +00004182
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004183 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004184 if (!RT)
4185 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004186
John McCall67da35c2010-02-04 22:26:26 +00004187 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004188
John McCall02db245d2010-08-18 09:41:07 +00004189 // We can't answer whether something is abstract until it has a
4190 // definition. If it's currently being defined, we'll walk back
4191 // over all the declarations when we have a full definition.
4192 const CXXRecordDecl *Def = RD->getDefinition();
4193 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00004194 return false;
4195
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004196 if (!RD->isAbstract())
4197 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004198
Douglas Gregorae298422012-05-04 17:09:59 +00004199 Diagnoser.diagnose(*this, Loc, T);
John McCall02db245d2010-08-18 09:41:07 +00004200 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00004201
John McCall02db245d2010-08-18 09:41:07 +00004202 return true;
4203}
4204
4205void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4206 // Check if we've already emitted the list of pure virtual functions
4207 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004208 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00004209 return;
Mike Stump11289f42009-09-09 15:08:12 +00004210
Richard Smithbc46e432013-07-22 02:56:56 +00004211 // If the diagnostic is suppressed, don't emit the notes. We're only
4212 // going to emit them once, so try to attach them to a diagnostic we're
4213 // actually going to show.
4214 if (Diags.isLastDiagnosticIgnored())
4215 return;
4216
Douglas Gregor4165bd62010-03-23 23:47:56 +00004217 CXXFinalOverriderMap FinalOverriders;
4218 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00004219
Anders Carlssona2f74f32010-06-03 01:00:02 +00004220 // Keep a set of seen pure methods so we won't diagnose the same method
4221 // more than once.
4222 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4223
Douglas Gregor4165bd62010-03-23 23:47:56 +00004224 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4225 MEnd = FinalOverriders.end();
4226 M != MEnd;
4227 ++M) {
4228 for (OverridingMethods::iterator SO = M->second.begin(),
4229 SOEnd = M->second.end();
4230 SO != SOEnd; ++SO) {
4231 // C++ [class.abstract]p4:
4232 // A class is abstract if it contains or inherits at least one
4233 // pure virtual function for which the final overrider is pure
4234 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00004235
Douglas Gregor4165bd62010-03-23 23:47:56 +00004236 //
4237 if (SO->second.size() != 1)
4238 continue;
4239
4240 if (!SO->second.front().Method->isPure())
4241 continue;
4242
Anders Carlssona2f74f32010-06-03 01:00:02 +00004243 if (!SeenPureMethods.insert(SO->second.front().Method))
4244 continue;
4245
Douglas Gregor4165bd62010-03-23 23:47:56 +00004246 Diag(SO->second.front().Method->getLocation(),
4247 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00004248 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00004249 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004250 }
4251
4252 if (!PureVirtualClassDiagSet)
4253 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4254 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004255}
4256
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004257namespace {
John McCall02db245d2010-08-18 09:41:07 +00004258struct AbstractUsageInfo {
4259 Sema &S;
4260 CXXRecordDecl *Record;
4261 CanQualType AbstractType;
4262 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00004263
John McCall02db245d2010-08-18 09:41:07 +00004264 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4265 : S(S), Record(Record),
4266 AbstractType(S.Context.getCanonicalType(
4267 S.Context.getTypeDeclType(Record))),
4268 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004269
John McCall02db245d2010-08-18 09:41:07 +00004270 void DiagnoseAbstractType() {
4271 if (Invalid) return;
4272 S.DiagnoseAbstractType(Record);
4273 Invalid = true;
4274 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00004275
John McCall02db245d2010-08-18 09:41:07 +00004276 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4277};
4278
4279struct CheckAbstractUsage {
4280 AbstractUsageInfo &Info;
4281 const NamedDecl *Ctx;
4282
4283 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4284 : Info(Info), Ctx(Ctx) {}
4285
4286 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4287 switch (TL.getTypeLocClass()) {
4288#define ABSTRACT_TYPELOC(CLASS, PARENT)
4289#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00004290 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00004291#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004292 }
John McCall02db245d2010-08-18 09:41:07 +00004293 }
Mike Stump11289f42009-09-09 15:08:12 +00004294
John McCall02db245d2010-08-18 09:41:07 +00004295 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00004296 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004297 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4298 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00004299 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004300
4301 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00004302 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004303 }
John McCall02db245d2010-08-18 09:41:07 +00004304 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004305
John McCall02db245d2010-08-18 09:41:07 +00004306 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4307 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4308 }
Mike Stump11289f42009-09-09 15:08:12 +00004309
John McCall02db245d2010-08-18 09:41:07 +00004310 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4311 // Visit the type parameters from a permissive context.
4312 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4313 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4314 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4315 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4316 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4317 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004318 }
John McCall02db245d2010-08-18 09:41:07 +00004319 }
Mike Stump11289f42009-09-09 15:08:12 +00004320
John McCall02db245d2010-08-18 09:41:07 +00004321 // Visit pointee types from a permissive context.
4322#define CheckPolymorphic(Type) \
4323 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4324 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4325 }
4326 CheckPolymorphic(PointerTypeLoc)
4327 CheckPolymorphic(ReferenceTypeLoc)
4328 CheckPolymorphic(MemberPointerTypeLoc)
4329 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00004330 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00004331
John McCall02db245d2010-08-18 09:41:07 +00004332 /// Handle all the types we haven't given a more specific
4333 /// implementation for above.
4334 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4335 // Every other kind of type that we haven't called out already
4336 // that has an inner type is either (1) sugar or (2) contains that
4337 // inner type in some way as a subobject.
4338 if (TypeLoc Next = TL.getNextTypeLoc())
4339 return Visit(Next, Sel);
4340
4341 // If there's no inner type and we're in a permissive context,
4342 // don't diagnose.
4343 if (Sel == Sema::AbstractNone) return;
4344
4345 // Check whether the type matches the abstract type.
4346 QualType T = TL.getType();
4347 if (T->isArrayType()) {
4348 Sel = Sema::AbstractArrayType;
4349 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004350 }
John McCall02db245d2010-08-18 09:41:07 +00004351 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4352 if (CT != Info.AbstractType) return;
4353
4354 // It matched; do some magic.
4355 if (Sel == Sema::AbstractArrayType) {
4356 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4357 << T << TL.getSourceRange();
4358 } else {
4359 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4360 << Sel << T << TL.getSourceRange();
4361 }
4362 Info.DiagnoseAbstractType();
4363 }
4364};
4365
4366void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4367 Sema::AbstractDiagSelID Sel) {
4368 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4369}
4370
4371}
4372
4373/// Check for invalid uses of an abstract type in a method declaration.
4374static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4375 CXXMethodDecl *MD) {
4376 // No need to do the check on definitions, which require that
4377 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004378 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00004379 return;
4380
4381 // For safety's sake, just ignore it if we don't have type source
4382 // information. This should never happen for non-implicit methods,
4383 // but...
4384 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4385 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4386}
4387
4388/// Check for invalid uses of an abstract type within a class definition.
4389static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4390 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00004391 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00004392 if (D->isImplicit()) continue;
4393
4394 // Methods and method templates.
4395 if (isa<CXXMethodDecl>(D)) {
4396 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4397 } else if (isa<FunctionTemplateDecl>(D)) {
4398 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4399 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4400
4401 // Fields and static variables.
4402 } else if (isa<FieldDecl>(D)) {
4403 FieldDecl *FD = cast<FieldDecl>(D);
4404 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4405 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4406 } else if (isa<VarDecl>(D)) {
4407 VarDecl *VD = cast<VarDecl>(D);
4408 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4409 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4410
4411 // Nested classes and class templates.
4412 } else if (isa<CXXRecordDecl>(D)) {
4413 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4414 } else if (isa<ClassTemplateDecl>(D)) {
4415 CheckAbstractClassUsage(Info,
4416 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4417 }
4418 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004419}
4420
Hans Wennborg853ae942014-05-30 16:59:42 +00004421/// \brief Check class-level dllimport/dllexport attribute.
4422static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) {
4423 Attr *ClassAttr = getDLLAttr(Class);
Hans Wennborg205c39b2014-08-23 22:34:43 +00004424
4425 // MSVC inherits DLL attributes to partial class template specializations.
4426 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
4427 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4428 if (Attr *TemplateAttr =
4429 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
4430 auto *A = cast<InheritableAttr>(TemplateAttr->clone(S.getASTContext()));
4431 A->setInherited(true);
4432 ClassAttr = A;
4433 }
4434 }
4435 }
4436
Hans Wennborg853ae942014-05-30 16:59:42 +00004437 if (!ClassAttr)
4438 return;
4439
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004440 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4441 !ClassAttr->isInherited()) {
4442 // Diagnose dll attributes on members of class with dll attribute.
4443 for (Decl *Member : Class->decls()) {
4444 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4445 continue;
4446 InheritableAttr *MemberAttr = getDLLAttr(Member);
4447 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4448 continue;
4449
4450 S.Diag(MemberAttr->getLocation(),
4451 diag::err_attribute_dll_member_of_dll_class)
4452 << MemberAttr << ClassAttr;
4453 S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4454 Member->setInvalidDecl();
4455 }
4456 }
4457
4458 if (Class->getDescribedClassTemplate())
4459 // Don't inherit dll attribute until the template is instantiated.
4460 return;
4461
Hans Wennborg853ae942014-05-30 16:59:42 +00004462 bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4463
4464 // Force declaration of implicit members so they can inherit the attribute.
4465 S.ForceDeclarationOfImplicitMembers(Class);
4466
4467 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4468 // seem to be true in practice?
4469
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004470 TemplateSpecializationKind TSK =
4471 Class->getTemplateSpecializationKind();
4472
Hans Wennborg853ae942014-05-30 16:59:42 +00004473 for (Decl *Member : Class->decls()) {
Hans Wennborge8ad3832014-06-11 22:44:39 +00004474 VarDecl *VD = dyn_cast<VarDecl>(Member);
4475 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4476
4477 // Only methods and static fields inherit the attributes.
4478 if (!VD && !MD)
Hans Wennborg853ae942014-05-30 16:59:42 +00004479 continue;
Hans Wennborge8ad3832014-06-11 22:44:39 +00004480
4481 // Don't process deleted methods.
4482 if (MD && MD->isDeleted())
Hans Wennborg9d06a8d2014-06-10 17:53:23 +00004483 continue;
Hans Wennborg853ae942014-05-30 16:59:42 +00004484
Hans Wennborge8ad3832014-06-11 22:44:39 +00004485 if (MD && MD->isMoveAssignmentOperator() && !ClassExported &&
4486 MD->isInlined()) {
4487 // Current MSVC versions don't export the move assignment operators, so
4488 // don't attempt to import them if we have a definition.
4489 continue;
4490 }
4491
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004492 if (!getDLLAttr(Member)) {
Hans Wennborg496524b2014-05-31 02:08:49 +00004493 auto *NewAttr =
4494 cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
4495 NewAttr->setInherited(true);
4496 Member->addAttr(NewAttr);
4497 }
Hans Wennborg853ae942014-05-30 16:59:42 +00004498
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004499 if (MD && ClassExported) {
4500 if (MD->isUserProvided()) {
4501 // Instantiate non-default methods..
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004502
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004503 // .. except for certain kinds of template specializations.
4504 if (TSK == TSK_ExplicitInstantiationDeclaration)
4505 continue;
4506 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4507 continue;
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004508
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004509 S.MarkFunctionReferenced(Class->getLocation(), MD);
4510 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4511 MD->isCopyAssignmentOperator() ||
4512 MD->isMoveAssignmentOperator()) {
4513 // Instantiate non-trivial or explicitly defaulted methods, and the
4514 // copy assignment / move assignment operators.
4515 S.MarkFunctionReferenced(Class->getLocation(), MD);
4516 // Resolve its exception specification; CodeGen needs it.
4517 auto *FPT = MD->getType()->getAs<FunctionProtoType>();
4518 S.ResolveExceptionSpec(Class->getLocation(), FPT);
4519 S.ActOnFinishInlineMethodDef(MD);
Hans Wennborg853ae942014-05-30 16:59:42 +00004520 }
4521 }
4522 }
4523}
4524
Douglas Gregorc99f1552009-12-03 18:33:45 +00004525/// \brief Perform semantic checks on a class definition that has been
4526/// completing, introducing implicitly-declared members, checking for
4527/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004528void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00004529 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00004530 return;
4531
John McCall02db245d2010-08-18 09:41:07 +00004532 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4533 AbstractUsageInfo Info(*this, Record);
4534 CheckAbstractClassUsage(Info, Record);
4535 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00004536
4537 // If this is not an aggregate type and has no user-declared constructor,
4538 // complain about any non-static data members of reference or const scalar
4539 // type, since they will never get initializers.
4540 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00004541 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4542 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004543 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004544 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004545 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004546 continue;
4547
Douglas Gregor454a5b62010-04-15 00:00:53 +00004548 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00004549 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004550 if (!Complained) {
4551 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4552 << Record->getTagKind() << Record;
4553 Complained = true;
4554 }
4555
4556 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4557 << F->getType()->isReferenceType()
4558 << F->getDeclName();
4559 }
4560 }
4561 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004562
Anders Carlssone771e762011-01-25 18:08:22 +00004563 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00004564 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00004565
4566 if (Record->getIdentifier()) {
4567 // C++ [class.mem]p13:
4568 // If T is the name of a class, then each of the following shall have a
4569 // name different from T:
4570 // - every member of every anonymous union that is a member of class T.
4571 //
4572 // C++ [class.mem]p14:
4573 // In addition, if class T has a user-declared constructor (12.1), every
4574 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00004575 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4576 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4577 ++I) {
4578 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004579 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4580 isa<IndirectFieldDecl>(D)) {
4581 Diag(D->getLocation(), diag::err_member_name_of_class)
4582 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00004583 break;
4584 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00004585 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00004586 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004587
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004588 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00004589 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004590 CXXDestructorDecl *dtor = Record->getDestructor();
David Blaikie04e2e662014-05-09 22:02:28 +00004591 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4592 !Record->hasAttr<FinalAttr>())
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004593 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4594 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4595 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004596
David Majnemera5433082013-10-18 00:33:31 +00004597 if (Record->isAbstract()) {
4598 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4599 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4600 << FA->isSpelledAsSealed();
4601 DiagnoseAbstractType(Record);
4602 }
David Blaikie348df502012-09-21 03:21:07 +00004603 }
4604
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004605 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004606 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00004607 // See if a method overloads virtual methods in a base
4608 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004609 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004610 DiagnoseHiddenVirtualMethods(M);
Richard Smithbd305122012-12-11 01:14:52 +00004611
4612 // Check whether the explicitly-defaulted special members are valid.
4613 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004614 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004615
4616 // For an explicitly defaulted or deleted special member, we defer
4617 // determining triviality until the class is complete. That time is now!
4618 if (!M->isImplicit() && !M->isUserProvided()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004619 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004620 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004621 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00004622
4623 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00004624 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004625 }
4626 }
4627 }
4628 }
4629
4630 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4631 // function that is not a constructor declares that member function to be
4632 // const. [...] The class of which that function is a member shall be
4633 // a literal type.
4634 //
4635 // If the class has virtual bases, any constexpr members will already have
4636 // been diagnosed by the checks performed on the member declaration, so
4637 // suppress this (less useful) diagnostic.
4638 //
4639 // We delay this until we know whether an explicitly-defaulted (or deleted)
4640 // destructor for the class is trivial.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004641 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smithbd305122012-12-11 01:14:52 +00004642 !Record->isLiteral() && !Record->getNumVBases()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004643 for (const auto *M : Record->methods()) {
4644 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) {
Richard Smithbd305122012-12-11 01:14:52 +00004645 switch (Record->getTemplateSpecializationKind()) {
4646 case TSK_ImplicitInstantiation:
4647 case TSK_ExplicitInstantiationDeclaration:
4648 case TSK_ExplicitInstantiationDefinition:
4649 // If a template instantiates to a non-literal type, but its members
4650 // instantiate to constexpr functions, the template is technically
4651 // ill-formed, but we allow it for sanity.
4652 continue;
4653
4654 case TSK_Undeclared:
4655 case TSK_ExplicitSpecialization:
4656 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4657 diag::err_constexpr_method_non_literal);
4658 break;
4659 }
4660
4661 // Only produce one error per class.
4662 break;
4663 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004664 }
4665 }
Sebastian Redl08905022011-02-05 19:23:19 +00004666
John McCall95833f32014-02-27 20:30:49 +00004667 // ms_struct is a request to use the same ABI rules as MSVC. Check
4668 // whether this class uses any C++ features that are implemented
4669 // completely differently in MSVC, and if so, emit a diagnostic.
4670 // That diagnostic defaults to an error, but we allow projects to
4671 // map it down to a warning (or ignore it). It's a fairly common
4672 // practice among users of the ms_struct pragma to mass-annotate
4673 // headers, sweeping up a bunch of types that the project doesn't
4674 // really rely on MSVC-compatible layout for. We must therefore
4675 // support "ms_struct except for C++ stuff" as a secondary ABI.
4676 if (Record->isMsStruct(Context) &&
4677 (Record->isPolymorphic() || Record->getNumBases())) {
4678 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00004679 }
4680
Richard Smithc2bc61b2013-03-18 21:12:30 +00004681 // Declare inheriting constructors. We do this eagerly here because:
4682 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redl08905022011-02-05 19:23:19 +00004683 // constructors from different classes.
4684 // - The lazy declaration of the other implicit constructors is so as to not
4685 // waste space and performance on classes that are not meant to be
4686 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smithc2bc61b2013-03-18 21:12:30 +00004687 // have inheriting constructors.
4688 DeclareInheritingConstructors(Record);
Hans Wennborg853ae942014-05-30 16:59:42 +00004689
4690 checkDLLAttribute(*this, Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004691}
4692
Richard Smith41c35d62013-11-27 03:39:20 +00004693/// Look up the special member function that would be called by a special
4694/// member function for a subobject of class type.
4695///
4696/// \param Class The class type of the subobject.
4697/// \param CSM The kind of special member function.
4698/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4699/// \param ConstRHS True if this is a copy operation with a const object
4700/// on its RHS, that is, if the argument to the outer special member
4701/// function is 'const' and this is not a field marked 'mutable'.
4702static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4703 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4704 unsigned FieldQuals, bool ConstRHS) {
4705 unsigned LHSQuals = 0;
4706 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4707 LHSQuals = FieldQuals;
4708
4709 unsigned RHSQuals = FieldQuals;
4710 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4711 RHSQuals = 0;
4712 else if (ConstRHS)
4713 RHSQuals |= Qualifiers::Const;
4714
4715 return S.LookupSpecialMember(Class, CSM,
4716 RHSQuals & Qualifiers::Const,
4717 RHSQuals & Qualifiers::Volatile,
4718 false,
4719 LHSQuals & Qualifiers::Const,
4720 LHSQuals & Qualifiers::Volatile);
4721}
4722
Richard Smithb5800092012-06-10 05:43:50 +00004723/// Is the special member function which would be selected to perform the
4724/// specified operation on the specified class type a constexpr constructor?
4725static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4726 Sema::CXXSpecialMember CSM,
Richard Smith41c35d62013-11-27 03:39:20 +00004727 unsigned Quals, bool ConstRHS) {
Richard Smithb5800092012-06-10 05:43:50 +00004728 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00004729 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00004730 if (!SMOR || !SMOR->getMethod())
4731 // A constructor we wouldn't select can't be "involved in initializing"
4732 // anything.
4733 return true;
4734 return SMOR->getMethod()->isConstexpr();
4735}
4736
4737/// Determine whether the specified special member function would be constexpr
4738/// if it were implicitly defined.
4739static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4740 Sema::CXXSpecialMember CSM,
4741 bool ConstArg) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004742 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00004743 return false;
4744
4745 // C++11 [dcl.constexpr]p4:
4746 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00004747 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00004748 switch (CSM) {
4749 case Sema::CXXDefaultConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004750 // Since default constructor lookup is essentially trivial (and cannot
4751 // involve, for instance, template instantiation), we compute whether a
4752 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4753 //
4754 // This is important for performance; we need to know whether the default
4755 // constructor is constexpr to determine whether the type is a literal type.
4756 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4757
Richard Smithb5800092012-06-10 05:43:50 +00004758 case Sema::CXXCopyConstructor:
4759 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004760 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00004761 break;
4762
4763 case Sema::CXXCopyAssignment:
4764 case Sema::CXXMoveAssignment:
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004765 if (!S.getLangOpts().CPlusPlus14)
Richard Smith99005e62013-05-07 03:19:20 +00004766 return false;
4767 // In C++1y, we need to perform overload resolution.
4768 Ctor = false;
4769 break;
4770
Richard Smithb5800092012-06-10 05:43:50 +00004771 case Sema::CXXDestructor:
4772 case Sema::CXXInvalid:
4773 return false;
4774 }
4775
4776 // -- if the class is a non-empty union, or for each non-empty anonymous
4777 // union member of a non-union class, exactly one non-static data member
4778 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00004779 //
4780 // If we squint, this is guaranteed, since exactly one non-static data member
4781 // will be initialized (if the constructor isn't deleted), we just don't know
4782 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00004783 if (Ctor && ClassDecl->isUnion())
Richard Smith4086a132012-06-10 07:07:24 +00004784 return true;
Richard Smithb5800092012-06-10 05:43:50 +00004785
4786 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00004787 if (Ctor && ClassDecl->getNumVBases())
4788 return false;
4789
4790 // C++1y [class.copy]p26:
4791 // -- [the class] is a literal type, and
4792 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00004793 return false;
4794
4795 // -- every constructor involved in initializing [...] base class
4796 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00004797 // -- the assignment operator selected to copy/move each direct base
4798 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00004799 for (const auto &B : ClassDecl->bases()) {
4800 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00004801 if (!BaseType) continue;
4802
4803 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004804 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smithb5800092012-06-10 05:43:50 +00004805 return false;
4806 }
4807
4808 // -- every constructor involved in initializing non-static data members
4809 // [...] shall be a constexpr constructor;
4810 // -- every non-static data member and base class sub-object shall be
4811 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00004812 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00004813 // thereof), the assignment operator selected to copy/move that member is
4814 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004815 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00004816 if (F->isInvalidDecl())
4817 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00004818 QualType BaseType = S.Context.getBaseElementType(F->getType());
4819 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00004820 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004821 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
4822 BaseType.getCVRQualifiers(),
4823 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00004824 return false;
Richard Smithb5800092012-06-10 05:43:50 +00004825 }
4826 }
4827
4828 // All OK, it's constexpr!
4829 return true;
4830}
4831
Richard Smithd3b5c9082012-07-27 04:22:15 +00004832static Sema::ImplicitExceptionSpecification
4833computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4834 switch (S.getSpecialMember(MD)) {
4835 case Sema::CXXDefaultConstructor:
4836 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4837 case Sema::CXXCopyConstructor:
4838 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4839 case Sema::CXXCopyAssignment:
4840 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4841 case Sema::CXXMoveConstructor:
4842 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4843 case Sema::CXXMoveAssignment:
4844 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4845 case Sema::CXXDestructor:
4846 return S.ComputeDefaultedDtorExceptionSpec(MD);
4847 case Sema::CXXInvalid:
4848 break;
4849 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00004850 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4851 "only special members have implicit exception specs");
4852 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00004853}
4854
Reid Kleckner78af0702013-08-27 23:08:25 +00004855static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4856 CXXMethodDecl *MD) {
4857 FunctionProtoType::ExtProtoInfo EPI;
4858
4859 // Build an exception specification pointing back at this member.
Richard Smith8acb4282014-07-31 21:57:55 +00004860 EPI.ExceptionSpec.Type = EST_Unevaluated;
4861 EPI.ExceptionSpec.SourceDecl = MD;
Reid Kleckner78af0702013-08-27 23:08:25 +00004862
4863 // Set the calling convention to the default for C++ instance methods.
4864 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4865 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4866 /*IsCXXMethod=*/true));
4867 return EPI;
4868}
4869
Richard Smithd3b5c9082012-07-27 04:22:15 +00004870void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4871 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4872 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4873 return;
4874
Richard Smith7f782272012-07-30 23:48:14 +00004875 // Evaluate the exception specification.
Richard Smith8acb4282014-07-31 21:57:55 +00004876 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
Richard Smith564417a2014-03-20 21:47:22 +00004877
Richard Smith7f782272012-07-30 23:48:14 +00004878 // Update the type of the special member to use it.
Richard Smith8acb4282014-07-31 21:57:55 +00004879 UpdateExceptionSpec(MD, ESI);
Richard Smith7f782272012-07-30 23:48:14 +00004880
4881 // A user-provided destructor can be defined outside the class. When that
4882 // happens, be sure to update the exception specification on both
4883 // declarations.
4884 const FunctionProtoType *CanonicalFPT =
4885 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4886 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smith8acb4282014-07-31 21:57:55 +00004887 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00004888}
4889
Richard Smithb9e90b12012-05-15 04:39:51 +00004890void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4891 CXXRecordDecl *RD = MD->getParent();
4892 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004893
Richard Smithb9e90b12012-05-15 04:39:51 +00004894 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4895 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00004896
4897 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00004898 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00004899 bool First = MD == MD->getCanonicalDecl();
4900
4901 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004902
4903 // C++11 [dcl.fct.def.default]p1:
4904 // A function that is explicitly defaulted shall
4905 // -- be a special member function (checked elsewhere),
4906 // -- have the same type (except for ref-qualifiers, and except that a
4907 // copy operation can take a non-const reference) as an implicit
4908 // declaration, and
4909 // -- not have default arguments.
4910 unsigned ExpectedParams = 1;
4911 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4912 ExpectedParams = 0;
4913 if (MD->getNumParams() != ExpectedParams) {
4914 // This also checks for default arguments: a copy or move constructor with a
4915 // default argument is classified as a default constructor, and assignment
4916 // operations and destructors can't have default arguments.
4917 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4918 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00004919 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00004920 } else if (MD->isVariadic()) {
4921 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4922 << CSM << MD->getSourceRange();
4923 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00004924 }
4925
Richard Smithb9e90b12012-05-15 04:39:51 +00004926 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00004927
Richard Smithb5800092012-06-10 05:43:50 +00004928 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00004929 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00004930 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00004931 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00004932 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00004933
Richard Smithb9e90b12012-05-15 04:39:51 +00004934 QualType ReturnType = Context.VoidTy;
4935 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4936 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00004937 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00004938 QualType ExpectedReturnType =
4939 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4940 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4941 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4942 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4943 HadError = true;
4944 }
4945
4946 // A defaulted special member cannot have cv-qualifiers.
4947 if (Type->getTypeQuals()) {
4948 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004949 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
Richard Smithb9e90b12012-05-15 04:39:51 +00004950 HadError = true;
4951 }
4952 }
4953
4954 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00004955 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00004956 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004957 if (ExpectedParams && ArgType->isReferenceType()) {
4958 // Argument must be reference to possibly-const T.
4959 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00004960 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00004961
4962 if (ReferentType.isVolatileQualified()) {
4963 Diag(MD->getLocation(),
4964 diag::err_defaulted_special_member_volatile_param) << CSM;
4965 HadError = true;
4966 }
4967
Richard Smithb5800092012-06-10 05:43:50 +00004968 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00004969 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4970 Diag(MD->getLocation(),
4971 diag::err_defaulted_special_member_copy_const_param)
4972 << (CSM == CXXCopyAssignment);
4973 // FIXME: Explain why this special member can't be const.
4974 } else {
4975 Diag(MD->getLocation(),
4976 diag::err_defaulted_special_member_move_const_param)
4977 << (CSM == CXXMoveAssignment);
4978 }
4979 HadError = true;
4980 }
Richard Smithb9e90b12012-05-15 04:39:51 +00004981 } else if (ExpectedParams) {
4982 // A copy assignment operator can take its argument by value, but a
4983 // defaulted one cannot.
4984 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00004985 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00004986 HadError = true;
4987 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00004988
Richard Smithcc36f692011-12-22 02:22:31 +00004989 // C++11 [dcl.fct.def.default]p2:
4990 // An explicitly-defaulted function may be declared constexpr only if it
4991 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00004992 // Do not apply this rule to members of class templates, since core issue 1358
4993 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00004994 // functions which cannot be constexpr (for non-constructors in C++11 and for
4995 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00004996 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4997 HasConstParam);
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004998 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
Richard Smith99005e62013-05-07 03:19:20 +00004999 : isa<CXXConstructorDecl>(MD)) &&
5000 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00005001 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5002 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00005003 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00005004 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00005005 }
Richard Smithbd305122012-12-11 01:14:52 +00005006
Richard Smithcc36f692011-12-22 02:22:31 +00005007 // and may have an explicit exception-specification only if it is compatible
5008 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00005009 if (Type->hasExceptionSpec()) {
5010 // Delay the check if this is the first declaration of the special member,
5011 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00005012 if (First) {
5013 // If the exception specification needs to be instantiated, do so now,
5014 // before we clobber it with an EST_Unevaluated specification below.
5015 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5016 InstantiateExceptionSpec(MD->getLocStart(), MD);
5017 Type = MD->getType()->getAs<FunctionProtoType>();
5018 }
Richard Smithbd305122012-12-11 01:14:52 +00005019 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00005020 } else
Richard Smithbd305122012-12-11 01:14:52 +00005021 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5022 }
Richard Smithcc36f692011-12-22 02:22:31 +00005023
5024 // If a function is explicitly defaulted on its first declaration,
5025 if (First) {
5026 // -- it is implicitly considered to be constexpr if the implicit
5027 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00005028 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00005029
Richard Smithb9e90b12012-05-15 04:39:51 +00005030 // -- it is implicitly considered to have the same exception-specification
5031 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00005032 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00005033 EPI.ExceptionSpec.Type = EST_Unevaluated;
5034 EPI.ExceptionSpec.SourceDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00005035 MD->setType(Context.getFunctionType(ReturnType,
5036 ArrayRef<QualType>(&ArgType,
5037 ExpectedParams),
5038 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00005039 }
5040
Richard Smithb9e90b12012-05-15 04:39:51 +00005041 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00005042 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00005043 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00005044 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00005045 // C++11 [dcl.fct.def.default]p4:
5046 // [For a] user-provided explicitly-defaulted function [...] if such a
5047 // function is implicitly defined as deleted, the program is ill-formed.
5048 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith566184a2014-01-22 20:09:10 +00005049 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00005050 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00005051 }
5052 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00005053
Richard Smithb9e90b12012-05-15 04:39:51 +00005054 if (HadError)
5055 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00005056}
5057
Richard Smithbd305122012-12-11 01:14:52 +00005058/// Check whether the exception specification provided for an
5059/// explicitly-defaulted special member matches the exception specification
5060/// that would have been generated for an implicit special member, per
5061/// C++11 [dcl.fct.def.default]p2.
5062void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5063 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
5064 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00005065 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5066 /*IsCXXMethod=*/true);
5067 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smith8acb4282014-07-31 21:57:55 +00005068 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5069 .getExceptionSpec();
Richard Smithbd305122012-12-11 01:14:52 +00005070 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005071 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00005072
5073 // Ensure that it matches.
5074 CheckEquivalentExceptionSpec(
5075 PDiag(diag::err_incorrect_defaulted_exception_spec)
5076 << getSpecialMember(MD), PDiag(),
5077 ImplicitType, SourceLocation(),
5078 SpecifiedType, MD->getLocation());
5079}
5080
Alp Tokerae3a9442013-10-18 05:54:19 +00005081void Sema::CheckDelayedMemberExceptionSpecs() {
5082 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
5083 2> Checks;
5084 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
Richard Smithbd305122012-12-11 01:14:52 +00005085
Alp Tokerae3a9442013-10-18 05:54:19 +00005086 std::swap(Checks, DelayedDestructorExceptionSpecChecks);
5087 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5088
5089 // Perform any deferred checking of exception specifications for virtual
5090 // destructors.
5091 for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
5092 const CXXDestructorDecl *Dtor = Checks[i].first;
5093 assert(!Dtor->getParent()->isDependentType() &&
5094 "Should not ever add destructors of templates into the list.");
5095 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
5096 }
5097
5098 // Check that any explicitly-defaulted methods have exception specifications
5099 // compatible with their implicit exception specifications.
5100 for (unsigned I = 0, N = Specs.size(); I != N; ++I)
5101 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
5102 Specs[I].second);
Richard Smithbd305122012-12-11 01:14:52 +00005103}
5104
Richard Smithd951a1d2012-02-18 02:02:13 +00005105namespace {
5106struct SpecialMemberDeletionInfo {
5107 Sema &S;
5108 CXXMethodDecl *MD;
5109 Sema::CXXSpecialMember CSM;
Richard Smith852265f2012-03-30 20:53:28 +00005110 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00005111
5112 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00005113 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00005114 SourceLocation Loc;
5115
5116 bool AllFieldsAreConst;
5117
5118 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith852265f2012-03-30 20:53:28 +00005119 Sema::CXXSpecialMember CSM, bool Diagnose)
5120 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smithd951a1d2012-02-18 02:02:13 +00005121 IsConstructor(false), IsAssignment(false), IsMove(false),
Richard Smith41c35d62013-11-27 03:39:20 +00005122 ConstArg(false), Loc(MD->getLocation()),
Richard Smithd951a1d2012-02-18 02:02:13 +00005123 AllFieldsAreConst(true) {
5124 switch (CSM) {
5125 case Sema::CXXDefaultConstructor:
5126 case Sema::CXXCopyConstructor:
5127 IsConstructor = true;
5128 break;
5129 case Sema::CXXMoveConstructor:
5130 IsConstructor = true;
5131 IsMove = true;
5132 break;
5133 case Sema::CXXCopyAssignment:
5134 IsAssignment = true;
5135 break;
5136 case Sema::CXXMoveAssignment:
5137 IsAssignment = true;
5138 IsMove = true;
5139 break;
5140 case Sema::CXXDestructor:
5141 break;
5142 case Sema::CXXInvalid:
5143 llvm_unreachable("invalid special member kind");
5144 }
5145
5146 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00005147 if (const ReferenceType *RT =
5148 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5149 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00005150 }
5151 }
5152
5153 bool inUnion() const { return MD->getParent()->isUnion(); }
5154
5155 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00005156 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00005157 unsigned Quals, bool IsMutable) {
5158 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5159 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00005160 }
5161
Richard Smith852265f2012-03-30 20:53:28 +00005162 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00005163
Richard Smith852265f2012-03-30 20:53:28 +00005164 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00005165 bool shouldDeleteForField(FieldDecl *FD);
5166 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00005167
Richard Smithaf136f82012-07-18 03:51:16 +00005168 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5169 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00005170 bool shouldDeleteForSubobjectCall(Subobject Subobj,
5171 Sema::SpecialMemberOverloadResult *SMOR,
5172 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00005173
5174 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00005175};
5176}
5177
John McCalld4274212012-04-09 20:53:23 +00005178/// Is the given special member inaccessible when used on the given
5179/// sub-object.
5180bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5181 CXXMethodDecl *target) {
5182 /// If we're operating on a base class, the object type is the
5183 /// type of this special member.
5184 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005185 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00005186 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5187 objectTy = S.Context.getTypeDeclType(MD->getParent());
5188 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5189
5190 // If we're operating on a field, the object type is the type of the field.
5191 } else {
5192 objectTy = S.Context.getTypeDeclType(target->getParent());
5193 }
5194
5195 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5196}
5197
Richard Smith852265f2012-03-30 20:53:28 +00005198/// Check whether we should delete a special member due to the implicit
5199/// definition containing a call to a special member of a subobject.
5200bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5201 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5202 bool IsDtorCallInCtor) {
5203 CXXMethodDecl *Decl = SMOR->getMethod();
5204 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5205
5206 int DiagKind = -1;
5207
5208 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5209 DiagKind = !Decl ? 0 : 1;
5210 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5211 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00005212 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00005213 DiagKind = 3;
5214 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5215 !Decl->isTrivial()) {
5216 // A member of a union must have a trivial corresponding special member.
5217 // As a weird special case, a destructor call from a union's constructor
5218 // must be accessible and non-deleted, but need not be trivial. Such a
5219 // destructor is never actually called, but is semantically checked as
5220 // if it were.
5221 DiagKind = 4;
5222 }
5223
5224 if (DiagKind == -1)
5225 return false;
5226
5227 if (Diagnose) {
5228 if (Field) {
5229 S.Diag(Field->getLocation(),
5230 diag::note_deleted_special_member_class_subobject)
5231 << CSM << MD->getParent() << /*IsField*/true
5232 << Field << DiagKind << IsDtorCallInCtor;
5233 } else {
5234 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5235 S.Diag(Base->getLocStart(),
5236 diag::note_deleted_special_member_class_subobject)
5237 << CSM << MD->getParent() << /*IsField*/false
5238 << Base->getType() << DiagKind << IsDtorCallInCtor;
5239 }
5240
5241 if (DiagKind == 1)
5242 S.NoteDeletedFunction(Decl);
5243 // FIXME: Explain inaccessibility if DiagKind == 3.
5244 }
5245
5246 return true;
5247}
5248
Richard Smith921bd202012-02-26 09:11:52 +00005249/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00005250/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00005251bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00005252 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00005253 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00005254 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00005255
5256 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00005257 // -- any direct or virtual base class, or non-static data member with no
5258 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00005259 // either M has no default constructor or overload resolution as applied
5260 // to M's default constructor results in an ambiguity or in a function
5261 // that is deleted or inaccessible
5262 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5263 // -- a direct or virtual base class B that cannot be copied/moved because
5264 // overload resolution, as applied to B's corresponding special member,
5265 // results in an ambiguity or a function that is deleted or inaccessible
5266 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00005267 // C++11 [class.dtor]p5:
5268 // -- any direct or virtual base class [...] has a type with a destructor
5269 // that is deleted or inaccessible
5270 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005271 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00005272 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5273 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005274 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005275
Richard Smith852265f2012-03-30 20:53:28 +00005276 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5277 // -- any direct or virtual base class or non-static data member has a
5278 // type with a destructor that is deleted or inaccessible
5279 if (IsConstructor) {
5280 Sema::SpecialMemberOverloadResult *SMOR =
5281 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5282 false, false, false, false, false);
5283 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5284 return true;
5285 }
5286
Richard Smith921bd202012-02-26 09:11:52 +00005287 return false;
5288}
5289
5290/// Check whether we should delete a special member function due to the class
5291/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00005292bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005293 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smithaf136f82012-07-18 03:51:16 +00005294 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00005295}
5296
5297/// Check whether we should delete a special member function due to the class
5298/// having a particular non-static data member.
5299bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5300 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5301 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5302
5303 if (CSM == Sema::CXXDefaultConstructor) {
5304 // For a default constructor, all references must be initialized in-class
5305 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00005306 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5307 if (Diagnose)
5308 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5309 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005310 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005311 }
Richard Smith619ecdc2012-02-27 06:07:25 +00005312 // C++11 [class.ctor]p5: any non-variant non-static data member of
5313 // const-qualified type (or array thereof) with no
5314 // brace-or-equal-initializer does not have a user-provided default
5315 // constructor.
5316 if (!inUnion() && FieldType.isConstQualified() &&
5317 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00005318 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5319 if (Diagnose)
5320 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005321 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00005322 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005323 }
5324
5325 if (inUnion() && !FieldType.isConstQualified())
5326 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005327 } else if (CSM == Sema::CXXCopyConstructor) {
5328 // For a copy constructor, data members must not be of rvalue reference
5329 // type.
Richard Smith852265f2012-03-30 20:53:28 +00005330 if (FieldType->isRValueReferenceType()) {
5331 if (Diagnose)
5332 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5333 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00005334 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005335 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005336 } else if (IsAssignment) {
5337 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00005338 if (FieldType->isReferenceType()) {
5339 if (Diagnose)
5340 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5341 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005342 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005343 }
5344 if (!FieldRecord && FieldType.isConstQualified()) {
5345 // C++11 [class.copy]p23:
5346 // -- a non-static data member of const non-class type (or array thereof)
5347 if (Diagnose)
5348 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005349 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00005350 return true;
5351 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005352 }
5353
5354 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005355 // Some additional restrictions exist on the variant members.
5356 if (!inUnion() && FieldRecord->isUnion() &&
5357 FieldRecord->isAnonymousStructOrUnion()) {
5358 bool AllVariantFieldsAreConst = true;
5359
Richard Smith5704fe82012-03-29 19:00:10 +00005360 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005361 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005362 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00005363
5364 if (!UnionFieldType.isConstQualified())
5365 AllVariantFieldsAreConst = false;
5366
Richard Smith921bd202012-02-26 09:11:52 +00005367 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5368 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005369 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00005370 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00005371 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005372 }
5373
5374 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00005375 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005376 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005377 if (Diagnose)
5378 S.Diag(FieldRecord->getLocation(),
5379 diag::note_deleted_default_ctor_all_const)
5380 << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00005381 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005382 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005383
Richard Smith5704fe82012-03-29 19:00:10 +00005384 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00005385 // This is technically non-conformant, but sanity demands it.
5386 return false;
5387 }
5388
Richard Smithaf136f82012-07-18 03:51:16 +00005389 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5390 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00005391 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005392 }
5393
5394 return false;
5395}
5396
5397/// C++11 [class.ctor] p5:
5398/// A defaulted default constructor for a class X is defined as deleted if
5399/// X is a union and all of its variant members are of const-qualified type.
5400bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00005401 // This is a silly definition, because it gives an empty union a deleted
5402 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00005403 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005404 !MD->getParent()->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005405 if (Diagnose)
5406 S.Diag(MD->getParent()->getLocation(),
5407 diag::note_deleted_default_ctor_all_const)
5408 << MD->getParent() << /*not anonymous union*/0;
5409 return true;
5410 }
5411 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005412}
5413
5414/// Determine whether a defaulted special member function should be defined as
5415/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5416/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00005417bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5418 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00005419 if (MD->isInvalidDecl())
5420 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00005421 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00005422 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005423 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00005424 return false;
5425
Richard Smithd951a1d2012-02-18 02:02:13 +00005426 // C++11 [expr.lambda.prim]p19:
5427 // The closure type associated with a lambda-expression has a
5428 // deleted (8.4.3) default constructor and a deleted copy
5429 // assignment operator.
5430 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00005431 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5432 if (Diagnose)
5433 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00005434 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005435 }
5436
Richard Smith6f1e2c62012-04-02 20:59:25 +00005437 // For an anonymous struct or union, the copy and assignment special members
5438 // will never be used, so skip the check. For an anonymous union declared at
5439 // namespace scope, the constructor and destructor are used.
5440 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5441 RD->isAnonymousStructOrUnion())
5442 return false;
5443
Richard Smith852265f2012-03-30 20:53:28 +00005444 // C++11 [class.copy]p7, p18:
5445 // If the class definition declares a move constructor or move assignment
5446 // operator, an implicitly declared copy constructor or copy assignment
5447 // operator is defined as deleted.
5448 if (MD->isImplicit() &&
5449 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005450 CXXMethodDecl *UserDeclaredMove = nullptr;
Richard Smith852265f2012-03-30 20:53:28 +00005451
5452 // In Microsoft mode, a user-declared move only causes the deletion of the
5453 // corresponding copy operation, not both copy operations.
5454 if (RD->hasUserDeclaredMoveConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005455 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00005456 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005457
5458 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005459 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005460 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005461 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005462 break;
5463 }
5464 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005465 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005466 } else if (RD->hasUserDeclaredMoveAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005467 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00005468 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005469
5470 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005471 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005472 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005473 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005474 break;
5475 }
5476 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005477 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005478 }
5479
5480 if (UserDeclaredMove) {
5481 Diag(UserDeclaredMove->getLocation(),
5482 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00005483 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00005484 << UserDeclaredMove->isMoveAssignmentOperator();
5485 return true;
5486 }
5487 }
Alexis Huntd6da8762011-10-10 06:18:57 +00005488
Richard Smith6f1e2c62012-04-02 20:59:25 +00005489 // Do access control from the special member function
5490 ContextRAII MethodContext(*this, MD);
5491
Richard Smith921bd202012-02-26 09:11:52 +00005492 // C++11 [class.dtor]p5:
5493 // -- for a virtual destructor, lookup of the non-array deallocation function
5494 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00005495 if (CSM == CXXDestructor && MD->isVirtual()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005496 FunctionDecl *OperatorDelete = nullptr;
Richard Smith921bd202012-02-26 09:11:52 +00005497 DeclarationName Name =
5498 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5499 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00005500 OperatorDelete, false)) {
5501 if (Diagnose)
5502 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00005503 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005504 }
Richard Smith921bd202012-02-26 09:11:52 +00005505 }
5506
Richard Smith852265f2012-03-30 20:53:28 +00005507 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00005508
Aaron Ballman574705e2014-03-13 15:41:46 +00005509 for (auto &BI : RD->bases())
5510 if (!BI.isVirtual() &&
5511 SMI.shouldDeleteForBase(&BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005512 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005513
Richard Smithd1627032013-07-22 18:06:23 +00005514 // Per DR1611, do not consider virtual bases of constructors of abstract
5515 // classes, since we are not going to construct them.
Richard Smithbc46e432013-07-22 02:56:56 +00005516 if (!RD->isAbstract() || !SMI.IsConstructor) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005517 for (auto &BI : RD->vbases())
5518 if (SMI.shouldDeleteForBase(&BI))
Richard Smithbc46e432013-07-22 02:56:56 +00005519 return true;
5520 }
Alexis Huntea6f0322011-05-11 22:34:38 +00005521
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005522 for (auto *FI : RD->fields())
Richard Smithd951a1d2012-02-18 02:02:13 +00005523 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005524 SMI.shouldDeleteForField(FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00005525 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005526
Richard Smithd951a1d2012-02-18 02:02:13 +00005527 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00005528 return true;
5529
5530 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005531}
5532
Richard Smith92f241f2012-12-08 02:53:02 +00005533/// Perform lookup for a special member of the specified kind, and determine
5534/// whether it is trivial. If the triviality can be determined without the
5535/// lookup, skip it. This is intended for use when determining whether a
5536/// special member of a containing object is trivial, and thus does not ever
5537/// perform overload resolution for default constructors.
5538///
5539/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5540/// member that was most likely to be intended to be trivial, if any.
5541static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5542 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00005543 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00005544 if (Selected)
Craig Topperc3ec1492014-05-26 06:22:03 +00005545 *Selected = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005546
5547 switch (CSM) {
5548 case Sema::CXXInvalid:
5549 llvm_unreachable("not a special member");
5550
5551 case Sema::CXXDefaultConstructor:
5552 // C++11 [class.ctor]p5:
5553 // A default constructor is trivial if:
5554 // - all the [direct subobjects] have trivial default constructors
5555 //
5556 // Note, no overload resolution is performed in this case.
5557 if (RD->hasTrivialDefaultConstructor())
5558 return true;
5559
5560 if (Selected) {
5561 // If there's a default constructor which could have been trivial, dig it
5562 // out. Otherwise, if there's any user-provided default constructor, point
5563 // to that as an example of why there's not a trivial one.
Craig Topperc3ec1492014-05-26 06:22:03 +00005564 CXXConstructorDecl *DefCtor = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005565 if (RD->needsImplicitDefaultConstructor())
5566 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005567 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005568 if (!CI->isDefaultConstructor())
5569 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005570 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005571 if (!DefCtor->isUserProvided())
5572 break;
5573 }
5574
5575 *Selected = DefCtor;
5576 }
5577
5578 return false;
5579
5580 case Sema::CXXDestructor:
5581 // C++11 [class.dtor]p5:
5582 // A destructor is trivial if:
5583 // - all the direct [subobjects] have trivial destructors
5584 if (RD->hasTrivialDestructor())
5585 return true;
5586
5587 if (Selected) {
5588 if (RD->needsImplicitDestructor())
5589 S.DeclareImplicitDestructor(RD);
5590 *Selected = RD->getDestructor();
5591 }
5592
5593 return false;
5594
5595 case Sema::CXXCopyConstructor:
5596 // C++11 [class.copy]p12:
5597 // A copy constructor is trivial if:
5598 // - the constructor selected to copy each direct [subobject] is trivial
5599 if (RD->hasTrivialCopyConstructor()) {
5600 if (Quals == Qualifiers::Const)
5601 // We must either select the trivial copy constructor or reach an
5602 // ambiguity; no need to actually perform overload resolution.
5603 return true;
5604 } else if (!Selected) {
5605 return false;
5606 }
5607 // In C++98, we are not supposed to perform overload resolution here, but we
5608 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5609 // cases like B as having a non-trivial copy constructor:
5610 // struct A { template<typename T> A(T&); };
5611 // struct B { mutable A a; };
5612 goto NeedOverloadResolution;
5613
5614 case Sema::CXXCopyAssignment:
5615 // C++11 [class.copy]p25:
5616 // A copy assignment operator is trivial if:
5617 // - the assignment operator selected to copy each direct [subobject] is
5618 // trivial
5619 if (RD->hasTrivialCopyAssignment()) {
5620 if (Quals == Qualifiers::Const)
5621 return true;
5622 } else if (!Selected) {
5623 return false;
5624 }
5625 // In C++98, we are not supposed to perform overload resolution here, but we
5626 // treat that as a language defect.
5627 goto NeedOverloadResolution;
5628
5629 case Sema::CXXMoveConstructor:
5630 case Sema::CXXMoveAssignment:
5631 NeedOverloadResolution:
5632 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005633 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00005634
5635 // The standard doesn't describe how to behave if the lookup is ambiguous.
5636 // We treat it as not making the member non-trivial, just like the standard
5637 // mandates for the default constructor. This should rarely matter, because
5638 // the member will also be deleted.
5639 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5640 return true;
5641
5642 if (!SMOR->getMethod()) {
5643 assert(SMOR->getKind() ==
5644 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5645 return false;
5646 }
5647
5648 // We deliberately don't check if we found a deleted special member. We're
5649 // not supposed to!
5650 if (Selected)
5651 *Selected = SMOR->getMethod();
5652 return SMOR->getMethod()->isTrivial();
5653 }
5654
5655 llvm_unreachable("unknown special method kind");
5656}
5657
Benjamin Kramer3e350262013-02-15 12:30:38 +00005658static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005659 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00005660 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005661 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005662
5663 // Look for constructor templates.
5664 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5665 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5666 if (CXXConstructorDecl *CD =
5667 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5668 return CD;
5669 }
5670
Craig Topperc3ec1492014-05-26 06:22:03 +00005671 return nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005672}
5673
5674/// The kind of subobject we are checking for triviality. The values of this
5675/// enumeration are used in diagnostics.
5676enum TrivialSubobjectKind {
5677 /// The subobject is a base class.
5678 TSK_BaseClass,
5679 /// The subobject is a non-static data member.
5680 TSK_Field,
5681 /// The object is actually the complete object.
5682 TSK_CompleteObject
5683};
5684
5685/// Check whether the special member selected for a given type would be trivial.
5686static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00005687 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00005688 Sema::CXXSpecialMember CSM,
5689 TrivialSubobjectKind Kind,
5690 bool Diagnose) {
5691 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5692 if (!SubRD)
5693 return true;
5694
5695 CXXMethodDecl *Selected;
5696 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005697 ConstRHS, Diagnose ? &Selected : nullptr))
Richard Smith92f241f2012-12-08 02:53:02 +00005698 return true;
5699
5700 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00005701 if (ConstRHS)
5702 SubType.addConst();
5703
Richard Smith92f241f2012-12-08 02:53:02 +00005704 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5705 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5706 << Kind << SubType.getUnqualifiedType();
5707 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5708 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5709 } else if (!Selected)
5710 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5711 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5712 else if (Selected->isUserProvided()) {
5713 if (Kind == TSK_CompleteObject)
5714 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5715 << Kind << SubType.getUnqualifiedType() << CSM;
5716 else {
5717 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5718 << Kind << SubType.getUnqualifiedType() << CSM;
5719 S.Diag(Selected->getLocation(), diag::note_declared_at);
5720 }
5721 } else {
5722 if (Kind != TSK_CompleteObject)
5723 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5724 << Kind << SubType.getUnqualifiedType() << CSM;
5725
5726 // Explain why the defaulted or deleted special member isn't trivial.
5727 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5728 }
5729 }
5730
5731 return false;
5732}
5733
5734/// Check whether the members of a class type allow a special member to be
5735/// trivial.
5736static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5737 Sema::CXXSpecialMember CSM,
5738 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005739 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005740 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5741 continue;
5742
5743 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5744
5745 // Pretend anonymous struct or union members are members of this class.
5746 if (FI->isAnonymousStructOrUnion()) {
5747 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5748 CSM, ConstArg, Diagnose))
5749 return false;
5750 continue;
5751 }
5752
5753 // C++11 [class.ctor]p5:
5754 // A default constructor is trivial if [...]
5755 // -- no non-static data member of its class has a
5756 // brace-or-equal-initializer
5757 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5758 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005759 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00005760 return false;
5761 }
5762
5763 // Objective C ARC 4.3.5:
5764 // [...] nontrivally ownership-qualified types are [...] not trivially
5765 // default constructible, copy constructible, move constructible, copy
5766 // assignable, move assignable, or destructible [...]
5767 if (S.getLangOpts().ObjCAutoRefCount &&
5768 FieldType.hasNonTrivialObjCLifetime()) {
5769 if (Diagnose)
5770 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5771 << RD << FieldType.getObjCLifetime();
5772 return false;
5773 }
5774
Richard Smith41c35d62013-11-27 03:39:20 +00005775 bool ConstRHS = ConstArg && !FI->isMutable();
5776 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
5777 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005778 return false;
5779 }
5780
5781 return true;
5782}
5783
5784/// Diagnose why the specified class does not have a trivial special member of
5785/// the given kind.
5786void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5787 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00005788
Richard Smith41c35d62013-11-27 03:39:20 +00005789 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
5790 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00005791 TSK_CompleteObject, /*Diagnose*/true);
5792}
5793
5794/// Determine whether a defaulted or deleted special member function is trivial,
5795/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5796/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5797bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5798 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00005799 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5800
5801 CXXRecordDecl *RD = MD->getParent();
5802
5803 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00005804
Richard Smith2002bfe2013-11-04 02:02:27 +00005805 // C++11 [class.copy]p12, p25: [DR1593]
5806 // A [special member] is trivial if [...] its parameter-type-list is
5807 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00005808 switch (CSM) {
5809 case CXXDefaultConstructor:
5810 case CXXDestructor:
5811 // Trivial default constructors and destructors cannot have parameters.
5812 break;
5813
5814 case CXXCopyConstructor:
5815 case CXXCopyAssignment: {
5816 // Trivial copy operations always have const, non-volatile parameter types.
5817 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00005818 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005819 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5820 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5821 if (Diagnose)
5822 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5823 << Param0->getSourceRange() << Param0->getType()
5824 << Context.getLValueReferenceType(
5825 Context.getRecordType(RD).withConst());
5826 return false;
5827 }
5828 break;
5829 }
5830
5831 case CXXMoveConstructor:
5832 case CXXMoveAssignment: {
5833 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00005834 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005835 const RValueReferenceType *RT =
5836 Param0->getType()->getAs<RValueReferenceType>();
5837 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5838 if (Diagnose)
5839 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5840 << Param0->getSourceRange() << Param0->getType()
5841 << Context.getRValueReferenceType(Context.getRecordType(RD));
5842 return false;
5843 }
5844 break;
5845 }
5846
5847 case CXXInvalid:
5848 llvm_unreachable("not a special member");
5849 }
5850
Richard Smith92f241f2012-12-08 02:53:02 +00005851 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5852 if (Diagnose)
5853 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5854 diag::note_nontrivial_default_arg)
5855 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5856 return false;
5857 }
5858 if (MD->isVariadic()) {
5859 if (Diagnose)
5860 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5861 return false;
5862 }
5863
5864 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5865 // A copy/move [constructor or assignment operator] is trivial if
5866 // -- the [member] selected to copy/move each direct base class subobject
5867 // is trivial
5868 //
5869 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5870 // A [default constructor or destructor] is trivial if
5871 // -- all the direct base classes have trivial [default constructors or
5872 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00005873 for (const auto &BI : RD->bases())
5874 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00005875 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005876 return false;
5877
5878 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5879 // A copy/move [constructor or assignment operator] for a class X is
5880 // trivial if
5881 // -- for each non-static data member of X that is of class type (or array
5882 // thereof), the constructor selected to copy/move that member is
5883 // trivial
5884 //
5885 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5886 // A [default constructor or destructor] is trivial if
5887 // -- for all of the non-static data members of its class that are of class
5888 // type (or array thereof), each such class has a trivial [default
5889 // constructor or destructor]
5890 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5891 return false;
5892
5893 // C++11 [class.dtor]p5:
5894 // A destructor is trivial if [...]
5895 // -- the destructor is not virtual
5896 if (CSM == CXXDestructor && MD->isVirtual()) {
5897 if (Diagnose)
5898 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5899 return false;
5900 }
5901
5902 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5903 // A [special member] for class X is trivial if [...]
5904 // -- class X has no virtual functions and no virtual base classes
5905 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5906 if (!Diagnose)
5907 return false;
5908
5909 if (RD->getNumVBases()) {
5910 // Check for virtual bases. We already know that the corresponding
5911 // member in all bases is trivial, so vbases must all be direct.
5912 CXXBaseSpecifier &BS = *RD->vbases_begin();
5913 assert(BS.isVirtual());
5914 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5915 return false;
5916 }
5917
5918 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005919 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005920 if (MI->isVirtual()) {
5921 SourceLocation MLoc = MI->getLocStart();
5922 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5923 return false;
5924 }
5925 }
5926
5927 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5928 }
5929
5930 // Looks like it's trivial!
5931 return true;
5932}
5933
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005934/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00005935namespace {
5936 struct FindHiddenVirtualMethodData {
5937 Sema *S;
5938 CXXMethodDecl *Method;
5939 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005940 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00005941 };
5942}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005943
David Blaikie282c92a2012-10-19 00:53:08 +00005944/// \brief Check whether any most overriden method from MD in Methods
5945static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00005946 const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00005947 if (MD->size_overridden_methods() == 0)
5948 return Methods.count(MD->getCanonicalDecl());
5949 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5950 E = MD->end_overridden_methods();
5951 I != E; ++I)
5952 if (CheckMostOverridenMethods(*I, Methods))
5953 return true;
5954 return false;
5955}
5956
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005957/// \brief Member lookup function that determines whether a given C++
5958/// method overloads virtual methods in a base class without overriding any,
5959/// to be used with CXXRecordDecl::lookupInBases().
5960static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5961 CXXBasePath &Path,
5962 void *UserData) {
5963 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5964
5965 FindHiddenVirtualMethodData &Data
5966 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5967
5968 DeclarationName Name = Data.Method->getDeclName();
5969 assert(Name.getNameKind() == DeclarationName::Identifier);
5970
5971 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005972 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005973 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00005974 !Path.Decls.empty();
5975 Path.Decls = Path.Decls.slice(1)) {
5976 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005977 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00005978 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005979 foundSameNameMethod = true;
5980 // Interested only in hidden virtual methods.
5981 if (!MD->isVirtual())
5982 continue;
5983 // If the method we are checking overrides a method from its base
Aaron Ballman04559a72014-07-30 23:50:53 +00005984 // don't warn about the other overloaded methods. Clang deviates from GCC
5985 // by only diagnosing overloads of inherited virtual functions that do not
5986 // override any other virtual functions in the base. GCC's
5987 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
5988 // function from a base class. These cases may be better served by a
5989 // warning (not specific to virtual functions) on call sites when the call
5990 // would select a different function from the base class, were it visible.
5991 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005992 if (!Data.S->IsOverload(Data.Method, MD, false))
5993 return true;
5994 // Collect the overload only if its hidden.
David Blaikie282c92a2012-10-19 00:53:08 +00005995 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005996 overloadedMethods.push_back(MD);
5997 }
5998 }
5999
6000 if (foundSameNameMethod)
6001 Data.OverloadedMethods.append(overloadedMethods.begin(),
6002 overloadedMethods.end());
6003 return foundSameNameMethod;
6004}
6005
David Blaikie282c92a2012-10-19 00:53:08 +00006006/// \brief Add the most overriden methods from MD to Methods
6007static void AddMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00006008 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00006009 if (MD->size_overridden_methods() == 0)
6010 Methods.insert(MD->getCanonicalDecl());
6011 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6012 E = MD->end_overridden_methods();
6013 I != E; ++I)
6014 AddMostOverridenMethods(*I, Methods);
6015}
6016
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006017/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006018/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006019void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6020 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00006021 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006022 return;
6023
6024 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6025 /*bool RecordPaths=*/false,
6026 /*bool DetectVirtual=*/false);
6027 FindHiddenVirtualMethodData Data;
6028 Data.Method = MD;
6029 Data.S = this;
6030
6031 // Keep the base methods that were overriden or introduced in the subclass
6032 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006033 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00006034 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6035 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6036 NamedDecl *ND = *I;
6037 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00006038 ND = shad->getTargetDecl();
6039 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6040 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006041 }
6042
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006043 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
6044 OverloadedMethods = Data.OverloadedMethods;
6045}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006046
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006047void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6048 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6049 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6050 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6051 PartialDiagnostic PD = PDiag(
6052 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6053 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6054 Diag(overloadedMD->getLocation(), PD);
6055 }
6056}
6057
6058/// \brief Diagnose methods which overload virtual methods in a base class
6059/// without overriding any.
6060void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6061 if (MD->isInvalidDecl())
6062 return;
6063
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006064 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006065 return;
6066
6067 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6068 FindHiddenVirtualMethods(MD, OverloadedMethods);
6069 if (!OverloadedMethods.empty()) {
6070 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6071 << MD << (OverloadedMethods.size() > 1);
6072
6073 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006074 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00006075}
6076
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006077void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00006078 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006079 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00006080 SourceLocation RBrac,
6081 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006082 if (!TagDecl)
6083 return;
Mike Stump11289f42009-09-09 15:08:12 +00006084
Douglas Gregorc9f9b862009-05-11 19:58:34 +00006085 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00006086
Rafael Espindola06e1b132012-07-12 04:32:30 +00006087 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6088 if (l->getKind() != AttributeList::AT_Visibility)
6089 continue;
6090 l->setInvalid();
6091 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6092 l->getName();
6093 }
6094
David Blaikie751c5582011-09-22 02:58:26 +00006095 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00006096 // strict aliasing violation!
6097 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00006098 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00006099
Douglas Gregor0be31a22010-07-02 17:43:08 +00006100 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00006101 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006102}
6103
Douglas Gregor05379422008-11-03 17:51:48 +00006104/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6105/// special functions, such as the default constructor, copy
6106/// constructor, or destructor, to the given C++ class (C++
6107/// [special]p1). This routine can only be executed just before the
6108/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00006109void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006110 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00006111 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006112
Richard Smith6b02d462012-12-08 08:32:28 +00006113 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00006114 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006115
Richard Smith6b02d462012-12-08 08:32:28 +00006116 // If the properties or semantics of the copy constructor couldn't be
6117 // determined while the class was being declared, force a declaration
6118 // of it now.
6119 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6120 DeclareImplicitCopyConstructor(ClassDecl);
6121 }
6122
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006123 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006124 ++ASTContext::NumImplicitMoveConstructors;
6125
Richard Smith6b02d462012-12-08 08:32:28 +00006126 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6127 DeclareImplicitMoveConstructor(ClassDecl);
6128 }
6129
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006130 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6131 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00006132
6133 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006134 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00006135 // it shows up in the right place in the vtable and that we diagnose
6136 // problems with the implicit exception specification.
6137 if (ClassDecl->isDynamicClass() ||
6138 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006139 DeclareImplicitCopyAssignment(ClassDecl);
6140 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006141
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006142 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006143 ++ASTContext::NumImplicitMoveAssignmentOperators;
6144
6145 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00006146 if (ClassDecl->isDynamicClass() ||
6147 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00006148 DeclareImplicitMoveAssignment(ClassDecl);
6149 }
6150
Douglas Gregor7454c562010-07-02 20:37:36 +00006151 if (!ClassDecl->hasUserDeclaredDestructor()) {
6152 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00006153
6154 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00006155 // have to declare the destructor immediately. This ensures that, e.g., it
6156 // shows up in the right place in the vtable and that we diagnose problems
6157 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00006158 if (ClassDecl->isDynamicClass() ||
6159 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00006160 DeclareImplicitDestructor(ClassDecl);
6161 }
Douglas Gregor05379422008-11-03 17:51:48 +00006162}
6163
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006164unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Francois Pichet1c229c02011-04-22 22:18:13 +00006165 if (!D)
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006166 return 0;
Francois Pichet1c229c02011-04-22 22:18:13 +00006167
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006168 // The order of template parameters is not important here. All names
6169 // get added to the same scope.
6170 SmallVector<TemplateParameterList *, 4> ParameterLists;
6171
6172 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6173 D = TD->getTemplatedDecl();
6174
6175 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6176 ParameterLists.push_back(PSD->getTemplateParameters());
6177
6178 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6179 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6180 ParameterLists.push_back(DD->getTemplateParameterList(i));
6181
6182 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6183 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6184 ParameterLists.push_back(FTD->getTemplateParameters());
6185 }
6186 }
6187
6188 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6189 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6190 ParameterLists.push_back(TD->getTemplateParameterList(i));
6191
6192 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6193 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6194 ParameterLists.push_back(CTD->getTemplateParameters());
6195 }
6196 }
6197
6198 unsigned Count = 0;
6199 for (TemplateParameterList *Params : ParameterLists) {
6200 if (Params->size() > 0)
6201 // Ignore explicit specializations; they don't contribute to the template
6202 // depth.
6203 ++Count;
6204 for (NamedDecl *Param : *Params) {
6205 if (Param->getDeclName()) {
6206 S->AddDecl(Param);
6207 IdResolver.AddDecl(Param);
Francois Pichet1c229c02011-04-22 22:18:13 +00006208 }
6209 }
6210 }
Francois Pichet1c229c02011-04-22 22:18:13 +00006211
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006212 return Count;
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006213}
6214
John McCall48871652010-08-21 09:40:31 +00006215void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006216 if (!RecordD) return;
6217 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00006218 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00006219 PushDeclContext(S, Record);
6220}
6221
John McCall48871652010-08-21 09:40:31 +00006222void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006223 if (!RecordD) return;
6224 PopDeclContext();
6225}
6226
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006227/// This is used to implement the constant expression evaluation part of the
6228/// attribute enable_if extension. There is nothing in standard C++ which would
6229/// require reentering parameters.
6230void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6231 if (!Param)
6232 return;
6233
6234 S->AddDecl(Param);
6235 if (Param->getDeclName())
6236 IdResolver.AddDecl(Param);
6237}
6238
Douglas Gregor4d87df52008-12-16 21:30:33 +00006239/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6240/// parsing a top-level (non-nested) C++ class, and we are now
6241/// parsing those parts of the given Method declaration that could
6242/// not be parsed earlier (C++ [class.mem]p2), such as default
6243/// arguments. This action should enter the scope of the given
6244/// Method declaration as if we had just parsed the qualified method
6245/// name. However, it should not bring the parameters into scope;
6246/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00006247void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006248}
6249
6250/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6251/// C++ method declaration. We're (re-)introducing the given
6252/// function parameter into scope for use in parsing later parts of
6253/// the method declaration. For example, we could see an
6254/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00006255void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006256 if (!ParamD)
6257 return;
Mike Stump11289f42009-09-09 15:08:12 +00006258
John McCall48871652010-08-21 09:40:31 +00006259 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00006260
6261 // If this parameter has an unparsed default argument, clear it out
6262 // to make way for the parsed default argument.
6263 if (Param->hasUnparsedDefaultArg())
Craig Topperc3ec1492014-05-26 06:22:03 +00006264 Param->setDefaultArg(nullptr);
Douglas Gregor58354032008-12-24 00:01:03 +00006265
John McCall48871652010-08-21 09:40:31 +00006266 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006267 if (Param->getDeclName())
6268 IdResolver.AddDecl(Param);
6269}
6270
6271/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6272/// processing the delayed method declaration for Method. The method
6273/// declaration is now considered finished. There may be a separate
6274/// ActOnStartOfFunctionDef action later (not necessarily
6275/// immediately!) for this method, if it was also defined inside the
6276/// class body.
John McCall48871652010-08-21 09:40:31 +00006277void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006278 if (!MethodD)
6279 return;
Mike Stump11289f42009-09-09 15:08:12 +00006280
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006281 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00006282
John McCall48871652010-08-21 09:40:31 +00006283 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006284
6285 // Now that we have our default arguments, check the constructor
6286 // again. It could produce additional diagnostics or affect whether
6287 // the class has implicitly-declared destructors, among other
6288 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006289 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6290 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006291
6292 // Check the default arguments, which we may have added.
6293 if (!Method->isInvalidDecl())
6294 CheckCXXDefaultArguments(Method);
6295}
6296
Douglas Gregor831c93f2008-11-05 20:51:48 +00006297/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00006298/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00006299/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006300/// emit diagnostics and set the invalid bit to true. In any case, the type
6301/// will be updated to reflect a well-formed type for the constructor and
6302/// returned.
6303QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006304 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006305 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006306
6307 // C++ [class.ctor]p3:
6308 // A constructor shall not be virtual (10.3) or static (9.4). A
6309 // constructor can be invoked for a const, volatile or const
6310 // volatile object. A constructor shall not be declared const,
6311 // volatile, or const volatile (9.3.2).
6312 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006313 if (!D.isInvalidType())
6314 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6315 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6316 << SourceRange(D.getIdentifierLoc());
6317 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006318 }
John McCall8e7d6562010-08-26 03:08:43 +00006319 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006320 if (!D.isInvalidType())
6321 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6322 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6323 << SourceRange(D.getIdentifierLoc());
6324 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006325 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006326 }
Mike Stump11289f42009-09-09 15:08:12 +00006327
David Majnemer03f705f2014-07-08 18:18:04 +00006328 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6329 diagnoseIgnoredQualifiers(
6330 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6331 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6332 D.getDeclSpec().getRestrictSpecLoc(),
6333 D.getDeclSpec().getAtomicSpecLoc());
6334 D.setInvalidType();
6335 }
6336
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006337 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006338 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00006339 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006340 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6341 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006342 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006343 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6344 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006345 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006346 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6347 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00006348 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006349 }
Mike Stump11289f42009-09-09 15:08:12 +00006350
Douglas Gregordb9d6642011-01-26 05:01:58 +00006351 // C++0x [class.ctor]p4:
6352 // A constructor shall not be declared with a ref-qualifier.
6353 if (FTI.hasRefQualifier()) {
6354 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6355 << FTI.RefQualifierIsLValueRef
6356 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6357 D.setInvalidType();
6358 }
6359
Douglas Gregor831c93f2008-11-05 20:51:48 +00006360 // Rebuild the function type "R" without any type qualifiers (in
6361 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00006362 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00006363 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006364 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00006365 return R;
6366
6367 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6368 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006369 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00006370
6371 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006372}
6373
Douglas Gregor4d87df52008-12-16 21:30:33 +00006374/// CheckConstructor - Checks a fully-formed constructor for
6375/// well-formedness, issuing any diagnostics required. Returns true if
6376/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006377void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00006378 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006379 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6380 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006381 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006382
6383 // C++ [class.copy]p3:
6384 // A declaration of a constructor for a class X is ill-formed if
6385 // its first parameter is of type (optionally cv-qualified) X and
6386 // either there are no other parameters or else all other
6387 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006388 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00006389 ((Constructor->getNumParams() == 1) ||
6390 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00006391 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6392 Constructor->getTemplateSpecializationKind()
6393 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006394 QualType ParamType = Constructor->getParamDecl(0)->getType();
6395 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6396 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00006397 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00006398 const char *ConstRef
6399 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6400 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00006401 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00006402 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00006403
6404 // FIXME: Rather that making the constructor invalid, we should endeavor
6405 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006406 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006407 }
6408 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00006409}
6410
John McCalldeb646e2010-08-04 01:04:25 +00006411/// CheckDestructor - Checks a fully-formed destructor definition for
6412/// well-formedness, issuing any diagnostics required. Returns true
6413/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00006414bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006415 CXXRecordDecl *RD = Destructor->getParent();
6416
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006417 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006418 SourceLocation Loc;
6419
6420 if (!Destructor->isImplicit())
6421 Loc = Destructor->getLocation();
6422 else
6423 Loc = RD->getLocation();
6424
6425 // If we have a virtual destructor, look up the deallocation function
Craig Topperc3ec1492014-05-26 06:22:03 +00006426 FunctionDecl *OperatorDelete = nullptr;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006427 DeclarationName Name =
6428 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006429 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00006430 return true;
Richard Smithf03bd302013-12-05 08:30:59 +00006431 // If there's no class-specific operator delete, look up the global
6432 // non-array delete.
6433 if (!OperatorDelete)
6434 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall1e5d75d2010-07-03 18:33:00 +00006435
Eli Friedmanfa0df832012-02-02 03:46:19 +00006436 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00006437
6438 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006439 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00006440
6441 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006442}
6443
Douglas Gregor831c93f2008-11-05 20:51:48 +00006444/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6445/// the well-formednes of the destructor declarator @p D with type @p
6446/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006447/// emit diagnostics and set the declarator to invalid. Even if this happens,
6448/// will be updated to reflect a well-formed type for the destructor and
6449/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00006450QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006451 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006452 // C++ [class.dtor]p1:
6453 // [...] A typedef-name that names a class is a class-name
6454 // (7.1.3); however, a typedef-name that names a class shall not
6455 // be used as the identifier in the declarator for a destructor
6456 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00006457 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00006458 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00006459 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00006460 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00006461 else if (const TemplateSpecializationType *TST =
6462 DeclaratorType->getAs<TemplateSpecializationType>())
6463 if (TST->isTypeAlias())
6464 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6465 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006466
6467 // C++ [class.dtor]p2:
6468 // A destructor is used to destroy objects of its class type. A
6469 // destructor takes no parameters, and no return type can be
6470 // specified for it (not even void). The address of a destructor
6471 // shall not be taken. A destructor shall not be static. A
6472 // destructor can be invoked for a const, volatile or const
6473 // volatile object. A destructor shall not be declared const,
6474 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00006475 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006476 if (!D.isInvalidType())
6477 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6478 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00006479 << SourceRange(D.getIdentifierLoc())
6480 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6481
John McCall8e7d6562010-08-26 03:08:43 +00006482 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006483 }
David Majnemer03f705f2014-07-08 18:18:04 +00006484 if (!D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006485 // Destructors don't have return types, but the parser will
6486 // happily parse something like:
6487 //
6488 // class X {
6489 // float ~X();
6490 // };
6491 //
6492 // The return type will be eliminated later.
David Majnemer03f705f2014-07-08 18:18:04 +00006493 if (D.getDeclSpec().hasTypeSpecifier())
6494 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6495 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6496 << SourceRange(D.getIdentifierLoc());
6497 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6498 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6499 SourceLocation(),
6500 D.getDeclSpec().getConstSpecLoc(),
6501 D.getDeclSpec().getVolatileSpecLoc(),
6502 D.getDeclSpec().getRestrictSpecLoc(),
6503 D.getDeclSpec().getAtomicSpecLoc());
6504 D.setInvalidType();
6505 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006506 }
Mike Stump11289f42009-09-09 15:08:12 +00006507
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006508 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006509 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006510 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006511 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6512 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006513 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006514 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6515 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006516 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006517 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6518 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00006519 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006520 }
6521
Douglas Gregordb9d6642011-01-26 05:01:58 +00006522 // C++0x [class.dtor]p2:
6523 // A destructor shall not be declared with a ref-qualifier.
6524 if (FTI.hasRefQualifier()) {
6525 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6526 << FTI.RefQualifierIsLValueRef
6527 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6528 D.setInvalidType();
6529 }
6530
Douglas Gregor831c93f2008-11-05 20:51:48 +00006531 // Make sure we don't have any parameters.
Alp Toker4284c6e2014-05-11 16:05:55 +00006532 if (FTIHasNonVoidParameters(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006533 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6534
6535 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006536 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00006537 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006538 }
6539
Mike Stump11289f42009-09-09 15:08:12 +00006540 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00006541 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006542 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00006543 D.setInvalidType();
6544 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006545
6546 // Rebuild the function type "R" without any type qualifiers or
6547 // parameters (in case any of the errors above fired) and with
6548 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00006549 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00006550 if (!D.isInvalidType())
6551 return R;
6552
Douglas Gregor95755162010-07-01 05:10:53 +00006553 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006554 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6555 EPI.Variadic = false;
6556 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006557 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006558 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006559}
6560
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006561/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6562/// well-formednes of the conversion function declarator @p D with
6563/// type @p R. If there are any errors in the declarator, this routine
6564/// will emit diagnostics and return true. Otherwise, it will return
6565/// false. Either way, the type @p R will be updated to reflect a
6566/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006567void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00006568 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006569 // C++ [class.conv.fct]p1:
6570 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00006571 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00006572 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00006573 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006574 if (!D.isInvalidType())
6575 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00006576 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6577 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006578 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006579 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006580 }
John McCall212fa2e2010-04-13 00:04:31 +00006581
6582 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6583
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006584 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006585 // Conversion functions don't have return types, but the parser will
6586 // happily parse something like:
6587 //
6588 // class X {
6589 // float operator bool();
6590 // };
6591 //
6592 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00006593 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6594 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6595 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00006596 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006597 }
6598
John McCall212fa2e2010-04-13 00:04:31 +00006599 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6600
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006601 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00006602 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006603 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6604
6605 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006606 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006607 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00006608 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006609 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006610 D.setInvalidType();
6611 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006612
John McCall212fa2e2010-04-13 00:04:31 +00006613 // Diagnose "&operator bool()" and other such nonsense. This
6614 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00006615 if (Proto->getReturnType() != ConvType) {
John McCall212fa2e2010-04-13 00:04:31 +00006616 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
Alp Toker314cc812014-01-25 16:55:45 +00006617 << Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006618 D.setInvalidType();
Alp Toker314cc812014-01-25 16:55:45 +00006619 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006620 }
6621
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006622 // C++ [class.conv.fct]p4:
6623 // The conversion-type-id shall not represent a function type nor
6624 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006625 if (ConvType->isArrayType()) {
6626 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6627 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006628 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006629 } else if (ConvType->isFunctionType()) {
6630 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6631 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006632 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006633 }
6634
6635 // Rebuild the function type "R" without any parameters (in case any
6636 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00006637 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00006638 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006639 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006640
Douglas Gregor5fb53972009-01-14 15:45:31 +00006641 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006642 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00006643 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006644 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006645 diag::warn_cxx98_compat_explicit_conversion_functions :
6646 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00006647 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006648}
6649
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006650/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6651/// the declaration of the given C++ conversion function. This routine
6652/// is responsible for recording the conversion function in the C++
6653/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00006654Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006655 assert(Conversion && "Expected to receive a conversion function declaration");
6656
Douglas Gregor4287b372008-12-12 08:25:50 +00006657 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006658
6659 // Make sure we aren't redeclaring the conversion function.
6660 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006661
6662 // C++ [class.conv.fct]p1:
6663 // [...] A conversion function is never used to convert a
6664 // (possibly cv-qualified) object to the (possibly cv-qualified)
6665 // same object type (or a reference to it), to a (possibly
6666 // cv-qualified) base class of that type (or a reference to it),
6667 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00006668 // FIXME: Suppress this warning if the conversion function ends up being a
6669 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00006670 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006671 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006672 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006673 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006674 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6675 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00006676 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006677 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006678 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6679 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006680 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006681 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006682 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006683 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006684 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006685 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006686 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006687 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006688 }
6689
Douglas Gregor457104e2010-09-29 04:25:11 +00006690 if (FunctionTemplateDecl *ConversionTemplate
6691 = Conversion->getDescribedFunctionTemplate())
6692 return ConversionTemplate;
6693
John McCall48871652010-08-21 09:40:31 +00006694 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006695}
6696
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006697//===----------------------------------------------------------------------===//
6698// Namespace Handling
6699//===----------------------------------------------------------------------===//
6700
Richard Smith45bb8852012-10-04 22:13:39 +00006701/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6702/// reopened.
6703static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6704 SourceLocation Loc,
6705 IdentifierInfo *II, bool *IsInline,
6706 NamespaceDecl *PrevNS) {
6707 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00006708
Richard Smithf501cc32012-10-05 01:46:25 +00006709 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6710 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6711 // inline namespaces, with the intention of bringing names into namespace std.
6712 //
6713 // We support this just well enough to get that case working; this is not
6714 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00006715 if (*IsInline && II && II->getName().startswith("__atomic") &&
6716 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00006717 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00006718 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6719 NS = NS->getPreviousDecl())
6720 NS->setInline(*IsInline);
6721 // Patch up the lookup table for the containing namespace. This isn't really
6722 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00006723 for (auto *I : PrevNS->decls())
6724 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00006725 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6726 return;
6727 }
6728
6729 if (PrevNS->isInline())
6730 // The user probably just forgot the 'inline', so suggest that it
6731 // be added back.
6732 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6733 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6734 else
Richard Smith5b5d21e2014-03-12 23:36:42 +00006735 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
Richard Smith45bb8852012-10-04 22:13:39 +00006736
6737 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6738 *IsInline = PrevNS->isInline();
6739}
John McCallb1be5232010-08-26 09:15:37 +00006740
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006741/// ActOnStartNamespaceDef - This is called at the start of a namespace
6742/// definition.
John McCall48871652010-08-21 09:40:31 +00006743Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00006744 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006745 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00006746 SourceLocation IdentLoc,
6747 IdentifierInfo *II,
6748 SourceLocation LBrace,
6749 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006750 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6751 // For anonymous namespace, take the location of the left brace.
6752 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00006753 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00006754 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00006755 bool IsStd = false;
6756 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006757 Scope *DeclRegionScope = NamespcScope->getParent();
6758
Craig Topperc3ec1492014-05-26 06:22:03 +00006759 NamespaceDecl *PrevNS = nullptr;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006760 if (II) {
6761 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00006762 // The identifier in an original-namespace-definition shall not
6763 // have been previously defined in the declarative region in
6764 // which the original-namespace-definition appears. The
6765 // identifier in an original-namespace-definition is the name of
6766 // the namespace. Subsequently in that declarative region, it is
6767 // treated as an original-namespace-name.
6768 //
6769 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006770 // look through using directives, just look for any ordinary names.
6771
6772 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00006773 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6774 Decl::IDNS_Namespace;
Craig Topperc3ec1492014-05-26 06:22:03 +00006775 NamedDecl *PrevDecl = nullptr;
David Blaikieff7d47a2012-12-19 00:45:41 +00006776 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6777 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6778 ++I) {
6779 if ((*I)->getIdentifierNamespace() & IDNS) {
6780 PrevDecl = *I;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006781 break;
6782 }
6783 }
6784
Douglas Gregore57e7522012-01-07 09:11:48 +00006785 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6786
6787 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00006788 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00006789 if (IsInline != PrevNS->isInline())
6790 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6791 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00006792 } else if (PrevDecl) {
6793 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006794 Diag(Loc, diag::err_redefinition_different_kind)
6795 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00006796 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006797 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00006798 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00006799 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00006800 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00006801 // This is the first "real" definition of the namespace "std", so update
6802 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006803 PrevNS = getStdNamespace();
6804 IsStd = true;
6805 AddToKnown = !IsInline;
6806 } else {
6807 // We've seen this namespace for the first time.
6808 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00006809 }
Douglas Gregor91f84212008-12-11 16:49:14 +00006810 } else {
John McCall4fa53422009-10-01 00:25:31 +00006811 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00006812
6813 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00006814 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00006815 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00006816 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006817 } else {
6818 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00006819 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006820 }
6821
Richard Smith45bb8852012-10-04 22:13:39 +00006822 if (PrevNS && IsInline != PrevNS->isInline())
6823 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6824 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00006825 }
6826
6827 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6828 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006829 if (IsInvalid)
6830 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00006831
6832 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00006833
Douglas Gregore57e7522012-01-07 09:11:48 +00006834 // FIXME: Should we be merging attributes?
6835 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006836 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00006837
6838 if (IsStd)
6839 StdNamespace = Namespc;
6840 if (AddToKnown)
6841 KnownNamespaces[Namespc] = false;
6842
6843 if (II) {
6844 PushOnScopeChains(Namespc, DeclRegionScope);
6845 } else {
6846 // Link the anonymous namespace into its parent.
6847 DeclContext *Parent = CurContext->getRedeclContext();
6848 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6849 TU->setAnonymousNamespace(Namespc);
6850 } else {
6851 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00006852 }
John McCall4fa53422009-10-01 00:25:31 +00006853
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00006854 CurContext->addDecl(Namespc);
6855
John McCall4fa53422009-10-01 00:25:31 +00006856 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6857 // behaves as if it were replaced by
6858 // namespace unique { /* empty body */ }
6859 // using namespace unique;
6860 // namespace unique { namespace-body }
6861 // where all occurrences of 'unique' in a translation unit are
6862 // replaced by the same identifier and this identifier differs
6863 // from all other identifiers in the entire program.
6864
6865 // We just create the namespace with an empty name and then add an
6866 // implicit using declaration, just like the standard suggests.
6867 //
6868 // CodeGen enforces the "universally unique" aspect by giving all
6869 // declarations semantically contained within an anonymous
6870 // namespace internal linkage.
6871
Douglas Gregore57e7522012-01-07 09:11:48 +00006872 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00006873 UsingDirectiveDecl* UD
Nick Lewycky38115822012-11-04 20:21:54 +00006874 = UsingDirectiveDecl::Create(Context, Parent,
John McCall0db42252009-12-16 02:06:49 +00006875 /* 'using' */ LBrace,
6876 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00006877 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00006878 /* identifier */ SourceLocation(),
6879 Namespc,
Nick Lewycky38115822012-11-04 20:21:54 +00006880 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00006881 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00006882 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00006883 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006884 }
6885
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00006886 ActOnDocumentableDecl(Namespc);
6887
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006888 // Although we could have an invalid decl (i.e. the namespace name is a
6889 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00006890 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6891 // for the namespace has the declarations that showed up in that particular
6892 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00006893 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00006894 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006895}
6896
Sebastian Redla6602e92009-11-23 15:34:23 +00006897/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6898/// is a namespace alias, returns the namespace it points to.
6899static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6900 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6901 return AD->getNamespace();
6902 return dyn_cast_or_null<NamespaceDecl>(D);
6903}
6904
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006905/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6906/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00006907void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006908 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6909 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006910 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006911 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00006912 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006913 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006914}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006915
John McCall28a0cf72010-08-25 07:42:41 +00006916CXXRecordDecl *Sema::getStdBadAlloc() const {
6917 return cast_or_null<CXXRecordDecl>(
6918 StdBadAlloc.get(Context.getExternalSource()));
6919}
6920
6921NamespaceDecl *Sema::getStdNamespace() const {
6922 return cast_or_null<NamespaceDecl>(
6923 StdNamespace.get(Context.getExternalSource()));
6924}
6925
Douglas Gregorcdf87022010-06-29 17:53:46 +00006926/// \brief Retrieve the special "std" namespace, which may require us to
6927/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006928NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00006929 if (!StdNamespace) {
6930 // The "std" namespace has not yet been defined, so build one implicitly.
6931 StdNamespace = NamespaceDecl::Create(Context,
6932 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006933 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006934 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006935 &PP.getIdentifierTable().get("std"),
Craig Topperc3ec1492014-05-26 06:22:03 +00006936 /*PrevDecl=*/nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006937 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006938 }
6939
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006940 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006941}
6942
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006943bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006944 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006945 "Looking for std::initializer_list outside of C++.");
6946
6947 // We're looking for implicit instantiations of
6948 // template <typename E> class std::initializer_list.
6949
6950 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6951 return false;
6952
Craig Topperc3ec1492014-05-26 06:22:03 +00006953 ClassTemplateDecl *Template = nullptr;
6954 const TemplateArgument *Arguments = nullptr;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006955
Sebastian Redl43144e72012-01-17 22:49:58 +00006956 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006957
Sebastian Redl43144e72012-01-17 22:49:58 +00006958 ClassTemplateSpecializationDecl *Specialization =
6959 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6960 if (!Specialization)
6961 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006962
Sebastian Redl43144e72012-01-17 22:49:58 +00006963 Template = Specialization->getSpecializedTemplate();
6964 Arguments = Specialization->getTemplateArgs().data();
6965 } else if (const TemplateSpecializationType *TST =
6966 Ty->getAs<TemplateSpecializationType>()) {
6967 Template = dyn_cast_or_null<ClassTemplateDecl>(
6968 TST->getTemplateName().getAsTemplateDecl());
6969 Arguments = TST->getArgs();
6970 }
6971 if (!Template)
6972 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006973
6974 if (!StdInitializerList) {
6975 // Haven't recognized std::initializer_list yet, maybe this is it.
6976 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6977 if (TemplateClass->getIdentifier() !=
6978 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00006979 !getStdNamespace()->InEnclosingNamespaceSetOf(
6980 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006981 return false;
6982 // This is a template called std::initializer_list, but is it the right
6983 // template?
6984 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006985 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006986 return false;
6987 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6988 return false;
6989
6990 // It's the right template.
6991 StdInitializerList = Template;
6992 }
6993
6994 if (Template != StdInitializerList)
6995 return false;
6996
6997 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00006998 if (Element)
6999 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007000 return true;
7001}
7002
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007003static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7004 NamespaceDecl *Std = S.getStdNamespace();
7005 if (!Std) {
7006 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00007007 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007008 }
7009
7010 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7011 Loc, Sema::LookupOrdinaryName);
7012 if (!S.LookupQualifiedName(Result, Std)) {
7013 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00007014 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007015 }
7016 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7017 if (!Template) {
7018 Result.suppressDiagnostics();
7019 // We found something weird. Complain about the first thing we found.
7020 NamedDecl *Found = *Result.begin();
7021 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00007022 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007023 }
7024
7025 // We found some template called std::initializer_list. Now verify that it's
7026 // correct.
7027 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00007028 if (Params->getMinRequiredArguments() != 1 ||
7029 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007030 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00007031 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007032 }
7033
7034 return Template;
7035}
7036
7037QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7038 if (!StdInitializerList) {
7039 StdInitializerList = LookupStdInitializerList(*this, Loc);
7040 if (!StdInitializerList)
7041 return QualType();
7042 }
7043
7044 TemplateArgumentListInfo Args(Loc, Loc);
7045 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7046 Context.getTrivialTypeSourceInfo(Element,
7047 Loc)));
7048 return Context.getCanonicalType(
7049 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7050}
7051
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007052bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7053 // C++ [dcl.init.list]p2:
7054 // A constructor is an initializer-list constructor if its first parameter
7055 // is of type std::initializer_list<E> or reference to possibly cv-qualified
7056 // std::initializer_list<E> for some type E, and either there are no other
7057 // parameters or else all other parameters have default arguments.
7058 if (Ctor->getNumParams() < 1 ||
7059 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7060 return false;
7061
7062 QualType ArgType = Ctor->getParamDecl(0)->getType();
7063 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7064 ArgType = RT->getPointeeType().getUnqualifiedType();
7065
Craig Topperc3ec1492014-05-26 06:22:03 +00007066 return isStdInitializerList(ArgType, nullptr);
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007067}
7068
Douglas Gregora172e082011-03-26 22:25:30 +00007069/// \brief Determine whether a using statement is in a context where it will be
7070/// apply in all contexts.
7071static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7072 switch (CurContext->getDeclKind()) {
7073 case Decl::TranslationUnit:
7074 return true;
7075 case Decl::LinkageSpec:
7076 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7077 default:
7078 return false;
7079 }
7080}
7081
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007082namespace {
7083
7084// Callback to only accept typo corrections that are namespaces.
7085class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007086public:
Craig Toppera798a9d2014-03-02 09:32:10 +00007087 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007088 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007089 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007090 return false;
7091 }
7092};
7093
7094}
7095
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007096static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7097 CXXScopeSpec &SS,
7098 SourceLocation IdentLoc,
7099 IdentifierInfo *Ident) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007100 NamespaceValidatorCCC Validator;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007101 R.clear();
7102 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007103 R.getLookupKind(), Sc, &SS,
John Thompson2255f2c2014-04-23 12:57:01 +00007104 Validator,
7105 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007106 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00007107 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7108 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007109 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00007110 S.diagnoseTypo(Corrected,
7111 S.PDiag(diag::err_using_directive_member_suggest)
7112 << Ident << DC << DroppedSpecifier << SS.getRange(),
7113 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007114 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007115 S.diagnoseTypo(Corrected,
7116 S.PDiag(diag::err_using_directive_suggest) << Ident,
7117 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007118 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007119 R.addDecl(Corrected.getCorrectionDecl());
7120 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007121 }
7122 return false;
7123}
7124
John McCall48871652010-08-21 09:40:31 +00007125Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00007126 SourceLocation UsingLoc,
7127 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007128 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00007129 SourceLocation IdentLoc,
7130 IdentifierInfo *NamespcName,
7131 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00007132 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7133 assert(NamespcName && "Invalid NamespcName.");
7134 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00007135
7136 // This can only happen along a recovery path.
7137 while (S->getFlags() & Scope::TemplateParamScope)
7138 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00007139 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00007140
Craig Topperc3ec1492014-05-26 06:22:03 +00007141 UsingDirectiveDecl *UDir = nullptr;
7142 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregorcdf87022010-06-29 17:53:46 +00007143 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00007144 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007145
Douglas Gregor34074322009-01-14 22:20:51 +00007146 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00007147 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7148 LookupParsedName(R, S, &SS);
7149 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00007150 return nullptr;
John McCall27b18f82009-11-17 02:14:36 +00007151
Douglas Gregorcdf87022010-06-29 17:53:46 +00007152 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007153 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007154 // Allow "using namespace std;" or "using namespace ::std;" even if
7155 // "std" hasn't been defined yet, for GCC compatibility.
7156 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7157 NamespcName->isStr("std")) {
7158 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007159 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00007160 R.resolveKind();
7161 }
7162 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007163 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007164 }
7165
John McCall9f3059a2009-10-09 21:13:30 +00007166 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00007167 NamedDecl *Named = R.getFoundDecl();
7168 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7169 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00007170 // C++ [namespace.udir]p1:
7171 // A using-directive specifies that the names in the nominated
7172 // namespace can be used in the scope in which the
7173 // using-directive appears after the using-directive. During
7174 // unqualified name lookup (3.4.1), the names appear as if they
7175 // were declared in the nearest enclosing namespace which
7176 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00007177 // namespace. [Note: in this context, "contains" means "contains
7178 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00007179
7180 // Find enclosing context containing both using-directive and
7181 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00007182 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007183 DeclContext *CommonAncestor = cast<DeclContext>(NS);
7184 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7185 CommonAncestor = CommonAncestor->getParent();
7186
Sebastian Redla6602e92009-11-23 15:34:23 +00007187 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00007188 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00007189 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007190
Douglas Gregora172e082011-03-26 22:25:30 +00007191 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00007192 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007193 Diag(IdentLoc, diag::warn_using_directive_in_header);
7194 }
7195
Douglas Gregor889ceb72009-02-03 19:21:40 +00007196 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007197 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00007198 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00007199 }
7200
Richard Smith54ecd982013-02-20 19:22:51 +00007201 if (UDir)
7202 ProcessDeclAttributeList(S, UDir, AttrList);
7203
John McCall48871652010-08-21 09:40:31 +00007204 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00007205}
7206
7207void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00007208 // If the scope has an associated entity and the using directive is at
7209 // namespace or translation unit scope, add the UsingDirectiveDecl into
7210 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007211 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00007212 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007213 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007214 else
Yaron Keren065da7c2014-05-20 18:23:05 +00007215 // Otherwise, it is at block scope. The using-directives will affect lookup
Richard Smith05afe5e2012-03-13 03:12:56 +00007216 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00007217 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007218}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007219
Douglas Gregorfec52632009-06-20 00:51:54 +00007220
John McCall48871652010-08-21 09:40:31 +00007221Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00007222 AccessSpecifier AS,
7223 bool HasUsingKeyword,
7224 SourceLocation UsingLoc,
7225 CXXScopeSpec &SS,
7226 UnqualifiedId &Name,
7227 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007228 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00007229 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00007230 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00007231
Douglas Gregor220f4272009-11-04 16:30:06 +00007232 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00007233 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00007234 case UnqualifiedId::IK_Identifier:
7235 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00007236 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00007237 case UnqualifiedId::IK_ConversionFunctionId:
7238 break;
7239
7240 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00007241 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00007242 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007243 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007244 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00007245 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00007246 diag::err_using_decl_constructor)
7247 << SS.getRange();
7248
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007249 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00007250
Craig Topperc3ec1492014-05-26 06:22:03 +00007251 return nullptr;
7252
Douglas Gregor220f4272009-11-04 16:30:06 +00007253 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007254 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00007255 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00007256 return nullptr;
7257
Douglas Gregor220f4272009-11-04 16:30:06 +00007258 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007259 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00007260 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007261 return nullptr;
Douglas Gregor220f4272009-11-04 16:30:06 +00007262 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007263
7264 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7265 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00007266 if (!TargetName)
Craig Topperc3ec1492014-05-26 06:22:03 +00007267 return nullptr;
John McCall3969e302009-12-08 07:46:18 +00007268
Richard Smithc2bc61b2013-03-18 21:12:30 +00007269 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00007270 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00007271 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00007272 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7273 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00007274 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00007275 }
7276
Douglas Gregorc4356532010-12-16 00:46:58 +00007277 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7278 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +00007279 return nullptr;
Douglas Gregorc4356532010-12-16 00:46:58 +00007280
John McCall3f746822009-11-17 05:59:44 +00007281 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007282 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007283 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007284 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00007285 if (UD)
7286 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00007287
John McCall48871652010-08-21 09:40:31 +00007288 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00007289}
7290
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007291/// \brief Determine whether a using declaration considers the given
7292/// declarations as "equivalent", e.g., if they are redeclarations of
7293/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00007294static bool
7295IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7296 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007297 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007298
Richard Smithdda56e42011-04-15 14:24:37 +00007299 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00007300 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007301 return Context.hasSameType(TD1->getUnderlyingType(),
7302 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007303
7304 return false;
7305}
7306
7307
John McCall84d87672009-12-10 09:41:52 +00007308/// Determines whether to create a using shadow decl for a particular
7309/// decl, given the set of decls existing prior to this using lookup.
7310bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00007311 const LookupResult &Previous,
7312 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00007313 // Diagnose finding a decl which is not from a base class of the
7314 // current class. We do this now because there are cases where this
7315 // function will silently decide not to build a shadow decl, which
7316 // will pre-empt further diagnostics.
7317 //
7318 // We don't need to do this in C++0x because we do the check once on
7319 // the qualifier.
7320 //
7321 // FIXME: diagnose the following if we care enough:
7322 // struct A { int foo; };
7323 // struct B : A { using A::foo; };
7324 // template <class T> struct C : A {};
7325 // template <class T> struct D : C<T> { using B::foo; } // <---
7326 // This is invalid (during instantiation) in C++03 because B::foo
7327 // resolves to the using decl in B, which is not a base class of D<T>.
7328 // We can't diagnose it immediately because C<T> is an unknown
7329 // specialization. The UsingShadowDecl in D<T> then points directly
7330 // to A::foo, which will look well-formed when we instantiate.
7331 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007332 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00007333 DeclContext *OrigDC = Orig->getDeclContext();
7334
7335 // Handle enums and anonymous structs.
7336 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7337 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7338 while (OrigRec->isAnonymousStructOrUnion())
7339 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7340
7341 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7342 if (OrigDC == CurContext) {
7343 Diag(Using->getLocation(),
7344 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007345 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007346 Diag(Orig->getLocation(), diag::note_using_decl_target);
7347 return true;
7348 }
7349
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007350 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00007351 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007352 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00007353 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007354 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007355 Diag(Orig->getLocation(), diag::note_using_decl_target);
7356 return true;
7357 }
7358 }
7359
7360 if (Previous.empty()) return false;
7361
7362 NamedDecl *Target = Orig;
7363 if (isa<UsingShadowDecl>(Target))
7364 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7365
John McCalla17e83e2009-12-11 02:33:26 +00007366 // If the target happens to be one of the previous declarations, we
7367 // don't have a conflict.
7368 //
7369 // FIXME: but we might be increasing its access, in which case we
7370 // should redeclare it.
Craig Topperc3ec1492014-05-26 06:22:03 +00007371 NamedDecl *NonTag = nullptr, *Tag = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00007372 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00007373 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7374 I != E; ++I) {
7375 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007376 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7377 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7378 PrevShadow = Shadow;
7379 FoundEquivalentDecl = true;
7380 }
John McCalla17e83e2009-12-11 02:33:26 +00007381
7382 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7383 }
7384
Richard Smithfd8634a2013-10-23 02:17:46 +00007385 if (FoundEquivalentDecl)
7386 return false;
7387
Alp Tokera2794f92014-01-22 07:29:52 +00007388 if (FunctionDecl *FD = Target->getAsFunction()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007389 NamedDecl *OldDecl = nullptr;
7390 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7391 /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00007392 case Ovl_Overload:
7393 return false;
7394
7395 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00007396 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007397 break;
Richard Smith18819302014-02-06 01:31:33 +00007398
John McCall84d87672009-12-10 09:41:52 +00007399 // We found a decl with the exact signature.
7400 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007401 // If we're in a record, we want to hide the target, so we
7402 // return true (without a diagnostic) to tell the caller not to
7403 // build a shadow decl.
7404 if (CurContext->isRecord())
7405 return true;
7406
7407 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00007408 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007409 break;
7410 }
7411
7412 Diag(Target->getLocation(), diag::note_using_decl_target);
7413 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7414 return true;
7415 }
7416
7417 // Target is not a function.
7418
John McCall84d87672009-12-10 09:41:52 +00007419 if (isa<TagDecl>(Target)) {
7420 // No conflict between a tag and a non-tag.
7421 if (!Tag) return false;
7422
John McCalle29c5cd2009-12-10 19:51:03 +00007423 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007424 Diag(Target->getLocation(), diag::note_using_decl_target);
7425 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7426 return true;
7427 }
7428
7429 // No conflict between a tag and a non-tag.
7430 if (!NonTag) return false;
7431
John McCalle29c5cd2009-12-10 19:51:03 +00007432 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007433 Diag(Target->getLocation(), diag::note_using_decl_target);
7434 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7435 return true;
7436}
7437
John McCall3f746822009-11-17 05:59:44 +00007438/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00007439UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00007440 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00007441 NamedDecl *Orig,
7442 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00007443
7444 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00007445 NamedDecl *Target = Orig;
7446 if (isa<UsingShadowDecl>(Target)) {
7447 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7448 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00007449 }
Richard Smithfd8634a2013-10-23 02:17:46 +00007450
John McCall3f746822009-11-17 05:59:44 +00007451 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00007452 = UsingShadowDecl::Create(Context, CurContext,
7453 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00007454 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00007455
Douglas Gregor457104e2010-09-29 04:25:11 +00007456 Shadow->setAccess(UD->getAccess());
7457 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7458 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007459
7460 Shadow->setPreviousDecl(PrevDecl);
7461
John McCall3f746822009-11-17 05:59:44 +00007462 if (S)
John McCall3969e302009-12-08 07:46:18 +00007463 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00007464 else
John McCall3969e302009-12-08 07:46:18 +00007465 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00007466
John McCall3969e302009-12-08 07:46:18 +00007467
John McCall84d87672009-12-10 09:41:52 +00007468 return Shadow;
7469}
John McCall3969e302009-12-08 07:46:18 +00007470
John McCall84d87672009-12-10 09:41:52 +00007471/// Hides a using shadow declaration. This is required by the current
7472/// using-decl implementation when a resolvable using declaration in a
7473/// class is followed by a declaration which would hide or override
7474/// one or more of the using decl's targets; for example:
7475///
7476/// struct Base { void foo(int); };
7477/// struct Derived : Base {
7478/// using Base::foo;
7479/// void foo(int);
7480/// };
7481///
7482/// The governing language is C++03 [namespace.udecl]p12:
7483///
7484/// When a using-declaration brings names from a base class into a
7485/// derived class scope, member functions in the derived class
7486/// override and/or hide member functions with the same name and
7487/// parameter types in a base class (rather than conflicting).
7488///
7489/// There are two ways to implement this:
7490/// (1) optimistically create shadow decls when they're not hidden
7491/// by existing declarations, or
7492/// (2) don't create any shadow decls (or at least don't make them
7493/// visible) until we've fully parsed/instantiated the class.
7494/// The problem with (1) is that we might have to retroactively remove
7495/// a shadow decl, which requires several O(n) operations because the
7496/// decl structures are (very reasonably) not designed for removal.
7497/// (2) avoids this but is very fiddly and phase-dependent.
7498void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00007499 if (Shadow->getDeclName().getNameKind() ==
7500 DeclarationName::CXXConversionFunctionName)
7501 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7502
John McCall84d87672009-12-10 09:41:52 +00007503 // Remove it from the DeclContext...
7504 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007505
John McCall84d87672009-12-10 09:41:52 +00007506 // ...and the scope, if applicable...
7507 if (S) {
John McCall48871652010-08-21 09:40:31 +00007508 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00007509 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007510 }
7511
John McCall84d87672009-12-10 09:41:52 +00007512 // ...and the using decl.
7513 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7514
7515 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00007516 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00007517}
7518
Richard Smith09d5b3a2014-05-01 00:35:04 +00007519/// Find the base specifier for a base class with the given type.
7520static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7521 QualType DesiredBase,
7522 bool &AnyDependentBases) {
7523 // Check whether the named type is a direct base class.
7524 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7525 for (auto &Base : Derived->bases()) {
7526 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7527 if (CanonicalDesiredBase == BaseType)
7528 return &Base;
7529 if (BaseType->isDependentType())
7530 AnyDependentBases = true;
7531 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007532 return nullptr;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007533}
7534
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007535namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007536class UsingValidatorCCC : public CorrectionCandidateCallback {
7537public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007538 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007539 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007540 : HasTypenameKeyword(HasTypenameKeyword),
Richard Smith09d5b3a2014-05-01 00:35:04 +00007541 IsInstantiation(IsInstantiation), OldNNS(NNS),
7542 RequireMemberOf(RequireMemberOf) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007543
Craig Toppera798a9d2014-03-02 09:32:10 +00007544 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007545 NamedDecl *ND = Candidate.getCorrectionDecl();
7546
7547 // Keywords are not valid here.
7548 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007549 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007550
7551 // Completely unqualified names are invalid for a 'using' declaration.
7552 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7553 return false;
7554
Richard Smith09d5b3a2014-05-01 00:35:04 +00007555 if (RequireMemberOf) {
7556 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7557 if (FoundRecord && FoundRecord->isInjectedClassName()) {
7558 // No-one ever wants a using-declaration to name an injected-class-name
7559 // of a base class, unless they're declaring an inheriting constructor.
7560 ASTContext &Ctx = ND->getASTContext();
7561 if (!Ctx.getLangOpts().CPlusPlus11)
7562 return false;
7563 QualType FoundType = Ctx.getRecordType(FoundRecord);
7564
7565 // Check that the injected-class-name is named as a member of its own
7566 // type; we don't want to suggest 'using Derived::Base;', since that
7567 // means something else.
7568 NestedNameSpecifier *Specifier =
7569 Candidate.WillReplaceSpecifier()
7570 ? Candidate.getCorrectionSpecifier()
7571 : OldNNS;
7572 if (!Specifier->getAsType() ||
7573 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
7574 return false;
7575
7576 // Check that this inheriting constructor declaration actually names a
7577 // direct base class of the current class.
7578 bool AnyDependentBases = false;
7579 if (!findDirectBaseWithType(RequireMemberOf,
7580 Ctx.getRecordType(FoundRecord),
7581 AnyDependentBases) &&
7582 !AnyDependentBases)
7583 return false;
7584 } else {
7585 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
7586 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
7587 return false;
7588
7589 // FIXME: Check that the base class member is accessible?
7590 }
7591 }
7592
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007593 if (isa<TypeDecl>(ND))
7594 return HasTypenameKeyword || !IsInstantiation;
7595
7596 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007597 }
7598
7599private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007600 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007601 bool IsInstantiation;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007602 NestedNameSpecifier *OldNNS;
Richard Smith21866c32014-04-30 18:03:21 +00007603 CXXRecordDecl *RequireMemberOf;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007604};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007605} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007606
John McCalle61f2ba2009-11-18 02:36:19 +00007607/// Builds a using declaration.
7608///
7609/// \param IsInstantiation - Whether this call arises from an
7610/// instantiation of an unresolved using declaration. We treat
7611/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00007612NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7613 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007614 CXXScopeSpec &SS,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007615 DeclarationNameInfo NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00007616 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007617 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007618 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00007619 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00007620 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007621 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00007622 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00007623
Anders Carlssonf038fc22009-08-28 05:49:21 +00007624 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00007625
Anders Carlsson59140b32009-08-28 03:16:11 +00007626 if (SS.isEmpty()) {
7627 Diag(IdentLoc, diag::err_using_requires_qualname);
Craig Topperc3ec1492014-05-26 06:22:03 +00007628 return nullptr;
Anders Carlsson59140b32009-08-28 03:16:11 +00007629 }
Mike Stump11289f42009-09-09 15:08:12 +00007630
John McCall84d87672009-12-10 09:41:52 +00007631 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007632 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00007633 ForRedeclaration);
7634 Previous.setHideTags(false);
7635 if (S) {
7636 LookupName(Previous, S);
7637
7638 // It is really dumb that we have to do this.
7639 LookupResult::Filter F = Previous.makeFilter();
7640 while (F.hasNext()) {
7641 NamedDecl *D = F.next();
7642 if (!isDeclInScope(D, CurContext, S))
7643 F.erase();
Richard Smith83e78f52014-04-11 01:03:38 +00007644 // If we found a local extern declaration that's not ordinarily visible,
7645 // and this declaration is being added to a non-block scope, ignore it.
7646 // We're only checking for scope conflicts here, not also for violations
7647 // of the linkage rules.
7648 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
7649 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
7650 F.erase();
John McCall84d87672009-12-10 09:41:52 +00007651 }
7652 F.done();
7653 } else {
7654 assert(IsInstantiation && "no scope in non-instantiation");
7655 assert(CurContext->isRecord() && "scope not record in instantiation");
7656 LookupQualifiedName(Previous, CurContext);
7657 }
7658
John McCall84d87672009-12-10 09:41:52 +00007659 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007660 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7661 SS, IdentLoc, Previous))
Craig Topperc3ec1492014-05-26 06:22:03 +00007662 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00007663
7664 // Check for bad qualifiers.
Richard Smith7ad0b882014-04-02 21:44:35 +00007665 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00007666 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00007667
John McCall84c16cf2009-11-12 03:15:40 +00007668 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007669 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007670 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00007671 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007672 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00007673 // FIXME: not all declaration name kinds are legal here
7674 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7675 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007676 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007677 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00007678 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007679 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7680 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00007681 }
Richard Smith09d5b3a2014-05-01 00:35:04 +00007682 D->setAccess(AS);
7683 CurContext->addDecl(D);
7684 return D;
Anders Carlssonf038fc22009-08-28 05:49:21 +00007685 }
John McCallb96ec562009-12-04 22:46:56 +00007686
Richard Smith09d5b3a2014-05-01 00:35:04 +00007687 auto Build = [&](bool Invalid) {
7688 UsingDecl *UD =
7689 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
7690 HasTypenameKeyword);
7691 UD->setAccess(AS);
7692 CurContext->addDecl(UD);
7693 UD->setInvalidDecl(Invalid);
John McCall3969e302009-12-08 07:46:18 +00007694 return UD;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007695 };
7696 auto BuildInvalid = [&]{ return Build(true); };
7697 auto BuildValid = [&]{ return Build(false); };
7698
7699 if (RequireCompleteDeclContext(SS, LookupContext))
7700 return BuildInvalid();
Anders Carlsson59140b32009-08-28 03:16:11 +00007701
Richard Smith23d55872012-04-02 01:30:27 +00007702 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redl08905022011-02-05 19:23:19 +00007703 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smith09d5b3a2014-05-01 00:35:04 +00007704 UsingDecl *UD = BuildValid();
7705 CheckInheritingConstructorUsingDecl(UD);
Sebastian Redl08905022011-02-05 19:23:19 +00007706 return UD;
7707 }
7708
7709 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00007710
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007711 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00007712
John McCall3969e302009-12-08 07:46:18 +00007713 // Unlike most lookups, we don't always want to hide tag
7714 // declarations: tag names are visible through the using declaration
7715 // even if hidden by ordinary names, *except* in a dependent context
7716 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00007717 if (!IsInstantiation)
7718 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00007719
John McCall5dadb652012-04-07 03:04:20 +00007720 // For the purposes of this lookup, we have a base object type
7721 // equal to that of the current context.
7722 if (CurContext->isRecord()) {
7723 R.setBaseObjectType(
7724 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7725 }
7726
John McCall27b18f82009-11-17 02:14:36 +00007727 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00007728
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007729 // Try to correct typos if possible.
John McCall9f3059a2009-10-09 21:13:30 +00007730 if (R.empty()) {
Richard Smith09d5b3a2014-05-01 00:35:04 +00007731 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
Richard Smith21866c32014-04-30 18:03:21 +00007732 dyn_cast<CXXRecordDecl>(CurContext));
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007733 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
John Thompson2255f2c2014-04-23 12:57:01 +00007734 R.getLookupKind(), S, &SS, CCC,
7735 CTK_ErrorRecovery)){
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007736 // We reject any correction for which ND would be NULL.
7737 NamedDecl *ND = Corrected.getCorrectionDecl();
Richard Smith09d5b3a2014-05-01 00:35:04 +00007738
Richard Smithf9b15102013-08-17 00:46:16 +00007739 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007740 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00007741 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7742 << NameInfo.getName() << LookupContext << 0
7743 << SS.getRange());
Richard Smith09d5b3a2014-05-01 00:35:04 +00007744
7745 // If we corrected to an inheriting constructor, handle it as one.
7746 auto *RD = dyn_cast<CXXRecordDecl>(ND);
7747 if (RD && RD->isInjectedClassName()) {
7748 // Fix up the information we'll use to build the using declaration.
7749 if (Corrected.WillReplaceSpecifier()) {
7750 NestedNameSpecifierLocBuilder Builder;
7751 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
7752 QualifierLoc.getSourceRange());
7753 QualifierLoc = Builder.getWithLocInContext(Context);
7754 }
7755
7756 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
7757 Context.getCanonicalType(Context.getRecordType(RD))));
Craig Topperc3ec1492014-05-26 06:22:03 +00007758 NameInfo.setNamedTypeInfo(nullptr);
Richard Smith09d5b3a2014-05-01 00:35:04 +00007759
7760 // Build it and process it as an inheriting constructor.
7761 UsingDecl *UD = BuildValid();
7762 CheckInheritingConstructorUsingDecl(UD);
7763 return UD;
7764 }
7765
7766 // FIXME: Pick up all the declarations if we found an overloaded function.
7767 R.setLookupName(Corrected.getCorrection());
7768 R.addDecl(ND);
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007769 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007770 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007771 << NameInfo.getName() << LookupContext << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00007772 return BuildInvalid();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007773 }
Douglas Gregorfec52632009-06-20 00:51:54 +00007774 }
7775
Richard Smith09d5b3a2014-05-01 00:35:04 +00007776 if (R.isAmbiguous())
7777 return BuildInvalid();
Mike Stump11289f42009-09-09 15:08:12 +00007778
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007779 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00007780 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00007781 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007782 Diag(IdentLoc, diag::err_using_typename_non_type);
7783 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7784 Diag((*I)->getUnderlyingDecl()->getLocation(),
7785 diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00007786 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00007787 }
7788 } else {
7789 // If we asked for a non-typename and we got a type, error out,
7790 // but only if this is an instantiation of an unresolved using
7791 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00007792 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007793 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7794 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00007795 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00007796 }
Anders Carlsson59140b32009-08-28 03:16:11 +00007797 }
7798
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007799 // C++0x N2914 [namespace.udecl]p6:
7800 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00007801 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007802 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7803 << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00007804 return BuildInvalid();
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007805 }
Mike Stump11289f42009-09-09 15:08:12 +00007806
Richard Smith09d5b3a2014-05-01 00:35:04 +00007807 UsingDecl *UD = BuildValid();
John McCall84d87672009-12-10 09:41:52 +00007808 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007809 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00007810 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7811 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00007812 }
John McCall3f746822009-11-17 05:59:44 +00007813
7814 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00007815}
7816
Sebastian Redl08905022011-02-05 19:23:19 +00007817/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00007818bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007819 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00007820
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007821 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00007822 assert(SourceType &&
7823 "Using decl naming constructor doesn't have type in scope spec.");
7824 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7825
7826 // Check whether the named type is a direct base class.
Richard Smith09d5b3a2014-05-01 00:35:04 +00007827 bool AnyDependentBases = false;
7828 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
7829 AnyDependentBases);
7830 if (!Base && !AnyDependentBases) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007831 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00007832 diag::err_using_decl_constructor_not_in_direct_base)
7833 << UD->getNameInfo().getSourceRange()
7834 << QualType(SourceType, 0) << TargetClass;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007835 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00007836 return true;
7837 }
7838
Richard Smith09d5b3a2014-05-01 00:35:04 +00007839 if (Base)
7840 Base->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00007841
7842 return false;
7843}
7844
John McCall84d87672009-12-10 09:41:52 +00007845/// Checks that the given using declaration is not an invalid
7846/// redeclaration. Note that this is checking only for the using decl
7847/// itself, not for any ill-formedness among the UsingShadowDecls.
7848bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007849 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00007850 const CXXScopeSpec &SS,
7851 SourceLocation NameLoc,
7852 const LookupResult &Prev) {
7853 // C++03 [namespace.udecl]p8:
7854 // C++0x [namespace.udecl]p10:
7855 // A using-declaration is a declaration and can therefore be used
7856 // repeatedly where (and only where) multiple declarations are
7857 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00007858 //
John McCall032092f2010-11-29 18:01:58 +00007859 // That's in non-member contexts.
7860 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00007861 return false;
7862
Aaron Ballman4a979672014-01-03 13:56:08 +00007863 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall84d87672009-12-10 09:41:52 +00007864
7865 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7866 NamedDecl *D = *I;
7867
7868 bool DTypename;
7869 NestedNameSpecifier *DQual;
7870 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007871 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007872 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007873 } else if (UnresolvedUsingValueDecl *UD
7874 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7875 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007876 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007877 } else if (UnresolvedUsingTypenameDecl *UD
7878 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7879 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007880 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007881 } else continue;
7882
7883 // using decls differ if one says 'typename' and the other doesn't.
7884 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007885 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00007886
7887 // using decls differ if they name different scopes (but note that
7888 // template instantiation can cause this check to trigger when it
7889 // didn't before instantiation).
7890 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7891 Context.getCanonicalNestedNameSpecifier(DQual))
7892 continue;
7893
7894 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00007895 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00007896 return true;
7897 }
7898
7899 return false;
7900}
7901
John McCall3969e302009-12-08 07:46:18 +00007902
John McCallb96ec562009-12-04 22:46:56 +00007903/// Checks that the given nested-name qualifier used in a using decl
7904/// in the current context is appropriately related to the current
7905/// scope. If an error is found, diagnoses it and returns true.
7906bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7907 const CXXScopeSpec &SS,
Richard Smith7ad0b882014-04-02 21:44:35 +00007908 const DeclarationNameInfo &NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00007909 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00007910 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007911
John McCall3969e302009-12-08 07:46:18 +00007912 if (!CurContext->isRecord()) {
7913 // C++03 [namespace.udecl]p3:
7914 // C++0x [namespace.udecl]p8:
7915 // A using-declaration for a class member shall be a member-declaration.
7916
7917 // If we weren't able to compute a valid scope, it must be a
7918 // dependent class scope.
7919 if (!NamedContext || NamedContext->isRecord()) {
Richard Smith7ad0b882014-04-02 21:44:35 +00007920 auto *RD = dyn_cast<CXXRecordDecl>(NamedContext);
7921 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
Craig Topperc3ec1492014-05-26 06:22:03 +00007922 RD = nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00007923
John McCall3969e302009-12-08 07:46:18 +00007924 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7925 << SS.getRange();
Richard Smith7ad0b882014-04-02 21:44:35 +00007926
7927 // If we have a complete, non-dependent source type, try to suggest a
7928 // way to get the same effect.
7929 if (!RD)
7930 return true;
7931
7932 // Find what this using-declaration was referring to.
7933 LookupResult R(*this, NameInfo, LookupOrdinaryName);
7934 R.setHideTags(false);
7935 R.suppressDiagnostics();
7936 LookupQualifiedName(R, RD);
7937
7938 if (R.getAsSingle<TypeDecl>()) {
7939 if (getLangOpts().CPlusPlus11) {
7940 // Convert 'using X::Y;' to 'using Y = X::Y;'.
7941 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
7942 << 0 // alias declaration
7943 << FixItHint::CreateInsertion(SS.getBeginLoc(),
7944 NameInfo.getName().getAsString() +
7945 " = ");
7946 } else {
7947 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
7948 SourceLocation InsertLoc =
7949 PP.getLocForEndOfToken(NameInfo.getLocEnd());
7950 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
7951 << 1 // typedef declaration
7952 << FixItHint::CreateReplacement(UsingLoc, "typedef")
7953 << FixItHint::CreateInsertion(
7954 InsertLoc, " " + NameInfo.getName().getAsString());
7955 }
7956 } else if (R.getAsSingle<VarDecl>()) {
7957 // Don't provide a fixit outside C++11 mode; we don't want to suggest
7958 // repeating the type of the static data member here.
7959 FixItHint FixIt;
7960 if (getLangOpts().CPlusPlus11) {
7961 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
7962 FixIt = FixItHint::CreateReplacement(
7963 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
7964 }
7965
7966 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
7967 << 2 // reference declaration
7968 << FixIt;
7969 }
John McCall3969e302009-12-08 07:46:18 +00007970 return true;
7971 }
7972
7973 // Otherwise, everything is known to be fine.
7974 return false;
7975 }
7976
7977 // The current scope is a record.
7978
7979 // If the named context is dependent, we can't decide much.
7980 if (!NamedContext) {
7981 // FIXME: in C++0x, we can diagnose if we can prove that the
7982 // nested-name-specifier does not refer to a base class, which is
7983 // still possible in some cases.
7984
7985 // Otherwise we have to conservatively report that things might be
7986 // okay.
7987 return false;
7988 }
7989
7990 if (!NamedContext->isRecord()) {
7991 // Ideally this would point at the last name in the specifier,
7992 // but we don't have that level of source info.
7993 Diag(SS.getRange().getBegin(),
7994 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00007995 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00007996 return true;
7997 }
7998
Douglas Gregor7c842292010-12-21 07:41:49 +00007999 if (!NamedContext->isDependentContext() &&
8000 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8001 return true;
8002
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008003 if (getLangOpts().CPlusPlus11) {
John McCall3969e302009-12-08 07:46:18 +00008004 // C++0x [namespace.udecl]p3:
8005 // In a using-declaration used as a member-declaration, the
8006 // nested-name-specifier shall name a base class of the class
8007 // being defined.
8008
8009 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8010 cast<CXXRecordDecl>(NamedContext))) {
8011 if (CurContext == NamedContext) {
8012 Diag(NameLoc,
8013 diag::err_using_decl_nested_name_specifier_is_current_class)
8014 << SS.getRange();
8015 return true;
8016 }
8017
8018 Diag(SS.getRange().getBegin(),
8019 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00008020 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00008021 << cast<CXXRecordDecl>(CurContext)
8022 << SS.getRange();
8023 return true;
8024 }
8025
8026 return false;
8027 }
8028
8029 // C++03 [namespace.udecl]p4:
8030 // A using-declaration used as a member-declaration shall refer
8031 // to a member of a base class of the class being defined [etc.].
8032
8033 // Salient point: SS doesn't have to name a base class as long as
8034 // lookup only finds members from base classes. Therefore we can
8035 // diagnose here only if we can prove that that can't happen,
8036 // i.e. if the class hierarchies provably don't intersect.
8037
8038 // TODO: it would be nice if "definitely valid" results were cached
8039 // in the UsingDecl and UsingShadowDecl so that these checks didn't
8040 // need to be repeated.
8041
8042 struct UserData {
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00008043 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall3969e302009-12-08 07:46:18 +00008044
8045 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
8046 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8047 Data->Bases.insert(Base);
8048 return true;
8049 }
8050
8051 bool hasDependentBases(const CXXRecordDecl *Class) {
8052 return !Class->forallBases(collect, this);
8053 }
8054
8055 /// Returns true if the base is dependent or is one of the
8056 /// accumulated base classes.
8057 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
8058 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8059 return !Data->Bases.count(Base);
8060 }
8061
8062 bool mightShareBases(const CXXRecordDecl *Class) {
8063 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
8064 }
8065 };
8066
8067 UserData Data;
8068
8069 // Returns false if we find a dependent base.
8070 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
8071 return false;
8072
8073 // Returns false if the class has a dependent base or if it or one
8074 // of its bases is present in the base set of the current context.
8075 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
8076 return false;
8077
8078 Diag(SS.getRange().getBegin(),
8079 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00008080 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00008081 << cast<CXXRecordDecl>(CurContext)
8082 << SS.getRange();
8083
8084 return true;
John McCallb96ec562009-12-04 22:46:56 +00008085}
8086
Richard Smithdda56e42011-04-15 14:24:37 +00008087Decl *Sema::ActOnAliasDeclaration(Scope *S,
8088 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008089 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00008090 SourceLocation UsingLoc,
8091 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00008092 AttributeList *AttrList,
Richard Smithdda56e42011-04-15 14:24:37 +00008093 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00008094 // Skip up to the relevant declaration scope.
8095 while (S->getFlags() & Scope::TemplateParamScope)
8096 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00008097 assert((S->getFlags() & Scope::DeclScope) &&
8098 "got alias-declaration outside of declaration scope");
8099
8100 if (Type.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00008101 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008102
8103 bool Invalid = false;
8104 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
Craig Topperc3ec1492014-05-26 06:22:03 +00008105 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky82e47802011-05-02 01:07:19 +00008106 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00008107
8108 if (DiagnoseClassNameShadow(CurContext, NameInfo))
Craig Topperc3ec1492014-05-26 06:22:03 +00008109 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008110
8111 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008112 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00008113 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008114 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8115 TInfo->getTypeLoc().getBeginLoc());
8116 }
Richard Smithdda56e42011-04-15 14:24:37 +00008117
8118 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8119 LookupName(Previous, S);
8120
8121 // Warn about shadowing the name of a template parameter.
8122 if (Previous.isSingleResult() &&
8123 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00008124 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00008125 Previous.clear();
8126 }
8127
8128 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8129 "name in alias declaration must be an identifier");
8130 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8131 Name.StartLocation,
8132 Name.Identifier, TInfo);
8133
8134 NewTD->setAccess(AS);
8135
8136 if (Invalid)
8137 NewTD->setInvalidDecl();
8138
Richard Smith54ecd982013-02-20 19:22:51 +00008139 ProcessDeclAttributeList(S, NewTD, AttrList);
8140
Richard Smith3f1b5d02011-05-05 21:57:07 +00008141 CheckTypedefForVariablyModifiedType(S, NewTD);
8142 Invalid |= NewTD->isInvalidDecl();
8143
Richard Smithdda56e42011-04-15 14:24:37 +00008144 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008145
8146 NamedDecl *NewND;
8147 if (TemplateParamLists.size()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008148 TypeAliasTemplateDecl *OldDecl = nullptr;
8149 TemplateParameterList *OldTemplateParams = nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008150
8151 if (TemplateParamLists.size() != 1) {
8152 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008153 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8154 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00008155 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008156 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00008157
8158 // Only consider previous declarations in the same scope.
8159 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8160 /*ExplicitInstantiationOrSpecialization*/false);
8161 if (!Previous.empty()) {
8162 Redeclaration = true;
8163
8164 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8165 if (!OldDecl && !Invalid) {
8166 Diag(UsingLoc, diag::err_redefinition_different_kind)
8167 << Name.Identifier;
8168
8169 NamedDecl *OldD = Previous.getRepresentativeDecl();
8170 if (OldD->getLocation().isValid())
8171 Diag(OldD->getLocation(), diag::note_previous_definition);
8172
8173 Invalid = true;
8174 }
8175
8176 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8177 if (TemplateParameterListsAreEqual(TemplateParams,
8178 OldDecl->getTemplateParameters(),
8179 /*Complain=*/true,
8180 TPL_TemplateMatch))
8181 OldTemplateParams = OldDecl->getTemplateParameters();
8182 else
8183 Invalid = true;
8184
8185 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8186 if (!Invalid &&
8187 !Context.hasSameType(OldTD->getUnderlyingType(),
8188 NewTD->getUnderlyingType())) {
8189 // FIXME: The C++0x standard does not clearly say this is ill-formed,
8190 // but we can't reasonably accept it.
8191 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8192 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8193 if (OldTD->getLocation().isValid())
8194 Diag(OldTD->getLocation(), diag::note_previous_definition);
8195 Invalid = true;
8196 }
8197 }
8198 }
8199
8200 // Merge any previous default template arguments into our parameters,
8201 // and check the parameter list.
8202 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8203 TPC_TypeAliasTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +00008204 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008205
8206 TypeAliasTemplateDecl *NewDecl =
8207 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8208 Name.Identifier, TemplateParams,
8209 NewTD);
8210
8211 NewDecl->setAccess(AS);
8212
8213 if (Invalid)
8214 NewDecl->setInvalidDecl();
8215 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00008216 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008217
8218 NewND = NewDecl;
8219 } else {
8220 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8221 NewND = NewTD;
8222 }
Richard Smithdda56e42011-04-15 14:24:37 +00008223
8224 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00008225 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00008226
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00008227 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008228 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00008229}
8230
John McCall48871652010-08-21 09:40:31 +00008231Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00008232 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00008233 SourceLocation AliasLoc,
8234 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00008235 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00008236 SourceLocation IdentLoc,
8237 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00008238
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008239 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00008240 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8241 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008242
Anders Carlssondca83c42009-03-28 06:23:46 +00008243 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00008244 NamedDecl *PrevDecl
8245 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8246 ForRedeclaration);
8247 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
Craig Topperc3ec1492014-05-26 06:22:03 +00008248 PrevDecl = nullptr;
Douglas Gregor5cf8d672010-05-03 15:37:31 +00008249
8250 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008251 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00008252 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008253 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00008254 // FIXME: At some point, we'll want to create the (redundant)
8255 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00008256 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00008257 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
Craig Topperc3ec1492014-05-26 06:22:03 +00008258 return nullptr;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008259 }
Mike Stump11289f42009-09-09 15:08:12 +00008260
Anders Carlssondca83c42009-03-28 06:23:46 +00008261 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
8262 diag::err_redefinition_different_kind;
8263 Diag(AliasLoc, DiagID) << Alias;
8264 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Craig Topperc3ec1492014-05-26 06:22:03 +00008265 return nullptr;
Anders Carlssondca83c42009-03-28 06:23:46 +00008266 }
8267
John McCall27b18f82009-11-17 02:14:36 +00008268 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00008269 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008270
John McCall9f3059a2009-10-09 21:13:30 +00008271 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008272 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00008273 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00008274 return nullptr;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00008275 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00008276 }
Mike Stump11289f42009-09-09 15:08:12 +00008277
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008278 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00008279 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00008280 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00008281 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00008282
John McCalld8d0d432010-02-16 06:53:13 +00008283 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00008284 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00008285}
8286
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008287Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008288Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8289 CXXMethodDecl *MD) {
8290 CXXRecordDecl *ClassDecl = MD->getParent();
8291
Douglas Gregor6d880b12010-07-01 22:31:05 +00008292 // C++ [except.spec]p14:
8293 // An implicitly declared special member function (Clause 12) shall have an
8294 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00008295 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008296 if (ClassDecl->isInvalidDecl())
8297 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00008298
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008299 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008300 for (const auto &B : ClassDecl->bases()) {
8301 if (B.isVirtual()) // Handled below.
Douglas Gregor6d880b12010-07-01 22:31:05 +00008302 continue;
8303
Aaron Ballman574705e2014-03-13 15:41:46 +00008304 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008305 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008306 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8307 // If this is a deleted function, add it anyway. This might be conformant
8308 // with the standard. This might not. I'm not sure. It might not matter.
8309 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008310 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008311 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008312 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008313
8314 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008315 for (const auto &B : ClassDecl->vbases()) {
8316 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008317 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008318 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8319 // If this is a deleted function, add it anyway. This might be conformant
8320 // with the standard. This might not. I'm not sure. It might not matter.
8321 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008322 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008323 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008324 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008325
8326 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008327 for (const auto *F : ClassDecl->fields()) {
Richard Smith938f40b2011-06-11 17:19:42 +00008328 if (F->hasInClassInitializer()) {
8329 if (Expr *E = F->getInClassInitializer())
8330 ExceptSpec.CalledExpr(E);
8331 else if (!F->isInvalidDecl())
Richard Smithd3b5c9082012-07-27 04:22:15 +00008332 // DR1351:
8333 // If the brace-or-equal-initializer of a non-static data member
8334 // invokes a defaulted default constructor of its class or of an
8335 // enclosing class in a potentially evaluated subexpression, the
8336 // program is ill-formed.
8337 //
8338 // This resolution is unworkable: the exception specification of the
8339 // default constructor can be needed in an unevaluated context, in
8340 // particular, in the operand of a noexcept-expression, and we can be
8341 // unable to compute an exception specification for an enclosed class.
8342 //
8343 // We do not allow an in-class initializer to require the evaluation
8344 // of the exception specification for any in-class initializer whose
8345 // definition is not lexically complete.
8346 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith938f40b2011-06-11 17:19:42 +00008347 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00008348 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00008349 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8350 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8351 // If this is a deleted function, add it anyway. This might be conformant
8352 // with the standard. This might not. I'm not sure. It might not matter.
8353 // In particular, the problem is that this function never gets called. It
8354 // might just be ill-formed because this function attempts to refer to
8355 // a deleted function here.
8356 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008357 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008358 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008359 }
John McCalldb40c7f2010-12-14 08:05:40 +00008360
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008361 return ExceptSpec;
8362}
8363
Richard Smithc2bc61b2013-03-18 21:12:30 +00008364Sema::ImplicitExceptionSpecification
Richard Smithb7151b92013-04-10 06:11:48 +00008365Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8366 CXXRecordDecl *ClassDecl = CD->getParent();
8367
8368 // C++ [except.spec]p14:
8369 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00008370 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00008371 if (ClassDecl->isInvalidDecl())
8372 return ExceptSpec;
8373
8374 // Inherited constructor.
8375 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8376 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8377 // FIXME: Copying or moving the parameters could add extra exceptions to the
8378 // set, as could the default arguments for the inherited constructor. This
8379 // will be addressed when we implement the resolution of core issue 1351.
8380 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8381
8382 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008383 for (const auto &B : ClassDecl->bases()) {
8384 if (B.isVirtual()) // Handled below.
Richard Smithb7151b92013-04-10 06:11:48 +00008385 continue;
8386
Aaron Ballman574705e2014-03-13 15:41:46 +00008387 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008388 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8389 if (BaseClassDecl == InheritedDecl)
8390 continue;
8391 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8392 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008393 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008394 }
8395 }
8396
8397 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008398 for (const auto &B : ClassDecl->vbases()) {
8399 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008400 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8401 if (BaseClassDecl == InheritedDecl)
8402 continue;
8403 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8404 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008405 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008406 }
8407 }
8408
8409 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008410 for (const auto *F : ClassDecl->fields()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008411 if (F->hasInClassInitializer()) {
8412 if (Expr *E = F->getInClassInitializer())
8413 ExceptSpec.CalledExpr(E);
8414 else if (!F->isInvalidDecl())
8415 Diag(CD->getLocation(),
8416 diag::err_in_class_initializer_references_def_ctor) << CD;
8417 } else if (const RecordType *RecordTy
8418 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8419 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8420 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8421 if (Constructor)
8422 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8423 }
8424 }
8425
Richard Smithc2bc61b2013-03-18 21:12:30 +00008426 return ExceptSpec;
8427}
8428
Richard Smith8bf22e52012-11-29 01:34:07 +00008429namespace {
8430/// RAII object to register a special member as being currently declared.
8431struct DeclaringSpecialMember {
8432 Sema &S;
8433 Sema::SpecialMemberDecl D;
8434 bool WasAlreadyBeingDeclared;
8435
8436 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8437 : S(S), D(RD, CSM) {
8438 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8439 if (WasAlreadyBeingDeclared)
8440 // This almost never happens, but if it does, ensure that our cache
8441 // doesn't contain a stale result.
8442 S.SpecialMemberCache.clear();
8443
8444 // FIXME: Register a note to be produced if we encounter an error while
8445 // declaring the special member.
8446 }
8447 ~DeclaringSpecialMember() {
8448 if (!WasAlreadyBeingDeclared)
8449 S.SpecialMembersBeingDeclared.erase(D);
8450 }
8451
8452 /// \brief Are we already trying to declare this special member?
8453 bool isAlreadyBeingDeclared() const {
8454 return WasAlreadyBeingDeclared;
8455 }
8456};
8457}
8458
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008459CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8460 CXXRecordDecl *ClassDecl) {
8461 // C++ [class.ctor]p5:
8462 // A default constructor for a class X is a constructor of class X
8463 // that can be called without an argument. If there is no
8464 // user-declared constructor for class X, a default constructor is
8465 // implicitly declared. An implicitly-declared default constructor
8466 // is an inline public member of its class.
Richard Smith7d125a12012-11-27 21:20:31 +00008467 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008468 "Should not build implicit default constructor!");
8469
Richard Smith8bf22e52012-11-29 01:34:07 +00008470 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8471 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00008472 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00008473
Richard Smithb5800092012-06-10 05:43:50 +00008474 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8475 CXXDefaultConstructor,
8476 false);
8477
Douglas Gregor6d880b12010-07-01 22:31:05 +00008478 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008479 CanQualType ClassType
8480 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008481 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008482 DeclarationName Name
8483 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008484 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00008485 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00008486 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8487 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8488 /*isImplicitlyDeclared=*/true, Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008489 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00008490 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008491 DefaultCon->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008492
8493 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008494 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008495 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008496
Richard Smith6b02d462012-12-08 08:32:28 +00008497 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8498 // constructors is easy to compute.
8499 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8500
8501 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008502 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008503
Douglas Gregor9672f922010-07-03 00:47:00 +00008504 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00008505 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00008506
Douglas Gregor0be31a22010-07-02 17:43:08 +00008507 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00008508 PushOnScopeChains(DefaultCon, S, false);
8509 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008510
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008511 return DefaultCon;
8512}
8513
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008514void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8515 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008516 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008517 !Constructor->doesThisDeclarationHaveABody() &&
8518 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008519 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008520
Anders Carlsson423f5d82010-04-23 16:04:08 +00008521 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00008522 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00008523
Eli Friedmaneaf34142012-10-18 20:14:08 +00008524 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008525 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00008526 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008527 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008528 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008529 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00008530 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00008531 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00008532 }
Douglas Gregor73193272010-09-20 16:48:21 +00008533
Daniel Jasperb3b0b802014-06-20 08:44:22 +00008534 SourceLocation Loc = Constructor->getLocEnd().isValid()
8535 ? Constructor->getLocEnd()
8536 : Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008537 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +00008538
Eli Friedman276dd182013-09-05 00:02:25 +00008539 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +00008540 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008541
8542 if (ASTMutationListener *L = getASTMutationListener()) {
8543 L->CompletedImplicitDefinition(Constructor);
8544 }
Richard Trieuef64e942013-10-25 00:56:00 +00008545
8546 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008547}
8548
Richard Smith938f40b2011-06-11 17:19:42 +00008549void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008550 // Perform any delayed checks on exception specifications.
8551 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +00008552}
8553
Richard Smith185be182013-04-10 05:48:59 +00008554namespace {
8555/// Information on inheriting constructors to declare.
8556class InheritingConstructorInfo {
8557public:
8558 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8559 : SemaRef(SemaRef), Derived(Derived) {
8560 // Mark the constructors that we already have in the derived class.
8561 //
8562 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8563 // unless there is a user-declared constructor with the same signature in
8564 // the class where the using-declaration appears.
8565 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8566 }
8567
8568 void inheritAll(CXXRecordDecl *RD) {
8569 visitAll(RD, &InheritingConstructorInfo::inherit);
8570 }
8571
8572private:
8573 /// Information about an inheriting constructor.
8574 struct InheritingConstructor {
8575 InheritingConstructor()
Craig Topperc3ec1492014-05-26 06:22:03 +00008576 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
Richard Smith185be182013-04-10 05:48:59 +00008577
8578 /// If \c true, a constructor with this signature is already declared
8579 /// in the derived class.
8580 bool DeclaredInDerived;
8581
8582 /// The constructor which is inherited.
8583 const CXXConstructorDecl *BaseCtor;
8584
8585 /// The derived constructor we declared.
8586 CXXConstructorDecl *DerivedCtor;
8587 };
8588
8589 /// Inheriting constructors with a given canonical type. There can be at
8590 /// most one such non-template constructor, and any number of templated
8591 /// constructors.
8592 struct InheritingConstructorsForType {
8593 InheritingConstructor NonTemplate;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008594 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8595 Templates;
Richard Smith185be182013-04-10 05:48:59 +00008596
8597 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8598 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8599 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8600 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8601 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8602 false, S.TPL_TemplateMatch))
8603 return Templates[I].second;
8604 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8605 return Templates.back().second;
Sebastian Redl08905022011-02-05 19:23:19 +00008606 }
Richard Smith185be182013-04-10 05:48:59 +00008607
8608 return NonTemplate;
8609 }
8610 };
8611
8612 /// Get or create the inheriting constructor record for a constructor.
8613 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8614 QualType CtorType) {
8615 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8616 .getEntry(SemaRef, Ctor);
8617 }
8618
8619 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8620
8621 /// Process all constructors for a class.
8622 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00008623 for (const auto *Ctor : RD->ctors())
8624 (this->*Callback)(Ctor);
Richard Smith185be182013-04-10 05:48:59 +00008625 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8626 I(RD->decls_begin()), E(RD->decls_end());
8627 I != E; ++I) {
8628 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8629 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8630 (this->*Callback)(CD);
Sebastian Redl08905022011-02-05 19:23:19 +00008631 }
8632 }
Richard Smith185be182013-04-10 05:48:59 +00008633
8634 /// Note that a constructor (or constructor template) was declared in Derived.
8635 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8636 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8637 }
8638
8639 /// Inherit a single constructor.
8640 void inherit(const CXXConstructorDecl *Ctor) {
8641 const FunctionProtoType *CtorType =
8642 Ctor->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00008643 ArrayRef<QualType> ArgTypes(CtorType->getParamTypes());
Richard Smith185be182013-04-10 05:48:59 +00008644 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8645
8646 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8647
8648 // Core issue (no number yet): the ellipsis is always discarded.
8649 if (EPI.Variadic) {
8650 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8651 SemaRef.Diag(Ctor->getLocation(),
8652 diag::note_using_decl_constructor_ellipsis);
8653 EPI.Variadic = false;
8654 }
8655
8656 // Declare a constructor for each number of parameters.
8657 //
8658 // C++11 [class.inhctor]p1:
8659 // The candidate set of inherited constructors from the class X named in
8660 // the using-declaration consists of [... modulo defects ...] for each
8661 // constructor or constructor template of X, the set of constructors or
8662 // constructor templates that results from omitting any ellipsis parameter
8663 // specification and successively omitting parameters with a default
8664 // argument from the end of the parameter-type-list
Richard Smith3c626ed2013-04-17 19:00:52 +00008665 unsigned MinParams = minParamsToInherit(Ctor);
8666 unsigned Params = Ctor->getNumParams();
8667 if (Params >= MinParams) {
8668 do
8669 declareCtor(UsingLoc, Ctor,
8670 SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00008671 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
Richard Smith3c626ed2013-04-17 19:00:52 +00008672 while (Params > MinParams &&
8673 Ctor->getParamDecl(--Params)->hasDefaultArg());
8674 }
Richard Smith185be182013-04-10 05:48:59 +00008675 }
8676
8677 /// Find the using-declaration which specified that we should inherit the
8678 /// constructors of \p Base.
8679 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8680 // No fancy lookup required; just look for the base constructor name
8681 // directly within the derived class.
8682 ASTContext &Context = SemaRef.Context;
8683 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8684 Context.getCanonicalType(Context.getRecordType(Base)));
8685 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8686 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8687 }
8688
8689 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8690 // C++11 [class.inhctor]p3:
8691 // [F]or each constructor template in the candidate set of inherited
8692 // constructors, a constructor template is implicitly declared
8693 if (Ctor->getDescribedFunctionTemplate())
8694 return 0;
8695
8696 // For each non-template constructor in the candidate set of inherited
8697 // constructors other than a constructor having no parameters or a
8698 // copy/move constructor having a single parameter, a constructor is
8699 // implicitly declared [...]
8700 if (Ctor->getNumParams() == 0)
8701 return 1;
8702 if (Ctor->isCopyOrMoveConstructor())
8703 return 2;
8704
8705 // Per discussion on core reflector, never inherit a constructor which
8706 // would become a default, copy, or move constructor of Derived either.
8707 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8708 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8709 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8710 }
8711
8712 /// Declare a single inheriting constructor, inheriting the specified
8713 /// constructor, with the given type.
8714 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8715 QualType DerivedType) {
8716 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8717
8718 // C++11 [class.inhctor]p3:
8719 // ... a constructor is implicitly declared with the same constructor
8720 // characteristics unless there is a user-declared constructor with
8721 // the same signature in the class where the using-declaration appears
8722 if (Entry.DeclaredInDerived)
8723 return;
8724
8725 // C++11 [class.inhctor]p7:
8726 // If two using-declarations declare inheriting constructors with the
8727 // same signature, the program is ill-formed
8728 if (Entry.DerivedCtor) {
8729 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8730 // Only diagnose this once per constructor.
8731 if (Entry.DerivedCtor->isInvalidDecl())
8732 return;
8733 Entry.DerivedCtor->setInvalidDecl();
8734
8735 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8736 SemaRef.Diag(BaseCtor->getLocation(),
8737 diag::note_using_decl_constructor_conflict_current_ctor);
8738 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8739 diag::note_using_decl_constructor_conflict_previous_ctor);
8740 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8741 diag::note_using_decl_constructor_conflict_previous_using);
8742 } else {
8743 // Core issue (no number): if the same inheriting constructor is
8744 // produced by multiple base class constructors from the same base
8745 // class, the inheriting constructor is defined as deleted.
8746 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8747 }
8748
8749 return;
8750 }
8751
8752 ASTContext &Context = SemaRef.Context;
8753 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8754 Context.getCanonicalType(Context.getRecordType(Derived)));
8755 DeclarationNameInfo NameInfo(Name, UsingLoc);
8756
Craig Topperc3ec1492014-05-26 06:22:03 +00008757 TemplateParameterList *TemplateParams = nullptr;
Richard Smith185be182013-04-10 05:48:59 +00008758 if (const FunctionTemplateDecl *FTD =
8759 BaseCtor->getDescribedFunctionTemplate()) {
8760 TemplateParams = FTD->getTemplateParameters();
8761 // We're reusing template parameters from a different DeclContext. This
8762 // is questionable at best, but works out because the template depth in
8763 // both places is guaranteed to be 0.
8764 // FIXME: Rebuild the template parameters in the new context, and
8765 // transform the function type to refer to them.
8766 }
8767
8768 // Build type source info pointing at the using-declaration. This is
8769 // required by template instantiation.
8770 TypeSourceInfo *TInfo =
8771 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8772 FunctionProtoTypeLoc ProtoLoc =
8773 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8774
8775 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8776 Context, Derived, UsingLoc, NameInfo, DerivedType,
8777 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8778 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8779
8780 // Build an unevaluated exception specification for this constructor.
8781 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8782 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00008783 EPI.ExceptionSpec.Type = EST_Unevaluated;
8784 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
Alp Toker314cc812014-01-25 16:55:45 +00008785 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00008786 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +00008787
8788 // Build the parameter declarations.
8789 SmallVector<ParmVarDecl *, 16> ParamDecls;
Alp Toker9cacbab2014-01-20 20:26:09 +00008790 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +00008791 TypeSourceInfo *TInfo =
Alp Toker9cacbab2014-01-20 20:26:09 +00008792 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
Richard Smith185be182013-04-10 05:48:59 +00008793 ParmVarDecl *PD = ParmVarDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00008794 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
8795 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
Richard Smith185be182013-04-10 05:48:59 +00008796 PD->setScopeInfo(0, I);
8797 PD->setImplicit();
8798 ParamDecls.push_back(PD);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00008799 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +00008800 }
8801
8802 // Set up the new constructor.
8803 DerivedCtor->setAccess(BaseCtor->getAccess());
8804 DerivedCtor->setParams(ParamDecls);
8805 DerivedCtor->setInheritedConstructor(BaseCtor);
8806 if (BaseCtor->isDeleted())
8807 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8808
8809 // If this is a constructor template, build the template declaration.
8810 if (TemplateParams) {
8811 FunctionTemplateDecl *DerivedTemplate =
8812 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8813 TemplateParams, DerivedCtor);
8814 DerivedTemplate->setAccess(BaseCtor->getAccess());
8815 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8816 Derived->addDecl(DerivedTemplate);
8817 } else {
8818 Derived->addDecl(DerivedCtor);
8819 }
8820
8821 Entry.BaseCtor = BaseCtor;
8822 Entry.DerivedCtor = DerivedCtor;
8823 }
8824
8825 Sema &SemaRef;
8826 CXXRecordDecl *Derived;
8827 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8828 MapType Map;
8829};
8830}
8831
8832void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8833 // Defer declaring the inheriting constructors until the class is
8834 // instantiated.
8835 if (ClassDecl->isDependentContext())
Sebastian Redl08905022011-02-05 19:23:19 +00008836 return;
8837
Richard Smith185be182013-04-10 05:48:59 +00008838 // Find base classes from which we might inherit constructors.
8839 SmallVector<CXXRecordDecl*, 4> InheritedBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00008840 for (const auto &BaseIt : ClassDecl->bases())
8841 if (BaseIt.getInheritConstructors())
8842 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
Richard Smithc2bc61b2013-03-18 21:12:30 +00008843
Richard Smith185be182013-04-10 05:48:59 +00008844 // Go no further if we're not inheriting any constructors.
8845 if (InheritedBases.empty())
8846 return;
Sebastian Redl08905022011-02-05 19:23:19 +00008847
Richard Smith185be182013-04-10 05:48:59 +00008848 // Declare the inherited constructors.
8849 InheritingConstructorInfo ICI(*this, ClassDecl);
8850 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8851 ICI.inheritAll(InheritedBases[I]);
Sebastian Redl08905022011-02-05 19:23:19 +00008852}
8853
Richard Smithc2bc61b2013-03-18 21:12:30 +00008854void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8855 CXXConstructorDecl *Constructor) {
8856 CXXRecordDecl *ClassDecl = Constructor->getParent();
8857 assert(Constructor->getInheritedConstructor() &&
8858 !Constructor->doesThisDeclarationHaveABody() &&
8859 !Constructor->isDeleted());
8860
8861 SynthesizedFunctionScope Scope(*this, Constructor);
8862 DiagnosticErrorTrap Trap(Diags);
8863 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8864 Trap.hasErrorOccurred()) {
8865 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8866 << Context.getTagDeclType(ClassDecl);
8867 Constructor->setInvalidDecl();
8868 return;
8869 }
8870
8871 SourceLocation Loc = Constructor->getLocation();
8872 Constructor->setBody(new (Context) CompoundStmt(Loc));
8873
Eli Friedman276dd182013-09-05 00:02:25 +00008874 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +00008875 MarkVTableUsed(CurrentLocation, ClassDecl);
8876
8877 if (ASTMutationListener *L = getASTMutationListener()) {
8878 L->CompletedImplicitDefinition(Constructor);
8879 }
8880}
8881
8882
Alexis Huntf91729462011-05-12 22:46:25 +00008883Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008884Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8885 CXXRecordDecl *ClassDecl = MD->getParent();
8886
Douglas Gregorf1203042010-07-01 19:09:28 +00008887 // C++ [except.spec]p14:
8888 // An implicitly declared special member function (Clause 12) shall have
8889 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +00008890 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008891 if (ClassDecl->isInvalidDecl())
8892 return ExceptSpec;
8893
Douglas Gregorf1203042010-07-01 19:09:28 +00008894 // Direct base-class destructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008895 for (const auto &B : ClassDecl->bases()) {
8896 if (B.isVirtual()) // Handled below.
Douglas Gregorf1203042010-07-01 19:09:28 +00008897 continue;
8898
Aaron Ballman574705e2014-03-13 15:41:46 +00008899 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8900 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008901 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008902 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008903
Douglas Gregorf1203042010-07-01 19:09:28 +00008904 // Virtual base-class destructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008905 for (const auto &B : ClassDecl->vbases()) {
8906 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8907 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008908 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008909 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008910
Douglas Gregorf1203042010-07-01 19:09:28 +00008911 // Field destructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008912 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorf1203042010-07-01 19:09:28 +00008913 if (const RecordType *RecordTy
8914 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00008915 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008916 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008917 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008918
Alexis Huntf91729462011-05-12 22:46:25 +00008919 return ExceptSpec;
8920}
8921
8922CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8923 // C++ [class.dtor]p2:
8924 // If a class has no user-declared destructor, a destructor is
8925 // declared implicitly. An implicitly-declared destructor is an
8926 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +00008927 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +00008928
Richard Smith8bf22e52012-11-29 01:34:07 +00008929 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8930 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00008931 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00008932
Douglas Gregor7454c562010-07-02 20:37:36 +00008933 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00008934 CanQualType ClassType
8935 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008936 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00008937 DeclarationName Name
8938 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008939 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00008940 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +00008941 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +00008942 QualType(), nullptr, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008943 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00008944 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00008945 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00008946 Destructor->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008947
8948 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008949 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008950 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008951
Richard Smith6b02d462012-12-08 08:32:28 +00008952 AddOverriddenMethods(ClassDecl, Destructor);
8953
8954 // We don't need to use SpecialMemberIsTrivial here; triviality for
8955 // destructors is easy to compute.
8956 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8957
8958 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008959 SetDeclDeleted(Destructor, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008960
Douglas Gregor7454c562010-07-02 20:37:36 +00008961 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00008962 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +00008963
Douglas Gregor7454c562010-07-02 20:37:36 +00008964 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00008965 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00008966 PushOnScopeChains(Destructor, S, false);
8967 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +00008968
Douglas Gregorf1203042010-07-01 19:09:28 +00008969 return Destructor;
8970}
8971
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008972void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00008973 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008974 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +00008975 !Destructor->doesThisDeclarationHaveABody() &&
8976 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008977 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00008978 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008979 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008980
Douglas Gregor54818f02010-05-12 16:39:35 +00008981 if (Destructor->isInvalidDecl())
8982 return;
8983
Eli Friedmaneaf34142012-10-18 20:14:08 +00008984 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008985
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008986 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00008987 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8988 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00008989
Douglas Gregor54818f02010-05-12 16:39:35 +00008990 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008991 Diag(CurrentLocation, diag::note_member_synthesized_at)
8992 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8993
8994 Destructor->setInvalidDecl();
8995 return;
8996 }
8997
Daniel Jasperb3b0b802014-06-20 08:44:22 +00008998 SourceLocation Loc = Destructor->getLocEnd().isValid()
8999 ? Destructor->getLocEnd()
9000 : Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00009001 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +00009002 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009003 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00009004
9005 if (ASTMutationListener *L = getASTMutationListener()) {
9006 L->CompletedImplicitDefinition(Destructor);
9007 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009008}
9009
Richard Smith84973e52012-04-21 18:42:51 +00009010/// \brief Perform any semantic analysis which needs to be delayed until all
9011/// pending class member declarations have been parsed.
9012void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00009013 // If the context is an invalid C++ class, just suppress these checks.
9014 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9015 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +00009016 DelayedDefaultedMemberExceptionSpecs.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00009017 DelayedDestructorExceptionSpecChecks.clear();
9018 return;
9019 }
9020 }
Richard Smith84973e52012-04-21 18:42:51 +00009021}
9022
Richard Smithd3b5c9082012-07-27 04:22:15 +00009023void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9024 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009025 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00009026 "adjusting dtor exception specs was introduced in c++11");
9027
Sebastian Redl623ea822011-05-19 05:13:44 +00009028 // C++11 [class.dtor]p3:
9029 // A declaration of a destructor that does not have an exception-
9030 // specification is implicitly considered to have the same exception-
9031 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009032 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +00009033 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009034 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +00009035 return;
9036
Chandler Carruth9a797572011-09-20 04:55:26 +00009037 // Replace the destructor's type, building off the existing one. Fortunately,
9038 // the only thing of interest in the destructor type is its extended info.
9039 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009040 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00009041 EPI.ExceptionSpec.Type = EST_Unevaluated;
9042 EPI.ExceptionSpec.SourceDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009043 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +00009044
Sebastian Redl623ea822011-05-19 05:13:44 +00009045 // FIXME: If the destructor has a body that could throw, and the newly created
9046 // spec doesn't allow exceptions, we should emit a warning, because this
9047 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009048 // However, we don't have a body or an exception specification yet, so it
9049 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +00009050}
9051
Pavel Labath58934982013-08-30 08:52:28 +00009052namespace {
9053/// \brief An abstract base class for all helper classes used in building the
9054// copy/move operators. These classes serve as factory functions and help us
9055// avoid using the same Expr* in the AST twice.
9056class ExprBuilder {
9057 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9058 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9059
9060protected:
9061 static Expr *assertNotNull(Expr *E) {
9062 assert(E && "Expression construction must not fail.");
9063 return E;
9064 }
9065
9066public:
9067 ExprBuilder() {}
9068 virtual ~ExprBuilder() {}
9069
9070 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9071};
9072
9073class RefBuilder: public ExprBuilder {
9074 VarDecl *Var;
9075 QualType VarType;
9076
9077public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009078 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009079 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009080 }
9081
9082 RefBuilder(VarDecl *Var, QualType VarType)
9083 : Var(Var), VarType(VarType) {}
9084};
9085
9086class ThisBuilder: public ExprBuilder {
9087public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009088 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009089 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
Pavel Labath58934982013-08-30 08:52:28 +00009090 }
9091};
9092
9093class CastBuilder: public ExprBuilder {
9094 const ExprBuilder &Builder;
9095 QualType Type;
9096 ExprValueKind Kind;
9097 const CXXCastPath &Path;
9098
9099public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009100 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009101 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9102 CK_UncheckedDerivedToBase, Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009103 &Path).get());
Pavel Labath58934982013-08-30 08:52:28 +00009104 }
9105
9106 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9107 const CXXCastPath &Path)
9108 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9109};
9110
9111class DerefBuilder: public ExprBuilder {
9112 const ExprBuilder &Builder;
9113
9114public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009115 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009116 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009117 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009118 }
9119
9120 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9121};
9122
9123class MemberBuilder: public ExprBuilder {
9124 const ExprBuilder &Builder;
9125 QualType Type;
9126 CXXScopeSpec SS;
9127 bool IsArrow;
9128 LookupResult &MemberLookup;
9129
9130public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009131 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009132 return assertNotNull(S.BuildMemberReferenceExpr(
Craig Topperc3ec1492014-05-26 06:22:03 +00009133 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009134 nullptr, MemberLookup, nullptr).get());
Pavel Labath58934982013-08-30 08:52:28 +00009135 }
9136
9137 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9138 LookupResult &MemberLookup)
9139 : Builder(Builder), Type(Type), IsArrow(IsArrow),
9140 MemberLookup(MemberLookup) {}
9141};
9142
9143class MoveCastBuilder: public ExprBuilder {
9144 const ExprBuilder &Builder;
9145
9146public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009147 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009148 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9149 }
9150
9151 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9152};
9153
9154class LvalueConvBuilder: public ExprBuilder {
9155 const ExprBuilder &Builder;
9156
9157public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009158 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009159 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009160 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009161 }
9162
9163 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9164};
9165
9166class SubscriptBuilder: public ExprBuilder {
9167 const ExprBuilder &Base;
9168 const ExprBuilder &Index;
9169
9170public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009171 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009172 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009173 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009174 }
9175
9176 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9177 : Base(Base), Index(Index) {}
9178};
9179
9180} // end anonymous namespace
9181
Richard Smith41ae3282012-11-14 00:50:40 +00009182/// When generating a defaulted copy or move assignment operator, if a field
9183/// should be copied with __builtin_memcpy rather than via explicit assignments,
9184/// do so. This optimization only applies for arrays of scalars, and for arrays
9185/// of class type where the selected copy/move-assignment operator is trivial.
9186static StmtResult
9187buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009188 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +00009189 // Compute the size of the memory buffer to be copied.
9190 QualType SizeType = S.Context.getSizeType();
9191 llvm::APInt Size(S.Context.getTypeSize(SizeType),
9192 S.Context.getTypeSizeInChars(T).getQuantity());
9193
9194 // Take the address of the field references for "from" and "to". We
9195 // directly construct UnaryOperators here because semantic analysis
9196 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009197 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009198 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9199 S.Context.getPointerType(From->getType()),
9200 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +00009201 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009202 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9203 S.Context.getPointerType(To->getType()),
9204 VK_RValue, OK_Ordinary, Loc);
9205
9206 const Type *E = T->getBaseElementTypeUnsafe();
9207 bool NeedsCollectableMemCpy =
9208 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9209
9210 // Create a reference to the __builtin_objc_memmove_collectable function
9211 StringRef MemCpyName = NeedsCollectableMemCpy ?
9212 "__builtin_objc_memmove_collectable" :
9213 "__builtin_memcpy";
9214 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9215 Sema::LookupOrdinaryName);
9216 S.LookupName(R, S.TUScope, true);
9217
9218 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9219 if (!MemCpy)
9220 // Something went horribly wrong earlier, and we will have complained
9221 // about it.
9222 return StmtError();
9223
9224 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
Craig Topperc3ec1492014-05-26 06:22:03 +00009225 VK_RValue, Loc, nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009226 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9227
9228 Expr *CallArgs[] = {
9229 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9230 };
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009231 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
Richard Smith41ae3282012-11-14 00:50:40 +00009232 Loc, CallArgs, Loc);
9233
9234 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009235 return Call.getAs<Stmt>();
Richard Smith41ae3282012-11-14 00:50:40 +00009236}
9237
Sebastian Redl22653ba2011-08-30 19:58:05 +00009238/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00009239/// \c To.
9240///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009241/// This routine is used to copy/move the members of a class with an
9242/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00009243/// copied are arrays, this routine builds for loops to copy them.
9244///
9245/// \param S The Sema object used for type-checking.
9246///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009247/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009248///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009249/// \param T The type of the expressions being copied/moved. Both expressions
9250/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009251///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009252/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009253///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009254/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009255///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009256/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009257/// Otherwise, it's a non-static member subobject.
9258///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009259/// \param Copying Whether we're copying or moving.
9260///
Douglas Gregorb139cd52010-05-01 20:49:11 +00009261/// \param Depth Internal parameter recording the depth of the recursion.
9262///
Richard Smith41ae3282012-11-14 00:50:40 +00009263/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9264/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +00009265static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +00009266buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009267 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009268 bool CopyingBaseSubobject, bool Copying,
9269 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +00009270 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00009271 // Each subobject is assigned in the manner appropriate to its type:
9272 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00009273 // - if the subobject is of class type, as if by a call to operator= with
9274 // the subobject as the object expression and the corresponding
9275 // subobject of x as a single function argument (as if by explicit
9276 // qualification; that is, ignoring any possible virtual overriding
9277 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +00009278 //
9279 // C++03 [class.copy]p13:
9280 // - if the subobject is of class type, the copy assignment operator for
9281 // the class is used (as if by explicit qualification; that is,
9282 // ignoring any possible virtual overriding functions in more derived
9283 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009284 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9285 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +00009286
Douglas Gregorb139cd52010-05-01 20:49:11 +00009287 // Look for operator=.
9288 DeclarationName Name
9289 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9290 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9291 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009292
Richard Smith52c0b582012-11-13 00:54:12 +00009293 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9294 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009295 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +00009296 LookupResult::Filter F = OpLookup.makeFilter();
9297 while (F.hasNext()) {
9298 NamedDecl *D = F.next();
9299 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9300 if (Method->isCopyAssignmentOperator() ||
9301 (!Copying && Method->isMoveAssignmentOperator()))
9302 continue;
9303
9304 F.erase();
9305 }
9306 F.done();
John McCallab8c2732010-03-16 06:11:48 +00009307 }
Richard Smith52c0b582012-11-13 00:54:12 +00009308
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009309 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +00009310 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009311 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +00009312 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009313 // ambiguities), we need to cast "this" to that subobject type; to
9314 // ensure that we don't go through the virtual call mechanism, we need
9315 // to qualify the operator= name with the base class (see below). However,
9316 // this means that if the base class has a protected copy assignment
9317 // operator, the protected member access check will fail. So, we
9318 // rewrite "protected" access to "public" access in this case, since we
9319 // know by construction that we're calling from a derived class.
9320 if (CopyingBaseSubobject) {
9321 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9322 L != LEnd; ++L) {
9323 if (L.getAccess() == AS_protected)
9324 L.setAccess(AS_public);
9325 }
9326 }
Richard Smith52c0b582012-11-13 00:54:12 +00009327
Douglas Gregorb139cd52010-05-01 20:49:11 +00009328 // Create the nested-name-specifier that will be used to qualify the
9329 // reference to operator=; this is required to suppress the virtual
9330 // call mechanism.
9331 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00009332 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +00009333 SS.MakeTrivial(S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +00009334 NestedNameSpecifier::Create(S.Context, nullptr, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00009335 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00009336 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009337
Douglas Gregorb139cd52010-05-01 20:49:11 +00009338 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00009339 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +00009340 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9341 SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009342 /*FirstQualifierInScope=*/nullptr,
Abramo Bagnara7945c982012-01-27 09:46:47 +00009343 OpLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00009344 /*TemplateArgs=*/nullptr,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009345 /*SuppressQualifierCheck=*/true);
9346 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009347 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009348
Douglas Gregorb139cd52010-05-01 20:49:11 +00009349 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00009350
Pavel Labath58934982013-08-30 08:52:28 +00009351 Expr *FromInst = From.build(S, Loc);
Craig Topperc3ec1492014-05-26 06:22:03 +00009352 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009353 OpEqualRef.getAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +00009354 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009355 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009356 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009357
Richard Smith41ae3282012-11-14 00:50:40 +00009358 // If we built a call to a trivial 'operator=' while copying an array,
9359 // bail out. We'll replace the whole shebang with a memcpy.
9360 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9361 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
Craig Topperc3ec1492014-05-26 06:22:03 +00009362 return StmtResult((Stmt*)nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009363
Richard Smith52c0b582012-11-13 00:54:12 +00009364 // Convert to an expression-statement, and clean up any produced
9365 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +00009366 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009367 }
John McCallab8c2732010-03-16 06:11:48 +00009368
Richard Smith52c0b582012-11-13 00:54:12 +00009369 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +00009370 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +00009371 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009372 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +00009373 ExprResult Assignment = S.CreateBuiltinBinOp(
9374 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009375 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009376 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +00009377 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009378 }
Richard Smith52c0b582012-11-13 00:54:12 +00009379
9380 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +00009381 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +00009382
Douglas Gregorb139cd52010-05-01 20:49:11 +00009383 // Construct a loop over the array bounds, e.g.,
9384 //
9385 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9386 //
9387 // that will copy each of the array elements.
9388 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +00009389
Douglas Gregorb139cd52010-05-01 20:49:11 +00009390 // Create the iteration variable.
Craig Topperc3ec1492014-05-26 06:22:03 +00009391 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009392 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009393 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009394 llvm::raw_svector_ostream OS(Str);
9395 OS << "__i" << Depth;
9396 IterationVarName = &S.Context.Idents.get(OS.str());
9397 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00009398 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009399 IterationVarName, SizeType,
9400 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009401 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +00009402
Douglas Gregorb139cd52010-05-01 20:49:11 +00009403 // Initialize the iteration variable to zero.
9404 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009405 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009406
Pavel Labath58934982013-08-30 08:52:28 +00009407 // Creates a reference to the iteration variable.
9408 RefBuilder IterationVarRef(IterationVar, SizeType);
9409 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +00009410
Douglas Gregorb139cd52010-05-01 20:49:11 +00009411 // Create the DeclStmt that holds the iteration variable.
9412 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009413
Douglas Gregorb139cd52010-05-01 20:49:11 +00009414 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +00009415 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9416 MoveCastBuilder FromIndexMove(FromIndexCopy);
9417 const ExprBuilder *FromIndex;
9418 if (Copying)
9419 FromIndex = &FromIndexCopy;
9420 else
9421 FromIndex = &FromIndexMove;
9422
9423 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009424
9425 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +00009426 StmtResult Copy =
9427 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +00009428 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +00009429 Copying, Depth + 1);
9430 // Bail out if copying fails or if we determined that we should use memcpy.
9431 if (Copy.isInvalid() || !Copy.get())
9432 return Copy;
9433
9434 // Create the comparison against the array bound.
9435 llvm::APInt Upper
9436 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9437 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +00009438 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +00009439 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9440 BO_NE, S.Context.BoolTy,
9441 VK_RValue, OK_Ordinary, Loc, false);
9442
9443 // Create the pre-increment of the iteration variable.
9444 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +00009445 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9446 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009447
Douglas Gregorb139cd52010-05-01 20:49:11 +00009448 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00009449 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009450 S.MakeFullExpr(Comparison),
Craig Topperc3ec1492014-05-26 06:22:03 +00009451 nullptr, S.MakeFullDiscardedValueExpr(Increment),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009452 Loc, Copy.get());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009453}
9454
Richard Smith41ae3282012-11-14 00:50:40 +00009455static StmtResult
9456buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009457 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009458 bool CopyingBaseSubobject, bool Copying) {
9459 // Maybe we should use a memcpy?
9460 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9461 T.isTriviallyCopyableType(S.Context))
9462 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9463
9464 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9465 CopyingBaseSubobject,
9466 Copying, 0));
9467
9468 // If we ended up picking a trivial assignment operator for an array of a
9469 // non-trivially-copyable class type, just emit a memcpy.
9470 if (!Result.isInvalid() && !Result.get())
9471 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9472
9473 return Result;
9474}
9475
Richard Smithd3b5c9082012-07-27 04:22:15 +00009476Sema::ImplicitExceptionSpecification
9477Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9478 CXXRecordDecl *ClassDecl = MD->getParent();
9479
9480 ImplicitExceptionSpecification ExceptSpec(*this);
9481 if (ClassDecl->isInvalidDecl())
9482 return ExceptSpec;
9483
9484 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00009485 assert(T->getNumParams() == 1 && "not a copy assignment op");
9486 unsigned ArgQuals =
9487 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009488
Douglas Gregor68e11362010-07-01 17:48:08 +00009489 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +00009490 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +00009491 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00009492
9493 // It is unspecified whether or not an implicit copy assignment operator
9494 // attempts to deduplicate calls to assignment operators of virtual bases are
9495 // made. As such, this exception specification is effectively unspecified.
9496 // Based on a similar decision made for constness in C++0x, we're erring on
9497 // the side of assuming such calls to be made regardless of whether they
9498 // actually happen.
Aaron Ballman574705e2014-03-13 15:41:46 +00009499 for (const auto &Base : ClassDecl->bases()) {
9500 if (Base.isVirtual())
Alexis Hunt491ec602011-06-21 23:42:56 +00009501 continue;
9502
Douglas Gregor330b9cf2010-07-02 21:50:04 +00009503 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009504 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009505 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9506 ArgQuals, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009507 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00009508 }
Alexis Hunt491ec602011-06-21 23:42:56 +00009509
Aaron Ballman445a9392014-03-13 16:15:17 +00009510 for (const auto &Base : ClassDecl->vbases()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00009511 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009512 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009513 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9514 ArgQuals, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009515 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +00009516 }
9517
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009518 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009519 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00009520 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9521 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +00009522 LookupCopyingAssignment(FieldClassDecl,
9523 ArgQuals | FieldType.getCVRQualifiers(),
9524 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009525 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009526 }
Douglas Gregor68e11362010-07-01 17:48:08 +00009527 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009528
Richard Smithd3b5c9082012-07-27 04:22:15 +00009529 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +00009530}
9531
9532CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9533 // Note: The following rules are largely analoguous to the copy
9534 // constructor rules. Note that virtual bases are not taken into account
9535 // for determining the argument type of the operator. Note also that
9536 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +00009537 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +00009538
Richard Smith8bf22e52012-11-29 01:34:07 +00009539 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9540 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009541 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009542
Alexis Hunt119f3652011-05-14 05:23:20 +00009543 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9544 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +00009545 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9546 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +00009547 ArgType = ArgType.withConst();
9548 ArgType = Context.getLValueReferenceType(ArgType);
9549
Richard Smith99005e62013-05-07 03:19:20 +00009550 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9551 CXXCopyAssignment,
9552 Const);
9553
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009554 // An implicitly-declared copy assignment operator is an inline public
9555 // member of its class.
9556 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009557 SourceLocation ClassLoc = ClassDecl->getLocation();
9558 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009559 CXXMethodDecl *CopyAssignment =
9560 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009561 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
9562 /*isInline=*/true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009563 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00009564 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009565 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009566
9567 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009568 FunctionProtoType::ExtProtoInfo EPI =
9569 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009570 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009571
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009572 // Add the parameter to the operator.
9573 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +00009574 ClassLoc, ClassLoc,
9575 /*Id=*/nullptr, ArgType,
9576 /*TInfo=*/nullptr, SC_None,
9577 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +00009578 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +00009579
Richard Smith6b02d462012-12-08 08:32:28 +00009580 AddOverriddenMethods(ClassDecl, CopyAssignment);
9581
9582 CopyAssignment->setTrivial(
9583 ClassDecl->needsOverloadResolutionForCopyAssignment()
9584 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9585 : ClassDecl->hasTrivialCopyAssignment());
9586
Richard Smith852265f2012-03-30 20:53:28 +00009587 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smithb4d2a152013-04-02 19:38:47 +00009588 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +00009589
Richard Smith6b02d462012-12-08 08:32:28 +00009590 // Note that we have added this copy-assignment operator.
9591 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9592
9593 if (Scope *S = getScopeForContext(ClassDecl))
9594 PushOnScopeChains(CopyAssignment, S, false);
9595 ClassDecl->addDecl(CopyAssignment);
9596
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009597 return CopyAssignment;
9598}
9599
Richard Smithd577fbb2013-06-13 03:23:42 +00009600/// Diagnose an implicit copy operation for a class which is odr-used, but
9601/// which is deprecated because the class has a user-declared copy constructor,
9602/// copy assignment operator, or destructor.
9603static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9604 SourceLocation UseLoc) {
9605 assert(CopyOp->isImplicit());
9606
9607 CXXRecordDecl *RD = CopyOp->getParent();
Craig Topperc3ec1492014-05-26 06:22:03 +00009608 CXXMethodDecl *UserDeclaredOperation = nullptr;
Richard Smithd577fbb2013-06-13 03:23:42 +00009609
9610 // In Microsoft mode, assignment operations don't affect constructors and
9611 // vice versa.
9612 if (RD->hasUserDeclaredDestructor()) {
9613 UserDeclaredOperation = RD->getDestructor();
9614 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9615 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009616 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009617 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009618 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009619 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009620 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009621 break;
9622 }
9623 }
9624 assert(UserDeclaredOperation);
9625 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9626 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009627 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009628 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00009629 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009630 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00009631 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009632 break;
9633 }
9634 }
9635 assert(UserDeclaredOperation);
9636 }
9637
9638 if (UserDeclaredOperation) {
9639 S.Diag(UserDeclaredOperation->getLocation(),
9640 diag::warn_deprecated_copy_operation)
9641 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9642 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9643 S.Diag(UseLoc, diag::note_member_synthesized_at)
9644 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9645 : Sema::CXXCopyAssignment)
9646 << RD;
9647 }
9648}
9649
Douglas Gregorb139cd52010-05-01 20:49:11 +00009650void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9651 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00009652 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009653 CopyAssignOperator->isOverloadedOperator() &&
9654 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009655 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9656 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009657 "DefineImplicitCopyAssignment called for wrong function");
9658
9659 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9660
9661 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9662 CopyAssignOperator->setInvalidDecl();
9663 return;
9664 }
Richard Smithd577fbb2013-06-13 03:23:42 +00009665
9666 // C++11 [class.copy]p18:
9667 // The [definition of an implicitly declared copy assignment operator] is
9668 // deprecated if the class has a user-declared copy constructor or a
9669 // user-declared destructor.
9670 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9671 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9672
Eli Friedman276dd182013-09-05 00:02:25 +00009673 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009674
Eli Friedmaneaf34142012-10-18 20:14:08 +00009675 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009676 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009677
9678 // C++0x [class.copy]p30:
9679 // The implicitly-defined or explicitly-defaulted copy assignment operator
9680 // for a non-union class X performs memberwise copy assignment of its
9681 // subobjects. The direct base classes of X are assigned first, in the
9682 // order of their declaration in the base-specifier-list, and then the
9683 // immediate non-static data members of X are assigned, in the order in
9684 // which they were declared in the class definition.
9685
9686 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009687 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009688
9689 // The parameter for the "other" object, which we are copying from.
9690 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9691 Qualifiers OtherQuals = Other->getType().getQualifiers();
9692 QualType OtherRefType = Other->getType();
9693 if (const LValueReferenceType *OtherRef
9694 = OtherRefType->getAs<LValueReferenceType>()) {
9695 OtherRefType = OtherRef->getPointeeType();
9696 OtherQuals = OtherRefType.getQualifiers();
9697 }
9698
9699 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +00009700 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
9701 ? CopyAssignOperator->getLocEnd()
9702 : CopyAssignOperator->getLocation();
9703
Pavel Labath58934982013-08-30 08:52:28 +00009704 // Builds a DeclRefExpr for the "other" object.
9705 RefBuilder OtherRef(Other, OtherRefType);
9706
9707 // Builds the "this" pointer.
9708 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009709
9710 // Assign base classes.
9711 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +00009712 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009713 // Form the assignment:
9714 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +00009715 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009716 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009717 Invalid = true;
9718 continue;
9719 }
9720
John McCallcf142162010-08-07 06:22:56 +00009721 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +00009722 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +00009723
Douglas Gregorb139cd52010-05-01 20:49:11 +00009724 // Construct the "from" expression, which is an implicit cast to the
9725 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009726 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9727 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009728
9729 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009730 DerefBuilder DerefThis(This);
9731 CastBuilder To(DerefThis,
9732 Context.getCVRQualifiedType(
9733 BaseType, CopyAssignOperator->getTypeQualifiers()),
9734 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009735
9736 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +00009737 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +00009738 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009739 /*CopyingBaseSubobject=*/true,
9740 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009741 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009742 Diag(CurrentLocation, diag::note_member_synthesized_at)
9743 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9744 CopyAssignOperator->setInvalidDecl();
9745 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009746 }
9747
9748 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009749 Statements.push_back(Copy.getAs<Expr>());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009750 }
9751
Douglas Gregorb139cd52010-05-01 20:49:11 +00009752 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009753 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009754 if (Field->isUnnamedBitfield())
9755 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009756
9757 if (Field->isInvalidDecl()) {
9758 Invalid = true;
9759 continue;
9760 }
9761
Douglas Gregorb139cd52010-05-01 20:49:11 +00009762 // Check for members of reference type; we can't copy those.
9763 if (Field->getType()->isReferenceType()) {
9764 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9765 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9766 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009767 Diag(CurrentLocation, diag::note_member_synthesized_at)
9768 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009769 Invalid = true;
9770 continue;
9771 }
9772
9773 // Check for members of const-qualified, non-class type.
9774 QualType BaseType = Context.getBaseElementType(Field->getType());
9775 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9776 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9777 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9778 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009779 Diag(CurrentLocation, diag::note_member_synthesized_at)
9780 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009781 Invalid = true;
9782 continue;
9783 }
John McCall1b1a1db2011-06-17 00:18:42 +00009784
9785 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009786 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9787 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009788
9789 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00009790 if (FieldType->isIncompleteArrayType()) {
9791 assert(ClassDecl->hasFlexibleArrayMember() &&
9792 "Incomplete array type is not valid");
9793 continue;
9794 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009795
9796 // Build references to the field in the object we're copying from and to.
9797 CXXScopeSpec SS; // Intentionally empty
9798 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9799 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009800 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009801 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +00009802
9803 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9804
9805 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009806
Douglas Gregorb139cd52010-05-01 20:49:11 +00009807 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +00009808 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +00009809 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009810 /*CopyingBaseSubobject=*/false,
9811 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009812 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009813 Diag(CurrentLocation, diag::note_member_synthesized_at)
9814 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9815 CopyAssignOperator->setInvalidDecl();
9816 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009817 }
9818
9819 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009820 Statements.push_back(Copy.getAs<Stmt>());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009821 }
9822
9823 if (!Invalid) {
9824 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +00009825 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009826
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00009827 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009828 if (Return.isInvalid())
9829 Invalid = true;
9830 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009831 Statements.push_back(Return.getAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00009832
9833 if (Trap.hasErrorOccurred()) {
9834 Diag(CurrentLocation, diag::note_member_synthesized_at)
9835 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9836 Invalid = true;
9837 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009838 }
9839 }
9840
9841 if (Invalid) {
9842 CopyAssignOperator->setInvalidDecl();
9843 return;
9844 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009845
9846 StmtResult Body;
9847 {
9848 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009849 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009850 /*isStmtExpr=*/false);
9851 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9852 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009853 CopyAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00009854
9855 if (ASTMutationListener *L = getASTMutationListener()) {
9856 L->CompletedImplicitDefinition(CopyAssignOperator);
9857 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009858}
9859
Sebastian Redl22653ba2011-08-30 19:58:05 +00009860Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009861Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9862 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009863
Richard Smithd3b5c9082012-07-27 04:22:15 +00009864 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009865 if (ClassDecl->isInvalidDecl())
9866 return ExceptSpec;
9867
9868 // C++0x [except.spec]p14:
9869 // An implicitly declared special member function (Clause 12) shall have an
9870 // exception-specification. [...]
9871
9872 // It is unspecified whether or not an implicit move assignment operator
9873 // attempts to deduplicate calls to assignment operators of virtual bases are
9874 // made. As such, this exception specification is effectively unspecified.
9875 // Based on a similar decision made for constness in C++0x, we're erring on
9876 // the side of assuming such calls to be made regardless of whether they
9877 // actually happen.
9878 // Note that a move constructor is not implicitly declared when there are
9879 // virtual bases, but it can still be user-declared and explicitly defaulted.
Aaron Ballman574705e2014-03-13 15:41:46 +00009880 for (const auto &Base : ClassDecl->bases()) {
9881 if (Base.isVirtual())
Sebastian Redl22653ba2011-08-30 19:58:05 +00009882 continue;
9883
9884 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009885 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009886 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009887 0, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009888 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009889 }
9890
Aaron Ballman445a9392014-03-13 16:15:17 +00009891 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009892 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009893 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009894 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009895 0, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009896 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009897 }
9898
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009899 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009900 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009901 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +00009902 if (CXXMethodDecl *MoveAssign =
9903 LookupMovingAssignment(FieldClassDecl,
9904 FieldType.getCVRQualifiers(),
9905 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009906 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009907 }
9908 }
9909
9910 return ExceptSpec;
9911}
9912
9913CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009914 assert(ClassDecl->needsImplicitMoveAssignment());
9915
Richard Smith8bf22e52012-11-29 01:34:07 +00009916 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9917 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009918 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009919
Sebastian Redl22653ba2011-08-30 19:58:05 +00009920 // Note: The following rules are largely analoguous to the move
9921 // constructor rules.
9922
Sebastian Redl22653ba2011-08-30 19:58:05 +00009923 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9924 QualType RetType = Context.getLValueReferenceType(ArgType);
9925 ArgType = Context.getRValueReferenceType(ArgType);
9926
Richard Smith99005e62013-05-07 03:19:20 +00009927 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9928 CXXMoveAssignment,
9929 false);
9930
Sebastian Redl22653ba2011-08-30 19:58:05 +00009931 // An implicitly-declared move assignment operator is an inline public
9932 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +00009933 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9934 SourceLocation ClassLoc = ClassDecl->getLocation();
9935 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009936 CXXMethodDecl *MoveAssignment =
9937 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009938 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
Richard Smith99005e62013-05-07 03:19:20 +00009939 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009940 MoveAssignment->setAccess(AS_public);
9941 MoveAssignment->setDefaulted();
9942 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009943
Richard Smithd3b5c9082012-07-27 04:22:15 +00009944 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009945 FunctionProtoType::ExtProtoInfo EPI =
9946 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009947 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009948
Sebastian Redl22653ba2011-08-30 19:58:05 +00009949 // Add the parameter to the operator.
9950 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +00009951 ClassLoc, ClassLoc,
9952 /*Id=*/nullptr, ArgType,
9953 /*TInfo=*/nullptr, SC_None,
9954 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +00009955 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009956
Richard Smith6b02d462012-12-08 08:32:28 +00009957 AddOverriddenMethods(ClassDecl, MoveAssignment);
9958
9959 MoveAssignment->setTrivial(
9960 ClassDecl->needsOverloadResolutionForMoveAssignment()
9961 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9962 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009963
Richard Smithd951a1d2012-02-18 02:02:13 +00009964 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +00009965 ClassDecl->setImplicitMoveAssignmentIsDeleted();
9966 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009967 }
9968
Richard Smith6b02d462012-12-08 08:32:28 +00009969 // Note that we have added this copy-assignment operator.
9970 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9971
Sebastian Redl22653ba2011-08-30 19:58:05 +00009972 if (Scope *S = getScopeForContext(ClassDecl))
9973 PushOnScopeChains(MoveAssignment, S, false);
9974 ClassDecl->addDecl(MoveAssignment);
9975
Sebastian Redl22653ba2011-08-30 19:58:05 +00009976 return MoveAssignment;
9977}
9978
Richard Smithb2504bd2013-11-04 04:26:14 +00009979/// Check if we're implicitly defining a move assignment operator for a class
9980/// with virtual bases. Such a move assignment might move-assign the virtual
9981/// base multiple times.
9982static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
9983 SourceLocation CurrentLocation) {
9984 assert(!Class->isDependentContext() && "should not define dependent move");
9985
9986 // Only a virtual base could get implicitly move-assigned multiple times.
9987 // Only a non-trivial move assignment can observe this. We only want to
9988 // diagnose if we implicitly define an assignment operator that assigns
9989 // two base classes, both of which move-assign the same virtual base.
9990 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
9991 Class->getNumBases() < 2)
9992 return;
9993
9994 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
9995 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
9996 VBaseMap VBases;
9997
Aaron Ballman574705e2014-03-13 15:41:46 +00009998 for (auto &BI : Class->bases()) {
9999 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000010000 while (!Worklist.empty()) {
10001 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10002 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10003
10004 // If the base has no non-trivial move assignment operators,
10005 // we don't care about moves from it.
10006 if (!Base->hasNonTrivialMoveAssignment())
10007 continue;
10008
10009 // If there's nothing virtual here, skip it.
10010 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10011 continue;
10012
10013 // If we're not actually going to call a move assignment for this base,
10014 // or the selected move assignment is trivial, skip it.
10015 Sema::SpecialMemberOverloadResult *SMOR =
10016 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10017 /*ConstArg*/false, /*VolatileArg*/false,
10018 /*RValueThis*/true, /*ConstThis*/false,
10019 /*VolatileThis*/false);
10020 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10021 !SMOR->getMethod()->isMoveAssignmentOperator())
10022 continue;
10023
10024 if (BaseSpec->isVirtual()) {
10025 // We're going to move-assign this virtual base, and its move
10026 // assignment operator is not trivial. If this can happen for
10027 // multiple distinct direct bases of Class, diagnose it. (If it
10028 // only happens in one base, we'll diagnose it when synthesizing
10029 // that base class's move assignment operator.)
10030 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +000010031 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +000010032 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +000010033 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010034 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10035 << Class << Base;
10036 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10037 << (Base->getCanonicalDecl() ==
10038 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10039 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +000010040 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +000010041 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +000010042 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10043 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +000010044
10045 // Only diagnose each vbase once.
Craig Topperc3ec1492014-05-26 06:22:03 +000010046 Existing = nullptr;
Richard Smithb2504bd2013-11-04 04:26:14 +000010047 }
10048 } else {
10049 // Only walk over bases that have defaulted move assignment operators.
10050 // We assume that any user-provided move assignment operator handles
10051 // the multiple-moves-of-vbase case itself somehow.
10052 if (!SMOR->getMethod()->isDefaulted())
10053 continue;
10054
10055 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +000010056 for (auto &BI : Base->bases())
10057 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000010058 }
10059 }
10060 }
10061}
10062
Sebastian Redl22653ba2011-08-30 19:58:05 +000010063void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10064 CXXMethodDecl *MoveAssignOperator) {
10065 assert((MoveAssignOperator->isDefaulted() &&
10066 MoveAssignOperator->isOverloadedOperator() &&
10067 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000010068 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10069 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010070 "DefineImplicitMoveAssignment called for wrong function");
10071
10072 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10073
10074 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10075 MoveAssignOperator->setInvalidDecl();
10076 return;
10077 }
10078
Eli Friedman276dd182013-09-05 00:02:25 +000010079 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010080
Eli Friedmaneaf34142012-10-18 20:14:08 +000010081 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010082 DiagnosticErrorTrap Trap(Diags);
10083
10084 // C++0x [class.copy]p28:
10085 // The implicitly-defined or move assignment operator for a non-union class
10086 // X performs memberwise move assignment of its subobjects. The direct base
10087 // classes of X are assigned first, in the order of their declaration in the
10088 // base-specifier-list, and then the immediate non-static data members of X
10089 // are assigned, in the order in which they were declared in the class
10090 // definition.
10091
Richard Smithb2504bd2013-11-04 04:26:14 +000010092 // Issue a warning if our implicit move assignment operator will move
10093 // from a virtual base more than once.
10094 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +000010095
Sebastian Redl22653ba2011-08-30 19:58:05 +000010096 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000010097 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010098
10099 // The parameter for the "other" object, which we are move from.
10100 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10101 QualType OtherRefType = Other->getType()->
10102 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +000010103 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010104 "Bad argument type of defaulted move assignment");
10105
10106 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010107 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10108 ? MoveAssignOperator->getLocEnd()
10109 : MoveAssignOperator->getLocation();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010110
Pavel Labath58934982013-08-30 08:52:28 +000010111 // Builds a reference to the "other" object.
10112 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010113 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +000010114 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010115
Pavel Labath58934982013-08-30 08:52:28 +000010116 // Builds the "this" pointer.
10117 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010118
Sebastian Redl22653ba2011-08-30 19:58:05 +000010119 // Assign base classes.
10120 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000010121 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010122 // C++11 [class.copy]p28:
10123 // It is unspecified whether subobjects representing virtual base classes
10124 // are assigned more than once by the implicitly-defined copy assignment
10125 // operator.
10126 // FIXME: Do not assign to a vbase that will be assigned by some other base
10127 // class. For a move-assignment, this can result in the vbase being moved
10128 // multiple times.
10129
Sebastian Redl22653ba2011-08-30 19:58:05 +000010130 // Form the assignment:
10131 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000010132 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010133 if (!BaseType->isRecordType()) {
10134 Invalid = true;
10135 continue;
10136 }
10137
10138 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000010139 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010140
10141 // Construct the "from" expression, which is an implicit cast to the
10142 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010143 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010144
10145 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000010146 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010147
10148 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010149 CastBuilder To(DerefThis,
10150 Context.getCVRQualifiedType(
10151 BaseType, MoveAssignOperator->getTypeQualifiers()),
10152 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010153
10154 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +000010155 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000010156 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010157 /*CopyingBaseSubobject=*/true,
10158 /*Copying=*/false);
10159 if (Move.isInvalid()) {
10160 Diag(CurrentLocation, diag::note_member_synthesized_at)
10161 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10162 MoveAssignOperator->setInvalidDecl();
10163 return;
10164 }
10165
10166 // Success! Record the move.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010167 Statements.push_back(Move.getAs<Expr>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010168 }
10169
Sebastian Redl22653ba2011-08-30 19:58:05 +000010170 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010171 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +000010172 if (Field->isUnnamedBitfield())
10173 continue;
10174
Eli Friedmanc9817fd2013-06-07 01:48:56 +000010175 if (Field->isInvalidDecl()) {
10176 Invalid = true;
10177 continue;
10178 }
10179
Sebastian Redl22653ba2011-08-30 19:58:05 +000010180 // Check for members of reference type; we can't move those.
10181 if (Field->getType()->isReferenceType()) {
10182 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10183 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10184 Diag(Field->getLocation(), diag::note_declared_at);
10185 Diag(CurrentLocation, diag::note_member_synthesized_at)
10186 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10187 Invalid = true;
10188 continue;
10189 }
10190
10191 // Check for members of const-qualified, non-class type.
10192 QualType BaseType = Context.getBaseElementType(Field->getType());
10193 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10194 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10195 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10196 Diag(Field->getLocation(), diag::note_declared_at);
10197 Diag(CurrentLocation, diag::note_member_synthesized_at)
10198 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10199 Invalid = true;
10200 continue;
10201 }
10202
10203 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000010204 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10205 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010206
10207 QualType FieldType = Field->getType().getNonReferenceType();
10208 if (FieldType->isIncompleteArrayType()) {
10209 assert(ClassDecl->hasFlexibleArrayMember() &&
10210 "Incomplete array type is not valid");
10211 continue;
10212 }
10213
10214 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010215 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10216 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010217 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010218 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000010219 MemberBuilder From(MoveOther, OtherRefType,
10220 /*IsArrow=*/false, MemberLookup);
10221 MemberBuilder To(This, getCurrentThisType(),
10222 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010223
Pavel Labath58934982013-08-30 08:52:28 +000010224 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +000010225 "Member reference with rvalue base must be rvalue except for reference "
10226 "members, which aren't allowed for move assignment.");
10227
Sebastian Redl22653ba2011-08-30 19:58:05 +000010228 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000010229 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010230 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010231 /*CopyingBaseSubobject=*/false,
10232 /*Copying=*/false);
10233 if (Move.isInvalid()) {
10234 Diag(CurrentLocation, diag::note_member_synthesized_at)
10235 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10236 MoveAssignOperator->setInvalidDecl();
10237 return;
10238 }
Richard Smith11d19592012-11-12 23:33:00 +000010239
Sebastian Redl22653ba2011-08-30 19:58:05 +000010240 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010241 Statements.push_back(Move.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010242 }
10243
10244 if (!Invalid) {
10245 // Add a "return *this;"
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010246 ExprResult ThisObj =
10247 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10248
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010249 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010250 if (Return.isInvalid())
10251 Invalid = true;
10252 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010253 Statements.push_back(Return.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010254
10255 if (Trap.hasErrorOccurred()) {
10256 Diag(CurrentLocation, diag::note_member_synthesized_at)
10257 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10258 Invalid = true;
10259 }
10260 }
10261 }
10262
10263 if (Invalid) {
10264 MoveAssignOperator->setInvalidDecl();
10265 return;
10266 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010267
10268 StmtResult Body;
10269 {
10270 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010271 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010272 /*isStmtExpr=*/false);
10273 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10274 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010275 MoveAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010276
10277 if (ASTMutationListener *L = getASTMutationListener()) {
10278 L->CompletedImplicitDefinition(MoveAssignOperator);
10279 }
10280}
10281
Richard Smithd3b5c9082012-07-27 04:22:15 +000010282Sema::ImplicitExceptionSpecification
10283Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10284 CXXRecordDecl *ClassDecl = MD->getParent();
10285
10286 ImplicitExceptionSpecification ExceptSpec(*this);
10287 if (ClassDecl->isInvalidDecl())
10288 return ExceptSpec;
10289
10290 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000010291 assert(T->getNumParams() >= 1 && "not a copy ctor");
10292 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010293
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010294 // C++ [except.spec]p14:
10295 // An implicitly declared special member function (Clause 12) shall have an
10296 // exception-specification. [...]
Aaron Ballman574705e2014-03-13 15:41:46 +000010297 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010298 // Virtual bases are handled below.
Aaron Ballman574705e2014-03-13 15:41:46 +000010299 if (Base.isVirtual())
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010300 continue;
10301
Douglas Gregora6d69502010-07-02 23:41:54 +000010302 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010303 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010304 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010305 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman574705e2014-03-13 15:41:46 +000010306 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010307 }
Aaron Ballman445a9392014-03-13 16:15:17 +000010308 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregora6d69502010-07-02 23:41:54 +000010309 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010310 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010311 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010312 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman445a9392014-03-13 16:15:17 +000010313 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010314 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010315 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010316 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000010317 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10318 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000010319 LookupCopyingConstructor(FieldClassDecl,
10320 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000010321 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010322 }
10323 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010324
Richard Smithd3b5c9082012-07-27 04:22:15 +000010325 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000010326}
10327
10328CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10329 CXXRecordDecl *ClassDecl) {
10330 // C++ [class.copy]p4:
10331 // If the class definition does not explicitly declare a copy
10332 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000010333 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000010334
Richard Smith8bf22e52012-11-29 01:34:07 +000010335 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10336 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010337 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010338
Alexis Hunt913820d2011-05-13 06:10:58 +000010339 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10340 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000010341 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000010342 if (Const)
10343 ArgType = ArgType.withConst();
10344 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000010345
Richard Smithb5800092012-06-10 05:43:50 +000010346 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10347 CXXCopyConstructor,
10348 Const);
10349
Douglas Gregor54be3392010-07-01 17:57:27 +000010350 DeclarationName Name
10351 = Context.DeclarationNames.getCXXConstructorName(
10352 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010353 SourceLocation ClassLoc = ClassDecl->getLocation();
10354 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000010355
10356 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010357 // member of its class.
10358 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010359 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000010360 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010361 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000010362 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000010363 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010364
Richard Smithd3b5c9082012-07-27 04:22:15 +000010365 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010366 FunctionProtoType::ExtProtoInfo EPI =
10367 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010368 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010369 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010370
Douglas Gregor54be3392010-07-01 17:57:27 +000010371 // Add the parameter to the constructor.
10372 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000010373 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010374 /*IdentifierInfo=*/nullptr,
10375 ArgType, /*TInfo=*/nullptr,
10376 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010377 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000010378
Richard Smith6b02d462012-12-08 08:32:28 +000010379 CopyConstructor->setTrivial(
10380 ClassDecl->needsOverloadResolutionForCopyConstructor()
10381 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10382 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000010383
Richard Smith852265f2012-03-30 20:53:28 +000010384 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +000010385 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010386
Richard Smith6b02d462012-12-08 08:32:28 +000010387 // Note that we have declared this constructor.
10388 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10389
10390 if (Scope *S = getScopeForContext(ClassDecl))
10391 PushOnScopeChains(CopyConstructor, S, false);
10392 ClassDecl->addDecl(CopyConstructor);
10393
Douglas Gregor54be3392010-07-01 17:57:27 +000010394 return CopyConstructor;
10395}
10396
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010397void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000010398 CXXConstructorDecl *CopyConstructor) {
10399 assert((CopyConstructor->isDefaulted() &&
10400 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010401 !CopyConstructor->doesThisDeclarationHaveABody() &&
10402 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010403 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010404
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000010405 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010406 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010407
Richard Smithd577fbb2013-06-13 03:23:42 +000010408 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000010409 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000010410 // deprecated if the class has a user-declared copy assignment operator
10411 // or a user-declared destructor.
10412 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10413 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10414
Eli Friedmaneaf34142012-10-18 20:14:08 +000010415 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010416 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010417
David Blaikie3fc2f912013-01-17 05:26:25 +000010418 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010419 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000010420 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000010421 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000010422 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000010423 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010424 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10425 ? CopyConstructor->getLocEnd()
10426 : CopyConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010427 Sema::CompoundScopeRAII CompoundScope(*this);
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010428 CopyConstructor->setBody(
10429 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000010430 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010431
Eli Friedman276dd182013-09-05 00:02:25 +000010432 CopyConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000010433 MarkVTableUsed(CurrentLocation, ClassDecl);
10434
Sebastian Redlab238a72011-04-24 16:28:06 +000010435 if (ASTMutationListener *L = getASTMutationListener()) {
10436 L->CompletedImplicitDefinition(CopyConstructor);
10437 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010438}
10439
Sebastian Redl22653ba2011-08-30 19:58:05 +000010440Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010441Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10442 CXXRecordDecl *ClassDecl = MD->getParent();
10443
Sebastian Redl22653ba2011-08-30 19:58:05 +000010444 // C++ [except.spec]p14:
10445 // An implicitly declared special member function (Clause 12) shall have an
10446 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000010447 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010448 if (ClassDecl->isInvalidDecl())
10449 return ExceptSpec;
10450
10451 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000010452 for (const auto &B : ClassDecl->bases()) {
10453 if (B.isVirtual()) // Handled below.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010454 continue;
10455
Aaron Ballman574705e2014-03-13 15:41:46 +000010456 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010457 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010458 CXXConstructorDecl *Constructor =
10459 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010460 // If this is a deleted function, add it anyway. This might be conformant
10461 // with the standard. This might not. I'm not sure. It might not matter.
10462 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +000010463 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010464 }
10465 }
10466
10467 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000010468 for (const auto &B : ClassDecl->vbases()) {
10469 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010470 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010471 CXXConstructorDecl *Constructor =
10472 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010473 // If this is a deleted function, add it anyway. This might be conformant
10474 // with the standard. This might not. I'm not sure. It might not matter.
10475 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000010476 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010477 }
10478 }
10479
10480 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010481 for (const auto *F : ClassDecl->fields()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010482 QualType FieldType = Context.getBaseElementType(F->getType());
10483 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10484 CXXConstructorDecl *Constructor =
10485 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010486 // If this is a deleted function, add it anyway. This might be conformant
10487 // with the standard. This might not. I'm not sure. It might not matter.
10488 // In particular, the problem is that this function never gets called. It
10489 // might just be ill-formed because this function attempts to refer to
10490 // a deleted function here.
10491 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010492 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010493 }
10494 }
10495
10496 return ExceptSpec;
10497}
10498
10499CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10500 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010501 assert(ClassDecl->needsImplicitMoveConstructor());
10502
Richard Smith8bf22e52012-11-29 01:34:07 +000010503 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10504 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010505 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010506
Sebastian Redl22653ba2011-08-30 19:58:05 +000010507 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10508 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010509
Richard Smithb5800092012-06-10 05:43:50 +000010510 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10511 CXXMoveConstructor,
10512 false);
10513
Sebastian Redl22653ba2011-08-30 19:58:05 +000010514 DeclarationName Name
10515 = Context.DeclarationNames.getCXXConstructorName(
10516 Context.getCanonicalType(ClassType));
10517 SourceLocation ClassLoc = ClassDecl->getLocation();
10518 DeclarationNameInfo NameInfo(Name, ClassLoc);
10519
Richard Smith99005e62013-05-07 03:19:20 +000010520 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000010521 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010522 // member of its class.
10523 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010524 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000010525 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010526 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010527 MoveConstructor->setAccess(AS_public);
10528 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010529
Richard Smithd3b5c9082012-07-27 04:22:15 +000010530 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010531 FunctionProtoType::ExtProtoInfo EPI =
10532 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010533 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010534 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010535
Sebastian Redl22653ba2011-08-30 19:58:05 +000010536 // Add the parameter to the constructor.
10537 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10538 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010539 /*IdentifierInfo=*/nullptr,
10540 ArgType, /*TInfo=*/nullptr,
10541 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010542 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010543
Richard Smith6b02d462012-12-08 08:32:28 +000010544 MoveConstructor->setTrivial(
10545 ClassDecl->needsOverloadResolutionForMoveConstructor()
10546 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10547 : ClassDecl->hasTrivialMoveConstructor());
10548
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000010549 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010550 ClassDecl->setImplicitMoveConstructorIsDeleted();
10551 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010552 }
10553
10554 // Note that we have declared this constructor.
10555 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10556
10557 if (Scope *S = getScopeForContext(ClassDecl))
10558 PushOnScopeChains(MoveConstructor, S, false);
10559 ClassDecl->addDecl(MoveConstructor);
10560
10561 return MoveConstructor;
10562}
10563
10564void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10565 CXXConstructorDecl *MoveConstructor) {
10566 assert((MoveConstructor->isDefaulted() &&
10567 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010568 !MoveConstructor->doesThisDeclarationHaveABody() &&
10569 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010570 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10571
10572 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10573 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10574
Eli Friedmaneaf34142012-10-18 20:14:08 +000010575 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010576 DiagnosticErrorTrap Trap(Diags);
10577
David Blaikie3fc2f912013-01-17 05:26:25 +000010578 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000010579 Trap.hasErrorOccurred()) {
10580 Diag(CurrentLocation, diag::note_member_synthesized_at)
10581 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10582 MoveConstructor->setInvalidDecl();
10583 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010584 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
10585 ? MoveConstructor->getLocEnd()
10586 : MoveConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010587 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010588 MoveConstructor->setBody(ActOnCompoundStmt(
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010589 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010590 }
10591
Eli Friedman276dd182013-09-05 00:02:25 +000010592 MoveConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000010593 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010594
10595 if (ASTMutationListener *L = getASTMutationListener()) {
10596 L->CompletedImplicitDefinition(MoveConstructor);
10597 }
10598}
10599
Douglas Gregor74f7d502012-02-15 19:33:52 +000010600bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000010601 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000010602}
Douglas Gregord3b672c2012-02-16 01:06:16 +000010603
10604void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000010605 SourceLocation CurrentLocation,
10606 CXXConversionDecl *Conv) {
10607 CXXRecordDecl *Lambda = Conv->getParent();
10608 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10609 // If we are defining a specialization of a conversion to function-ptr
10610 // cache the deduced template arguments for this specialization
10611 // so that we can use them to retrieve the corresponding call-operator
10612 // and static-invoker.
Craig Topperc3ec1492014-05-26 06:22:03 +000010613 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
10614
Faisal Vali571df122013-09-29 08:45:24 +000010615 // Retrieve the corresponding call-operator specialization.
10616 if (Lambda->isGenericLambda()) {
10617 assert(Conv->isFunctionTemplateSpecialization());
10618 FunctionTemplateDecl *CallOpTemplate =
10619 CallOp->getDescribedFunctionTemplate();
10620 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
Craig Topperc3ec1492014-05-26 06:22:03 +000010621 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000010622 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000010623 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000010624 InsertPos);
10625 assert(CallOpSpec &&
10626 "Conversion operator must have a corresponding call operator");
10627 CallOp = cast<CXXMethodDecl>(CallOpSpec);
10628 }
10629 // Mark the call operator referenced (and add to pending instantiations
10630 // if necessary).
10631 // For both the conversion and static-invoker template specializations
10632 // we construct their body's in this function, so no need to add them
10633 // to the PendingInstantiations.
10634 MarkFunctionReferenced(CurrentLocation, CallOp);
10635
Eli Friedmaneaf34142012-10-18 20:14:08 +000010636 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010637 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000010638
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010639 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000010640 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10641 // ... and get the corresponding specialization for a generic lambda.
10642 if (Lambda->isGenericLambda()) {
10643 assert(DeducedTemplateArgs &&
10644 "Must have deduced template arguments from Conversion Operator");
10645 FunctionTemplateDecl *InvokeTemplate =
10646 Invoker->getDescribedFunctionTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +000010647 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000010648 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000010649 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000010650 InsertPos);
10651 assert(InvokeSpec &&
10652 "Must have a corresponding static invoker specialization");
10653 Invoker = cast<CXXMethodDecl>(InvokeSpec);
10654 }
10655 // Construct the body of the conversion function { return __invoke; }.
10656 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010657 VK_LValue, Conv->getLocation()).get();
Faisal Vali571df122013-09-29 08:45:24 +000010658 assert(FunctionRef && "Can't refer to __invoke function?");
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010659 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
Faisal Vali571df122013-09-29 08:45:24 +000010660 Conv->setBody(new (Context) CompoundStmt(Context, Return,
10661 Conv->getLocation(),
10662 Conv->getLocation()));
10663
10664 Conv->markUsed(Context);
10665 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010666
Faisal Vali571df122013-09-29 08:45:24 +000010667 // Fill in the __invoke function with a dummy implementation. IR generation
10668 // will fill in the actual details.
10669 Invoker->markUsed(Context);
10670 Invoker->setReferenced();
10671 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10672
Douglas Gregord3b672c2012-02-16 01:06:16 +000010673 if (ASTMutationListener *L = getASTMutationListener()) {
10674 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000010675 L->CompletedImplicitDefinition(Invoker);
10676 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000010677}
10678
Faisal Vali571df122013-09-29 08:45:24 +000010679
10680
Douglas Gregord3b672c2012-02-16 01:06:16 +000010681void Sema::DefineImplicitLambdaToBlockPointerConversion(
10682 SourceLocation CurrentLocation,
10683 CXXConversionDecl *Conv)
10684{
Faisal Vali850da1a2013-09-29 17:08:32 +000010685 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000010686
Eli Friedman276dd182013-09-05 00:02:25 +000010687 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010688
Eli Friedmaneaf34142012-10-18 20:14:08 +000010689 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010690 DiagnosticErrorTrap Trap(Diags);
10691
Douglas Gregored90df32012-02-22 05:02:47 +000010692 // Copy-initialize the lambda object as needed to capture it.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010693 Expr *This = ActOnCXXThis(CurrentLocation).get();
10694 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010695
Eli Friedman98b01ed2012-03-01 04:01:32 +000010696 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10697 Conv->getLocation(),
10698 Conv, DerefThis);
10699
10700 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10701 // behavior. Note that only the general conversion function does this
10702 // (since it's unusable otherwise); in the case where we inline the
10703 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010704 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000010705 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10706 CK_CopyAndAutoreleaseBlockObject,
Craig Topperc3ec1492014-05-26 06:22:03 +000010707 BuildBlock.get(), nullptr, VK_RValue);
Eli Friedman98b01ed2012-03-01 04:01:32 +000010708
10709 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000010710 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000010711 Conv->setInvalidDecl();
10712 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000010713 }
Douglas Gregored90df32012-02-22 05:02:47 +000010714
Douglas Gregored90df32012-02-22 05:02:47 +000010715 // Create the return statement that returns the block from the conversion
10716 // function.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010717 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000010718 if (Return.isInvalid()) {
10719 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10720 Conv->setInvalidDecl();
10721 return;
10722 }
10723
10724 // Set the body of the conversion function.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010725 Stmt *ReturnS = Return.get();
Nico Webera2a0eb92012-12-29 20:03:39 +000010726 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000010727 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000010728 Conv->getLocation()));
10729
Douglas Gregored90df32012-02-22 05:02:47 +000010730 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010731 if (ASTMutationListener *L = getASTMutationListener()) {
10732 L->CompletedImplicitDefinition(Conv);
10733 }
10734}
10735
Douglas Gregord2f70072012-03-10 06:53:13 +000010736/// \brief Determine whether the given list arguments contains exactly one
10737/// "real" (non-default) argument.
10738static bool hasOneRealArgument(MultiExprArg Args) {
10739 switch (Args.size()) {
10740 case 0:
10741 return false;
10742
10743 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010744 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000010745 return false;
10746
10747 // fall through
10748 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010749 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000010750 }
10751
10752 return false;
10753}
10754
John McCalldadc5752010-08-24 06:29:42 +000010755ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010756Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +000010757 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010758 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010759 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010760 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000010761 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010762 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010763 unsigned ConstructKind,
10764 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000010765 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000010766
Douglas Gregor45cf7e32010-04-02 18:24:57 +000010767 // C++0x [class.copy]p34:
10768 // When certain criteria are met, an implementation is allowed to
10769 // omit the copy/move construction of a class object, even if the
10770 // copy/move constructor and/or destructor for the object have
10771 // side effects. [...]
10772 // - when a temporary class object that has not been bound to a
10773 // reference (12.2) would be copied/moved to a class object
10774 // with the same cv-unqualified type, the copy/move operation
10775 // can be omitted by constructing the temporary object
10776 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +000010777 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregord2f70072012-03-10 06:53:13 +000010778 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010779 Expr *SubExpr = ExprArgs[0];
John McCall7a626f62010-09-15 10:14:12 +000010780 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +000010781 }
Mike Stump11289f42009-09-09 15:08:12 +000010782
10783 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010784 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithf8adcdc2014-07-17 05:12:35 +000010785 IsListInitialization,
10786 IsStdInitListInitialization, RequiresZeroInit,
Richard Smithd59b8322012-12-19 01:39:02 +000010787 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000010788}
10789
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010790/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10791/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +000010792ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010793Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10794 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010795 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010796 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010797 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000010798 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010799 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010800 unsigned ConstructKind,
10801 SourceRange ParenRange) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010802 MarkFunctionReferenced(ConstructLoc, Constructor);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010803 return CXXConstructExpr::Create(
10804 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
Richard Smithf8adcdc2014-07-17 05:12:35 +000010805 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
10806 RequiresZeroInit,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010807 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10808 ParenRange);
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010809}
10810
John McCall03c48482010-02-02 09:10:11 +000010811void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000010812 if (VD->isInvalidDecl()) return;
10813
John McCall03c48482010-02-02 09:10:11 +000010814 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000010815 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000010816 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000010817 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000010818
Chandler Carruth86d17d32011-03-27 21:26:48 +000010819 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010820 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000010821 CheckDestructorAccess(VD->getLocation(), Destructor,
10822 PDiag(diag::err_access_dtor_var)
10823 << VD->getDeclName()
10824 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000010825 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000010826
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000010827 if (Destructor->isTrivial()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000010828 if (!VD->hasGlobalStorage()) return;
10829
10830 // Emit warning for non-trivial dtor in global scope (a real global,
10831 // class-static, function-static).
10832 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10833
10834 // TODO: this should be re-enabled for static locals by !CXAAtExit
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000010835 if (!VD->isStaticLocal())
Chandler Carruth86d17d32011-03-27 21:26:48 +000010836 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010837}
10838
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010839/// \brief Given a constructor and the set of arguments provided for the
10840/// constructor, convert the arguments and add any required default arguments
10841/// to form a proper call to this constructor.
10842///
10843/// \returns true if an error occurred, false otherwise.
10844bool
10845Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10846 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000010847 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000010848 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010849 bool AllowExplicit,
10850 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010851 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10852 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010853 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010854
10855 const FunctionProtoType *Proto
10856 = Constructor->getType()->getAs<FunctionProtoType>();
10857 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010858 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000010859
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010860 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010861 if (NumArgs < NumParams)
10862 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010863 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010864 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010865
10866 VariadicCallType CallType =
10867 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010868 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010869 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010870 Proto, 0,
10871 llvm::makeArrayRef(Args, NumArgs),
10872 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010873 CallType, AllowExplicit,
10874 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000010875 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000010876
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010877 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010878
Dmitri Gribenko765396f2013-01-13 20:46:02 +000010879 CheckConstructorCall(Constructor,
10880 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10881 AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000010882 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010883
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010884 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000010885}
10886
Anders Carlssone363c8e2009-12-12 00:32:00 +000010887static inline bool
10888CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10889 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000010890 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000010891 if (isa<NamespaceDecl>(DC)) {
10892 return SemaRef.Diag(FnDecl->getLocation(),
10893 diag::err_operator_new_delete_declared_in_namespace)
10894 << FnDecl->getDeclName();
10895 }
10896
10897 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000010898 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010899 return SemaRef.Diag(FnDecl->getLocation(),
10900 diag::err_operator_new_delete_declared_static)
10901 << FnDecl->getDeclName();
10902 }
10903
Anders Carlsson60659a82009-12-12 02:43:16 +000010904 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000010905}
10906
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010907static inline bool
10908CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10909 CanQualType ExpectedResultType,
10910 CanQualType ExpectedFirstParamType,
10911 unsigned DependentParamTypeDiag,
10912 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000010913 QualType ResultType =
10914 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010915
10916 // Check that the result type is not dependent.
10917 if (ResultType->isDependentType())
10918 return SemaRef.Diag(FnDecl->getLocation(),
10919 diag::err_operator_new_delete_dependent_result_type)
10920 << FnDecl->getDeclName() << ExpectedResultType;
10921
10922 // Check that the result type is what we expect.
10923 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10924 return SemaRef.Diag(FnDecl->getLocation(),
10925 diag::err_operator_new_delete_invalid_result_type)
10926 << FnDecl->getDeclName() << ExpectedResultType;
10927
10928 // A function template must have at least 2 parameters.
10929 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10930 return SemaRef.Diag(FnDecl->getLocation(),
10931 diag::err_operator_new_delete_template_too_few_parameters)
10932 << FnDecl->getDeclName();
10933
10934 // The function decl must have at least 1 parameter.
10935 if (FnDecl->getNumParams() == 0)
10936 return SemaRef.Diag(FnDecl->getLocation(),
10937 diag::err_operator_new_delete_too_few_parameters)
10938 << FnDecl->getDeclName();
10939
Sylvestre Ledru830885c2012-07-23 08:59:39 +000010940 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010941 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10942 if (FirstParamType->isDependentType())
10943 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10944 << FnDecl->getDeclName() << ExpectedFirstParamType;
10945
10946 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000010947 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010948 ExpectedFirstParamType)
10949 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10950 << FnDecl->getDeclName() << ExpectedFirstParamType;
10951
10952 return false;
10953}
10954
Anders Carlsson12308f42009-12-11 23:23:22 +000010955static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010956CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010957 // C++ [basic.stc.dynamic.allocation]p1:
10958 // A program is ill-formed if an allocation function is declared in a
10959 // namespace scope other than global scope or declared static in global
10960 // scope.
10961 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10962 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010963
10964 CanQualType SizeTy =
10965 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10966
10967 // C++ [basic.stc.dynamic.allocation]p1:
10968 // The return type shall be void*. The first parameter shall have type
10969 // std::size_t.
10970 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10971 SizeTy,
10972 diag::err_operator_new_dependent_param_type,
10973 diag::err_operator_new_param_type))
10974 return true;
10975
10976 // C++ [basic.stc.dynamic.allocation]p1:
10977 // The first parameter shall not have an associated default argument.
10978 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000010979 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010980 diag::err_operator_new_default_arg)
10981 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10982
10983 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000010984}
10985
10986static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000010987CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000010988 // C++ [basic.stc.dynamic.deallocation]p1:
10989 // A program is ill-formed if deallocation functions are declared in a
10990 // namespace scope other than global scope or declared static in global
10991 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000010992 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10993 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010994
10995 // C++ [basic.stc.dynamic.deallocation]p2:
10996 // Each deallocation function shall return void and its first parameter
10997 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010998 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10999 SemaRef.Context.VoidPtrTy,
11000 diag::err_operator_delete_dependent_param_type,
11001 diag::err_operator_delete_param_type))
11002 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000011003
Anders Carlsson12308f42009-12-11 23:23:22 +000011004 return false;
11005}
11006
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011007/// CheckOverloadedOperatorDeclaration - Check whether the declaration
11008/// of this overloaded operator is well-formed. If so, returns false;
11009/// otherwise, emits appropriate diagnostics and returns true.
11010bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000011011 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011012 "Expected an overloaded operator declaration");
11013
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011014 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11015
Mike Stump11289f42009-09-09 15:08:12 +000011016 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011017 // The allocation and deallocation functions, operator new,
11018 // operator new[], operator delete and operator delete[], are
11019 // described completely in 3.7.3. The attributes and restrictions
11020 // found in the rest of this subclause do not apply to them unless
11021 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000011022 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000011023 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000011024
Anders Carlsson22f443f2009-12-12 00:26:23 +000011025 if (Op == OO_New || Op == OO_Array_New)
11026 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011027
11028 // C++ [over.oper]p6:
11029 // An operator function shall either be a non-static member
11030 // function or be a non-member function and have at least one
11031 // parameter whose type is a class, a reference to a class, an
11032 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000011033 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11034 if (MethodDecl->isStatic())
11035 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011036 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011037 } else {
11038 bool ClassOrEnumParam = false;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011039 for (auto Param : FnDecl->params()) {
11040 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000011041 if (ParamType->isDependentType() || ParamType->isRecordType() ||
11042 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011043 ClassOrEnumParam = true;
11044 break;
11045 }
11046 }
11047
Douglas Gregord69246b2008-11-17 16:14:12 +000011048 if (!ClassOrEnumParam)
11049 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011050 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011051 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011052 }
11053
11054 // C++ [over.oper]p8:
11055 // An operator function cannot have default arguments (8.3.6),
11056 // except where explicitly stated below.
11057 //
Mike Stump11289f42009-09-09 15:08:12 +000011058 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011059 // (C++ [over.call]p1).
11060 if (Op != OO_Call) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011061 for (auto Param : FnDecl->params()) {
11062 if (Param->hasDefaultArg())
11063 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000011064 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011065 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011066 }
11067 }
11068
Douglas Gregor6cf08062008-11-10 13:38:07 +000011069 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11070 { false, false, false }
11071#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11072 , { Unary, Binary, MemberOnly }
11073#include "clang/Basic/OperatorKinds.def"
11074 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011075
Douglas Gregor6cf08062008-11-10 13:38:07 +000011076 bool CanBeUnaryOperator = OperatorUses[Op][0];
11077 bool CanBeBinaryOperator = OperatorUses[Op][1];
11078 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011079
11080 // C++ [over.oper]p8:
11081 // [...] Operator functions cannot have more or fewer parameters
11082 // than the number required for the corresponding operator, as
11083 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000011084 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000011085 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011086 if (Op != OO_Call &&
11087 ((NumParams == 1 && !CanBeUnaryOperator) ||
11088 (NumParams == 2 && !CanBeBinaryOperator) ||
11089 (NumParams < 1) || (NumParams > 2))) {
11090 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011091 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000011092 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011093 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000011094 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011095 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011096 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000011097 assert(CanBeBinaryOperator &&
11098 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011099 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011100 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011101
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011102 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011103 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011104 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000011105
Douglas Gregord69246b2008-11-17 16:14:12 +000011106 // Overloaded operators other than operator() cannot be variadic.
11107 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000011108 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000011109 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011110 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011111 }
11112
11113 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000011114 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11115 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011116 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011117 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011118 }
11119
11120 // C++ [over.inc]p1:
11121 // The user-defined function called operator++ implements the
11122 // prefix and postfix ++ operator. If this function is a member
11123 // function with no parameters, or a non-member function with one
11124 // parameter of class or enumeration type, it defines the prefix
11125 // increment operator ++ for objects of that type. If the function
11126 // is a member function with one parameter (which shall be of type
11127 // int) or a non-member function with two parameters (the second
11128 // of which shall be of type int), it defines the postfix
11129 // increment operator ++ for objects of that type.
11130 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11131 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000011132 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011133
Richard Smith538b52a2014-01-30 22:24:05 +000011134 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11135 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000011136 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000011137 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000011138 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011139 }
11140
Douglas Gregord69246b2008-11-17 16:14:12 +000011141 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011142}
Chris Lattner3b024a32008-12-17 07:09:26 +000011143
Alexis Huntc88db062010-01-13 09:01:02 +000011144/// CheckLiteralOperatorDeclaration - Check whether the declaration
11145/// of this literal operator function is well-formed. If so, returns
11146/// false; otherwise, emits appropriate diagnostics and returns true.
11147bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000011148 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000011149 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11150 << FnDecl->getDeclName();
11151 return true;
11152 }
11153
Richard Smith72eebee2012-03-04 09:41:16 +000011154 if (FnDecl->isExternC()) {
11155 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11156 return true;
11157 }
11158
Alexis Huntc88db062010-01-13 09:01:02 +000011159 bool Valid = false;
11160
Richard Smithbcc22fc2012-03-09 08:00:36 +000011161 // This might be the definition of a literal operator template.
11162 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11163 // This might be a specialization of a literal operator template.
11164 if (!TpDecl)
11165 TpDecl = FnDecl->getPrimaryTemplate();
11166
Richard Smithb8b41d32013-10-07 19:57:58 +000011167 // template <char...> type operator "" name() and
11168 // template <class T, T...> type operator "" name() are the only valid
11169 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000011170 if (TpDecl) {
Richard Smith72eebee2012-03-04 09:41:16 +000011171 if (FnDecl->param_size() == 0) {
Richard Smithb8b41d32013-10-07 19:57:58 +000011172 // Must have one or two template parameters
Alexis Hunt7dd26172010-04-07 23:11:06 +000011173 TemplateParameterList *Params = TpDecl->getTemplateParameters();
11174 if (Params->size() == 1) {
11175 NonTypeTemplateParmDecl *PmDecl =
Richard Smithed943022012-08-03 21:14:57 +000011176 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +000011177
Alexis Hunt7dd26172010-04-07 23:11:06 +000011178 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +000011179 if (PmDecl && PmDecl->isTemplateParameterPack() &&
11180 Context.hasSameType(PmDecl->getType(), Context.CharTy))
11181 Valid = true;
Richard Smithb8b41d32013-10-07 19:57:58 +000011182 } else if (Params->size() == 2) {
11183 TemplateTypeParmDecl *PmType =
11184 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11185 NonTypeTemplateParmDecl *PmArgs =
11186 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11187
11188 // The second template parameter must be a parameter pack with the
11189 // first template parameter as its type.
11190 if (PmType && PmArgs &&
11191 !PmType->isTemplateParameterPack() &&
11192 PmArgs->isTemplateParameterPack()) {
11193 const TemplateTypeParmType *TArgs =
11194 PmArgs->getType()->getAs<TemplateTypeParmType>();
11195 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11196 TArgs->getIndex() == PmType->getIndex()) {
11197 Valid = true;
11198 if (ActiveTemplateInstantiations.empty())
11199 Diag(FnDecl->getLocation(),
11200 diag::ext_string_literal_operator_template);
11201 }
11202 }
Alexis Hunt7dd26172010-04-07 23:11:06 +000011203 }
11204 }
Richard Smith72eebee2012-03-04 09:41:16 +000011205 } else if (FnDecl->param_size()) {
Alexis Huntc88db062010-01-13 09:01:02 +000011206 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +000011207 FunctionDecl::param_iterator Param = FnDecl->param_begin();
11208
Richard Smith72eebee2012-03-04 09:41:16 +000011209 QualType T = (*Param)->getType().getUnqualifiedType();
Alexis Huntc88db062010-01-13 09:01:02 +000011210
Alexis Hunt079a6f72010-04-07 22:57:35 +000011211 // unsigned long long int, long double, and any character type are allowed
11212 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +000011213 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11214 Context.hasSameType(T, Context.LongDoubleTy) ||
11215 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011216 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011217 Context.hasSameType(T, Context.Char16Ty) ||
11218 Context.hasSameType(T, Context.Char32Ty)) {
11219 if (++Param == FnDecl->param_end())
11220 Valid = true;
11221 goto FinishedParams;
11222 }
11223
Alexis Hunt079a6f72010-04-07 22:57:35 +000011224 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +000011225 const PointerType *PT = T->getAs<PointerType>();
11226 if (!PT)
11227 goto FinishedParams;
11228 T = PT->getPointeeType();
Richard Smith72eebee2012-03-04 09:41:16 +000011229 if (!T.isConstQualified() || T.isVolatileQualified())
Alexis Huntc88db062010-01-13 09:01:02 +000011230 goto FinishedParams;
11231 T = T.getUnqualifiedType();
11232
11233 // Move on to the second parameter;
11234 ++Param;
11235
11236 // If there is no second parameter, the first must be a const char *
11237 if (Param == FnDecl->param_end()) {
11238 if (Context.hasSameType(T, Context.CharTy))
11239 Valid = true;
11240 goto FinishedParams;
11241 }
11242
11243 // const char *, const wchar_t*, const char16_t*, and const char32_t*
11244 // are allowed as the first parameter to a two-parameter function
11245 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011246 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011247 Context.hasSameType(T, Context.Char16Ty) ||
11248 Context.hasSameType(T, Context.Char32Ty)))
11249 goto FinishedParams;
11250
11251 // The second and final parameter must be an std::size_t
11252 T = (*Param)->getType().getUnqualifiedType();
11253 if (Context.hasSameType(T, Context.getSizeType()) &&
11254 ++Param == FnDecl->param_end())
11255 Valid = true;
11256 }
11257
11258 // FIXME: This diagnostic is absolutely terrible.
11259FinishedParams:
11260 if (!Valid) {
11261 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11262 << FnDecl->getDeclName();
11263 return true;
11264 }
11265
Richard Smith768cecc2012-03-09 08:16:22 +000011266 // A parameter-declaration-clause containing a default argument is not
11267 // equivalent to any of the permitted forms.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011268 for (auto Param : FnDecl->params()) {
11269 if (Param->hasDefaultArg()) {
11270 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000011271 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011272 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000011273 break;
11274 }
11275 }
11276
Richard Smith0df56f42012-03-08 02:39:21 +000011277 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000011278 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11279 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000011280 // C++11 [usrlit.suffix]p1:
11281 // Literal suffix identifiers that do not start with an underscore
11282 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000011283 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11284 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000011285 }
Richard Smith0df56f42012-03-08 02:39:21 +000011286
Alexis Huntc88db062010-01-13 09:01:02 +000011287 return false;
11288}
11289
Douglas Gregor07665a62009-01-05 19:45:36 +000011290/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11291/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000011292/// the '{'. ExternLoc is the location of the 'extern', Lang is the
11293/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000011294/// the '{' brace. Otherwise, this linkage specification does not
11295/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000011296Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000011297 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000011298 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011299 StringLiteral *Lit = cast<StringLiteral>(LangStr);
11300 if (!Lit->isAscii()) {
11301 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11302 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011303 return nullptr;
Richard Smith4ee696d2014-02-17 23:25:27 +000011304 }
11305
11306 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000011307 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000011308 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000011309 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000011310 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000011311 Language = LinkageSpecDecl::lang_cxx;
11312 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000011313 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11314 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011315 return nullptr;
Chris Lattner438e5012008-12-17 07:13:27 +000011316 }
Mike Stump11289f42009-09-09 15:08:12 +000011317
Chris Lattner438e5012008-12-17 07:13:27 +000011318 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000011319
Richard Smith4ee696d2014-02-17 23:25:27 +000011320 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11321 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000011322 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011323 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000011324 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000011325 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000011326}
11327
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000011328/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000011329/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11330/// valid, it's the position of the closing '}' brace in a linkage
11331/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000011332Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011333 Decl *LinkageSpec,
11334 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011335 if (RBraceLoc.isValid()) {
11336 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11337 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011338 }
Richard Smith4ee696d2014-02-17 23:25:27 +000011339 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000011340 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000011341}
11342
Michael Han84324352013-02-22 17:15:32 +000011343Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11344 AttributeList *AttrList,
11345 SourceLocation SemiLoc) {
11346 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11347 // Attribute declarations appertain to empty declaration so we handle
11348 // them here.
11349 if (AttrList)
11350 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000011351
Michael Han84324352013-02-22 17:15:32 +000011352 CurContext->addDecl(ED);
11353 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000011354}
11355
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011356/// \brief Perform semantic analysis for the variable declaration that
11357/// occurs within a C++ catch clause, returning the newly-created
11358/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011359VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000011360 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011361 SourceLocation StartLoc,
11362 SourceLocation Loc,
11363 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011364 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011365 QualType ExDeclType = TInfo->getType();
11366
Sebastian Redl54c04d42008-12-22 19:15:10 +000011367 // Arrays and functions decay.
11368 if (ExDeclType->isArrayType())
11369 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11370 else if (ExDeclType->isFunctionType())
11371 ExDeclType = Context.getPointerType(ExDeclType);
11372
11373 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11374 // The exception-declaration shall not denote a pointer or reference to an
11375 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000011376 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000011377 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011378 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000011379 Invalid = true;
11380 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011381
Sebastian Redl54c04d42008-12-22 19:15:10 +000011382 QualType BaseType = ExDeclType;
11383 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000011384 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011385 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011386 BaseType = Ptr->getPointeeType();
11387 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011388 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000011389 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000011390 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011391 BaseType = Ref->getPointeeType();
11392 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011393 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011394 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000011395 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011396 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000011397 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011398
Mike Stump11289f42009-09-09 15:08:12 +000011399 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011400 RequireNonAbstractType(Loc, ExDeclType,
11401 diag::err_abstract_type_in_decl,
11402 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000011403 Invalid = true;
11404
John McCall2ca705e2010-07-24 00:37:23 +000011405 // Only the non-fragile NeXT runtime currently supports C++ catches
11406 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011407 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000011408 QualType T = ExDeclType;
11409 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11410 T = RT->getPointeeType();
11411
11412 if (T->isObjCObjectType()) {
11413 Diag(Loc, diag::err_objc_object_catch);
11414 Invalid = true;
11415 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000011416 // FIXME: should this be a test for macosx-fragile specifically?
11417 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000011418 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000011419 }
11420 }
11421
Abramo Bagnaradff19302011-03-08 08:55:46 +000011422 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000011423 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000011424 ExDecl->setExceptionVariable(true);
11425
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011426 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011427 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011428 Invalid = true;
11429
Douglas Gregor750734c2011-07-06 18:14:43 +000011430 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000011431 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000011432 // Insulate this from anything else we might currently be parsing.
11433 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11434
Douglas Gregor6de584c2010-03-05 23:38:39 +000011435 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000011436 // The object declared in an exception-declaration or, if the
11437 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000011438 // copy-initialized (8.5) from the exception object. [...]
11439 // The object is destroyed when the handler exits, after the destruction
11440 // of any automatic objects initialized within the handler.
11441 //
Nick Lewycky0f292892013-09-22 10:06:57 +000011442 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000011443 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +000011444 QualType initType = ExDeclType;
11445
11446 InitializedEntity entity =
11447 InitializedEntity::InitializeVariable(ExDecl);
11448 InitializationKind initKind =
11449 InitializationKind::CreateCopy(Loc, SourceLocation());
11450
11451 Expr *opaqueValue =
11452 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000011453 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11454 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000011455 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000011456 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000011457 else {
11458 // If the constructor used was non-trivial, set this as the
11459 // "initializer".
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011460 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000011461 if (!construct->getConstructor()->isTrivial()) {
11462 Expr *init = MaybeCreateExprWithCleanups(construct);
11463 ExDecl->setInit(init);
11464 }
11465
11466 // And make sure it's destructable.
11467 FinalizeVarWithDestructor(ExDecl, recordType);
11468 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000011469 }
11470 }
11471
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011472 if (Invalid)
11473 ExDecl->setInvalidDecl();
11474
11475 return ExDecl;
11476}
11477
11478/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11479/// handler.
John McCall48871652010-08-21 09:40:31 +000011480Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000011481 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000011482 bool Invalid = D.isInvalidType();
11483
11484 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000011485 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11486 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000011487 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11488 D.getIdentifierLoc());
11489 Invalid = true;
11490 }
11491
Sebastian Redl54c04d42008-12-22 19:15:10 +000011492 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011493 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000011494 LookupOrdinaryName,
11495 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011496 // The scope should be freshly made just for us. There is just no way
Aaron Ballman9ef622e2014-06-02 13:10:07 +000011497 // it contains any previous declaration, except for function parameters in
11498 // a function-try-block's catch statement.
John McCall48871652010-08-21 09:40:31 +000011499 assert(!S->isDeclScope(PrevDecl));
Aaron Ballman9ef622e2014-06-02 13:10:07 +000011500 if (isDeclInScope(PrevDecl, CurContext, S)) {
11501 Diag(D.getIdentifierLoc(), diag::err_redefinition)
11502 << D.getIdentifier();
11503 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11504 Invalid = true;
11505 } else if (PrevDecl->isTemplateParameter())
Sebastian Redl54c04d42008-12-22 19:15:10 +000011506 // Maybe we will complain about the shadowed template parameter.
11507 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011508 }
11509
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011510 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011511 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11512 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011513 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011514 }
11515
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011516 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011517 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011518 D.getIdentifierLoc(),
11519 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011520 if (Invalid)
11521 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000011522
Sebastian Redl54c04d42008-12-22 19:15:10 +000011523 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011524 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011525 PushOnScopeChains(ExDecl, S);
11526 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011527 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011528
Douglas Gregor758a8692009-06-17 21:51:59 +000011529 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000011530 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011531}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011532
Abramo Bagnaraea947882011-03-08 16:41:52 +000011533Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000011534 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000011535 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000011536 SourceLocation RParenLoc) {
Richard Smith085a64f2014-06-20 19:57:12 +000011537 StringLiteral *AssertMessage =
11538 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011539
Richard Smithded9c2e2012-07-11 22:37:56 +000011540 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
Craig Topperc3ec1492014-05-26 06:22:03 +000011541 return nullptr;
Richard Smithded9c2e2012-07-11 22:37:56 +000011542
11543 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11544 AssertMessage, RParenLoc, false);
11545}
11546
11547Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11548 Expr *AssertExpr,
11549 StringLiteral *AssertMessage,
11550 SourceLocation RParenLoc,
11551 bool Failed) {
Richard Smith085a64f2014-06-20 19:57:12 +000011552 assert(AssertExpr != nullptr && "Expected non-null condition");
Richard Smithded9c2e2012-07-11 22:37:56 +000011553 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11554 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000011555 // In a static_assert-declaration, the constant-expression shall be a
11556 // constant expression that can be contextually converted to bool.
11557 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11558 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011559 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000011560
Richard Smith902ca212011-12-14 23:32:26 +000011561 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000011562 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000011563 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000011564 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011565 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011566
Richard Smithded9c2e2012-07-11 22:37:56 +000011567 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011568 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000011569 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith085a64f2014-06-20 19:57:12 +000011570 if (AssertMessage)
11571 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000011572 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith085a64f2014-06-20 19:57:12 +000011573 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000011574 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000011575 }
Anders Carlsson54b26982009-03-14 00:33:21 +000011576 }
Mike Stump11289f42009-09-09 15:08:12 +000011577
Abramo Bagnaraea947882011-03-08 16:41:52 +000011578 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000011579 AssertExpr, AssertMessage, RParenLoc,
11580 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000011581
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011582 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000011583 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011584}
Sebastian Redlf769df52009-03-24 22:27:57 +000011585
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011586/// \brief Perform semantic analysis of the given friend type declaration.
11587///
11588/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000011589FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000011590 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011591 TypeSourceInfo *TSInfo) {
11592 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11593
11594 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000011595 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011596
Richard Smithc8239732011-10-18 21:39:00 +000011597 // C++03 [class.friend]p2:
11598 // An elaborated-type-specifier shall be used in a friend declaration
11599 // for a class.*
11600 //
11601 // * The class-key of the elaborated-type-specifier is required.
11602 if (!ActiveTemplateInstantiations.empty()) {
11603 // Do not complain about the form of friend template types during
11604 // template instantiation; we will already have complained when the
11605 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000011606 } else {
11607 if (!T->isElaboratedTypeSpecifier()) {
11608 // If we evaluated the type to a record type, suggest putting
11609 // a tag in front.
11610 if (const RecordType *RT = T->getAs<RecordType>()) {
11611 RecordDecl *RD = RT->getDecl();
Alp Tokera030cd02014-05-05 12:38:48 +000011612
11613 SmallString<16> InsertionText(" ");
11614 InsertionText += RD->getKindName();
11615
Nick Lewycky36722d22013-02-06 05:59:33 +000011616 Diag(TypeRange.getBegin(),
11617 getLangOpts().CPlusPlus11 ?
11618 diag::warn_cxx98_compat_unelaborated_friend_type :
11619 diag::ext_unelaborated_friend_type)
11620 << (unsigned) RD->getTagKind()
11621 << T
11622 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11623 InsertionText);
11624 } else {
11625 Diag(FriendLoc,
11626 getLangOpts().CPlusPlus11 ?
11627 diag::warn_cxx98_compat_nonclass_type_friend :
11628 diag::ext_nonclass_type_friend)
11629 << T
11630 << TypeRange;
11631 }
11632 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000011633 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011634 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000011635 diag::warn_cxx98_compat_enum_friend :
11636 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011637 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000011638 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011639 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011640
Nick Lewycky36722d22013-02-06 05:59:33 +000011641 // C++11 [class.friend]p3:
11642 // A friend declaration that does not declare a function shall have one
11643 // of the following forms:
11644 // friend elaborated-type-specifier ;
11645 // friend simple-type-specifier ;
11646 // friend typename-specifier ;
11647 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11648 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11649 }
Richard Smitha31a89a2012-09-20 01:31:00 +000011650
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011651 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000011652 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011653 // the friend declaration is ignored.
Nikola Smiljanic3a01af02014-05-23 12:48:27 +000011654 return FriendDecl::Create(Context, CurContext,
11655 TSInfo->getTypeLoc().getLocStart(), TSInfo,
11656 FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011657}
11658
John McCallace48cd2010-10-19 01:40:49 +000011659/// Handle a friend tag declaration where the scope specifier was
11660/// templated.
11661Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11662 unsigned TagSpec, SourceLocation TagLoc,
11663 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011664 IdentifierInfo *Name,
11665 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000011666 AttributeList *Attr,
11667 MultiTemplateParamsArg TempParamLists) {
11668 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11669
11670 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000011671 bool Invalid = false;
11672
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011673 if (TemplateParameterList *TemplateParams =
11674 MatchTemplateParametersToScopeSpecifier(
Craig Topperc3ec1492014-05-26 06:22:03 +000011675 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011676 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000011677 if (TemplateParams->size() > 0) {
11678 // This is a declaration of a class template.
11679 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +000011680 return nullptr;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000011681
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000011682 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
11683 NameLoc, Attr, TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000011684 /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000011685 FriendLoc, TempParamLists.size() - 1,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011686 TempParamLists.data()).get();
John McCallace48cd2010-10-19 01:40:49 +000011687 } else {
11688 // The "template<>" header is extraneous.
11689 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11690 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11691 isExplicitSpecialization = true;
11692 }
11693 }
11694
Craig Topperc3ec1492014-05-26 06:22:03 +000011695 if (Invalid) return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000011696
John McCallace48cd2010-10-19 01:40:49 +000011697 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000011698 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011699 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000011700 isAllExplicitSpecializations = false;
11701 break;
11702 }
11703 }
11704
11705 // FIXME: don't ignore attributes.
11706
11707 // If it's explicit specializations all the way down, just forget
11708 // about the template header and build an appropriate non-templated
11709 // friend. TODO: for source fidelity, remember the headers.
11710 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011711 if (SS.isEmpty()) {
11712 bool Owned = false;
11713 bool IsDependent = false;
11714 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000011715 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011716 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000011717 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000011718 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011719 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000011720 /*UnderlyingType=*/TypeResult(),
11721 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011722 }
Richard Smith649c7b062014-01-08 00:56:48 +000011723
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011724 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000011725 ElaboratedTypeKeyword Keyword
11726 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011727 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000011728 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011729 if (T.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +000011730 return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000011731
11732 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11733 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000011734 DependentNameTypeLoc TL =
11735 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011736 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011737 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000011738 TL.setNameLoc(NameLoc);
11739 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000011740 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011741 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000011742 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000011743 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011744 }
11745
11746 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011747 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011748 Friend->setAccess(AS_public);
11749 CurContext->addDecl(Friend);
11750 return Friend;
11751 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011752
11753 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11754
11755
John McCallace48cd2010-10-19 01:40:49 +000011756
11757 // Handle the case of a templated-scope friend class. e.g.
11758 // template <class T> class A<T>::B;
11759 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000011760 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
11761 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000011762 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11763 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11764 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000011765 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011766 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011767 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000011768 TL.setNameLoc(NameLoc);
11769
11770 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011771 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011772 Friend->setAccess(AS_public);
11773 Friend->setUnsupportedFriend(true);
11774 CurContext->addDecl(Friend);
11775 return Friend;
11776}
11777
11778
John McCall11083da2009-09-16 22:47:08 +000011779/// Handle a friend type declaration. This works in tandem with
11780/// ActOnTag.
11781///
11782/// Notes on friend class templates:
11783///
11784/// We generally treat friend class declarations as if they were
11785/// declaring a class. So, for example, the elaborated type specifier
11786/// in a friend declaration is required to obey the restrictions of a
11787/// class-head (i.e. no typedefs in the scope chain), template
11788/// parameters are required to match up with simple template-ids, &c.
11789/// However, unlike when declaring a template specialization, it's
11790/// okay to refer to a template specialization without an empty
11791/// template parameter declaration, e.g.
11792/// friend class A<T>::B<unsigned>;
11793/// We permit this as a special case; if there are any template
11794/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000011795/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000011796Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000011797 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011798 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000011799
11800 assert(DS.isFriendSpecified());
11801 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11802
John McCall11083da2009-09-16 22:47:08 +000011803 // Try to convert the decl specifier to a type. This works for
11804 // friend templates because ActOnTag never produces a ClassTemplateDecl
11805 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000011806 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000011807 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11808 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000011809 if (TheDeclarator.isInvalidType())
Craig Topperc3ec1492014-05-26 06:22:03 +000011810 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000011811
Douglas Gregor6c110f32010-12-16 01:14:37 +000011812 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000011813 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000011814
John McCall11083da2009-09-16 22:47:08 +000011815 // This is definitely an error in C++98. It's probably meant to
11816 // be forbidden in C++0x, too, but the specification is just
11817 // poorly written.
11818 //
11819 // The problem is with declarations like the following:
11820 // template <T> friend A<T>::foo;
11821 // where deciding whether a class C is a friend or not now hinges
11822 // on whether there exists an instantiation of A that causes
11823 // 'foo' to equal C. There are restrictions on class-heads
11824 // (which we declare (by fiat) elaborated friend declarations to
11825 // be) that makes this tractable.
11826 //
11827 // FIXME: handle "template <> friend class A<T>;", which
11828 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000011829 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000011830 Diag(Loc, diag::err_tagless_friend_type_template)
11831 << DS.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011832 return nullptr;
John McCall11083da2009-09-16 22:47:08 +000011833 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011834
John McCallaa74a0c2009-08-28 07:59:38 +000011835 // C++98 [class.friend]p1: A friend of a class is a function
11836 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000011837 // This is fixed in DR77, which just barely didn't make the C++03
11838 // deadline. It's also a very silly restriction that seriously
11839 // affects inner classes and which nobody else seems to implement;
11840 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000011841 //
11842 // But note that we could warn about it: it's always useless to
11843 // friend one of your own members (it's not, however, worthless to
11844 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000011845
John McCall11083da2009-09-16 22:47:08 +000011846 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011847 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000011848 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011849 NumTempParamLists,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011850 TempParams.data(),
John McCall15ad0962010-03-25 18:04:51 +000011851 TSI,
John McCall11083da2009-09-16 22:47:08 +000011852 DS.getFriendSpecLoc());
11853 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000011854 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011855
11856 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +000011857 return nullptr;
11858
John McCall11083da2009-09-16 22:47:08 +000011859 D->setAccess(AS_public);
11860 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000011861
John McCall48871652010-08-21 09:40:31 +000011862 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000011863}
11864
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000011865NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11866 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000011867 const DeclSpec &DS = D.getDeclSpec();
11868
11869 assert(DS.isFriendSpecified());
11870 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11871
11872 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000011873 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000011874
11875 // C++ [class.friend]p1
11876 // A friend of a class is a function or class....
11877 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000011878 // It *doesn't* see through dependent types, which is correct
11879 // according to [temp.arg.type]p3:
11880 // If a declaration acquires a function type through a
11881 // type dependent on a template-parameter and this causes
11882 // a declaration that does not use the syntactic form of a
11883 // function declarator to have a function type, the program
11884 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011885 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000011886 Diag(Loc, diag::err_unexpected_friend);
11887
11888 // It might be worthwhile to try to recover by creating an
11889 // appropriate declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000011890 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000011891 }
11892
11893 // C++ [namespace.memdef]p3
11894 // - If a friend declaration in a non-local class first declares a
11895 // class or function, the friend class or function is a member
11896 // of the innermost enclosing namespace.
11897 // - The name of the friend is not found by simple name lookup
11898 // until a matching declaration is provided in that namespace
11899 // scope (either before or after the class declaration granting
11900 // friendship).
11901 // - If a friend function is called, its name may be found by the
11902 // name lookup that considers functions from namespaces and
11903 // classes associated with the types of the function arguments.
11904 // - When looking for a prior declaration of a class or a function
11905 // declared as a friend, scopes outside the innermost enclosing
11906 // namespace scope are not considered.
11907
John McCallde3fd222010-10-12 23:13:28 +000011908 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011909 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11910 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000011911 assert(Name);
11912
Douglas Gregor6c110f32010-12-16 01:14:37 +000011913 // Check for unexpanded parameter packs.
11914 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11915 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11916 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000011917 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000011918
John McCall07e91c02009-08-06 02:15:43 +000011919 // The context we found the declaration in, or in which we should
11920 // create the declaration.
11921 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000011922 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011923 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000011924 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000011925
Richard Smith114394f2013-08-09 04:35:01 +000011926 // There are five cases here.
11927 // - There's no scope specifier and we're in a local class. Only look
11928 // for functions declared in the immediately-enclosing block scope.
11929 // We recover from invalid scope qualifiers as if they just weren't there.
Craig Topperc3ec1492014-05-26 06:22:03 +000011930 FunctionDecl *FunctionContainingLocalClass = nullptr;
Richard Smith114394f2013-08-09 04:35:01 +000011931 if ((SS.isInvalid() || !SS.isSet()) &&
11932 (FunctionContainingLocalClass =
11933 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11934 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000011935 // If a friend declaration appears in a local class and the name
11936 // specified is an unqualified name, a prior declaration is
11937 // looked up without considering scopes that are outside the
11938 // innermost enclosing non-class scope. For a friend function
11939 // declaration, if there is no prior declaration, the program is
11940 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000011941
11942 // Find the innermost enclosing non-class scope. This is the block
11943 // scope containing the local class definition (or for a nested class,
11944 // the outer local class).
11945 DCScope = S->getFnParent();
11946
11947 // Look up the function name in the scope.
11948 Previous.clear(LookupLocalFriendName);
11949 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11950
11951 if (!Previous.empty()) {
11952 // All possible previous declarations must have the same context:
11953 // either they were declared at block scope or they are members of
11954 // one of the enclosing local classes.
11955 DC = Previous.getRepresentativeDecl()->getDeclContext();
11956 } else {
11957 // This is ill-formed, but provide the context that we would have
11958 // declared the function in, if we were permitted to, for error recovery.
11959 DC = FunctionContainingLocalClass;
11960 }
Richard Smith541b38b2013-09-20 01:15:31 +000011961 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000011962
11963 // C++ [class.friend]p6:
11964 // A function can be defined in a friend declaration of a class if and
11965 // only if the class is a non-local class (9.8), the function name is
11966 // unqualified, and the function has namespace scope.
11967 if (D.isFunctionDefinition()) {
11968 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11969 }
11970
11971 // - There's no scope specifier, in which case we just go to the
11972 // appropriate scope and look for a function or function template
11973 // there as appropriate.
11974 } else if (SS.isInvalid() || !SS.isSet()) {
11975 // C++11 [namespace.memdef]p3:
11976 // If the name in a friend declaration is neither qualified nor
11977 // a template-id and the declaration is a function or an
11978 // elaborated-type-specifier, the lookup to determine whether
11979 // the entity has been previously declared shall not consider
11980 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000011981 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000011982
John McCallf7cfb222010-10-13 05:45:15 +000011983 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000011984 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000011985
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011986 // Skip class contexts. If someone can cite chapter and verse
11987 // for this behavior, that would be nice --- it's what GCC and
11988 // EDG do, and it seems like a reasonable intent, but the spec
11989 // really only says that checks for unqualified existing
11990 // declarations should stop at the nearest enclosing namespace,
11991 // not that they should only consider the nearest enclosing
11992 // namespace.
11993 while (DC->isRecord())
11994 DC = DC->getParent();
11995
11996 DeclContext *LookupDC = DC;
11997 while (LookupDC->isTransparentContext())
11998 LookupDC = LookupDC->getParent();
11999
12000 while (true) {
12001 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000012002
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012003 if (!Previous.empty()) {
12004 DC = LookupDC;
12005 break;
John McCallf4776592010-10-14 22:22:28 +000012006 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012007
12008 if (isTemplateId) {
12009 if (isa<TranslationUnitDecl>(LookupDC)) break;
12010 } else {
12011 if (LookupDC->isFileContext()) break;
12012 }
12013 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000012014 }
12015
John McCallccbc0322010-10-13 06:22:15 +000012016 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000012017
John McCallde3fd222010-10-12 23:13:28 +000012018 // - There's a non-dependent scope specifier, in which case we
12019 // compute it and do a previous lookup there for a function
12020 // or function template.
12021 } else if (!SS.getScopeRep()->isDependent()) {
12022 DC = computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +000012023 if (!DC) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012024
Craig Topperc3ec1492014-05-26 06:22:03 +000012025 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012026
12027 LookupQualifiedName(Previous, DC);
12028
12029 // Ignore things found implicitly in the wrong scope.
12030 // TODO: better diagnostics for this case. Suggesting the right
12031 // qualified scope would be nice...
12032 LookupResult::Filter F = Previous.makeFilter();
12033 while (F.hasNext()) {
12034 NamedDecl *D = F.next();
12035 if (!DC->InEnclosingNamespaceSetOf(
12036 D->getDeclContext()->getRedeclContext()))
12037 F.erase();
12038 }
12039 F.done();
12040
12041 if (Previous.empty()) {
12042 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012043 Diag(Loc, diag::err_qualified_friend_not_found)
12044 << Name << TInfo->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +000012045 return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012046 }
12047
12048 // C++ [class.friend]p1: A friend of a class is a function or
12049 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000012050 if (DC->Equals(CurContext))
12051 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012052 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000012053 diag::warn_cxx98_compat_friend_is_member :
12054 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000012055
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012056 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012057 // C++ [class.friend]p6:
12058 // A function can be defined in a friend declaration of a class if and
12059 // only if the class is a non-local class (9.8), the function name is
12060 // unqualified, and the function has namespace scope.
12061 SemaDiagnosticBuilder DB
12062 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12063
12064 DB << SS.getScopeRep();
12065 if (DC->isFileContext())
12066 DB << FixItHint::CreateRemoval(SS.getRange());
12067 SS.clear();
12068 }
John McCallde3fd222010-10-12 23:13:28 +000012069
12070 // - There's a scope specifier that does not match any template
12071 // parameter lists, in which case we use some arbitrary context,
12072 // create a method or method template, and wait for instantiation.
12073 // - There's a scope specifier that does match some template
12074 // parameter lists, which we don't handle right now.
12075 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012076 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012077 // C++ [class.friend]p6:
12078 // A function can be defined in a friend declaration of a class if and
12079 // only if the class is a non-local class (9.8), the function name is
12080 // unqualified, and the function has namespace scope.
12081 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12082 << SS.getScopeRep();
12083 }
12084
John McCallde3fd222010-10-12 23:13:28 +000012085 DC = CurContext;
12086 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000012087 }
Douglas Gregor16e65612011-10-10 01:11:59 +000012088
John McCallf7cfb222010-10-13 05:45:15 +000012089 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000012090 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000012091 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
12092 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
12093 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000012094 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000012095 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
12096 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
Craig Topperc3ec1492014-05-26 06:22:03 +000012097 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012098 }
John McCall07e91c02009-08-06 02:15:43 +000012099 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012100
Douglas Gregordd847ba2011-11-03 16:37:14 +000012101 // FIXME: This is an egregious hack to cope with cases where the scope stack
12102 // does not contain the declaration context, i.e., in an out-of-line
12103 // definition of a class.
12104 Scope FakeDCScope(S, Scope::DeclScope, Diags);
12105 if (!DCScope) {
12106 FakeDCScope.setEntity(DC);
12107 DCScope = &FakeDCScope;
12108 }
Richard Smith114394f2013-08-09 04:35:01 +000012109
Francois Pichet00c7e6c2011-08-14 03:52:19 +000012110 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012111 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012112 TemplateParams, AddToScope);
Craig Topperc3ec1492014-05-26 06:22:03 +000012113 if (!ND) return nullptr;
John McCall759e32b2009-08-31 22:39:49 +000012114
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012115 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000012116
Richard Smith114394f2013-08-09 04:35:01 +000012117 // If we performed typo correction, we might have added a scope specifier
12118 // and changed the decl context.
12119 DC = ND->getDeclContext();
12120
John McCall759e32b2009-08-31 22:39:49 +000012121 // Add the function declaration to the appropriate lookup tables,
12122 // adjusting the redeclarations list as necessary. We don't
12123 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000012124 //
John McCall759e32b2009-08-31 22:39:49 +000012125 // Also update the scope-based lookup if the target context's
12126 // lookup context is in lexical scope.
12127 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000012128 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000012129 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000012130 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012131 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000012132 }
John McCallaa74a0c2009-08-28 07:59:38 +000012133
12134 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012135 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000012136 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000012137 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000012138 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000012139
John McCalla0a96892012-08-10 03:15:35 +000012140 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000012141 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000012142 } else {
12143 if (DC->isRecord()) CheckFriendAccess(ND);
12144
John McCall2c2eb122010-10-16 06:59:13 +000012145 FunctionDecl *FD;
12146 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12147 FD = FTD->getTemplatedDecl();
12148 else
12149 FD = cast<FunctionDecl>(ND);
12150
David Majnemer502b0ed2013-06-25 23:09:30 +000012151 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12152 // default argument expression, that declaration shall be a definition
12153 // and shall be the only declaration of the function or function
12154 // template in the translation unit.
12155 if (functionDeclHasDefaultArgument(FD)) {
12156 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12157 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12158 Diag(OldFD->getLocation(), diag::note_previous_declaration);
12159 } else if (!D.isFunctionDefinition())
12160 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12161 }
12162
John McCall2c2eb122010-10-16 06:59:13 +000012163 // Mark templated-scope function declarations as unsupported.
12164 if (FD->getNumTemplateParameterLists())
12165 FrD->setUnsupportedFriend(true);
12166 }
John McCallde3fd222010-10-12 23:13:28 +000012167
John McCall48871652010-08-21 09:40:31 +000012168 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000012169}
12170
John McCall48871652010-08-21 09:40:31 +000012171void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12172 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000012173
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012174 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000012175 if (!Fn) {
12176 Diag(DelLoc, diag::err_deleted_non_function);
12177 return;
12178 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012179
Douglas Gregorec9fd132012-01-14 16:38:05 +000012180 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000012181 // Don't consider the implicit declaration we generate for explicit
12182 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000012183 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12184 Prev->getPreviousDecl()) &&
12185 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000012186 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000012187 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12188 Prev->isImplicit() ? diag::note_previous_implicit_declaration
12189 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000012190 }
Sebastian Redlf769df52009-03-24 22:27:57 +000012191 // If the declaration wasn't the first, we delete the function anyway for
12192 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000012193 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000012194 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012195
Nico Rieck9de0a572014-05-29 16:51:19 +000012196 // dllimport/dllexport cannot be deleted.
12197 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12198 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12199 Fn->setInvalidDecl();
12200 }
12201
Richard Smithb4d2a152013-04-02 19:38:47 +000012202 if (Fn->isDeleted())
12203 return;
12204
12205 // See if we're deleting a function which is already known to override a
12206 // non-deleted virtual function.
12207 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12208 bool IssuedDiagnostic = false;
12209 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12210 E = MD->end_overridden_methods();
12211 I != E; ++I) {
12212 if (!(*MD->begin_overridden_methods())->isDeleted()) {
12213 if (!IssuedDiagnostic) {
12214 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12215 IssuedDiagnostic = true;
12216 }
12217 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12218 }
12219 }
12220 }
12221
Richard Smithb63b6ee2014-01-22 01:43:19 +000012222 // C++11 [basic.start.main]p3:
12223 // A program that defines main as deleted [...] is ill-formed.
12224 if (Fn->isMain())
12225 Diag(DelLoc, diag::err_deleted_main);
12226
Alexis Hunt4a8ea102011-05-06 20:44:56 +000012227 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000012228}
Sebastian Redl4c018662009-04-27 21:33:24 +000012229
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012230void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012231 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012232
12233 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000012234 if (MD->getParent()->isDependentType()) {
12235 MD->setDefaulted();
12236 MD->setExplicitlyDefaulted();
12237 return;
12238 }
12239
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012240 CXXSpecialMember Member = getSpecialMember(MD);
12241 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000012242 if (!MD->isInvalidDecl())
12243 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012244 return;
12245 }
12246
12247 MD->setDefaulted();
12248 MD->setExplicitlyDefaulted();
12249
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012250 // If this definition appears within the record, do the checking when
12251 // the record is complete.
12252 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000012253 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012254 // Find the uninstantiated declaration that actually had the '= default'
12255 // on it.
Richard Smith802c4b72012-08-23 06:16:52 +000012256 Pattern->isDefined(Primary);
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012257
Richard Smith3901dfe2013-03-27 00:22:47 +000012258 // If the method was defaulted on its first declaration, we will have
12259 // already performed the checking in CheckCompletedCXXClass. Such a
12260 // declaration doesn't trigger an implicit definition.
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012261 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012262 return;
12263
Richard Smithd3b5c9082012-07-27 04:22:15 +000012264 CheckExplicitlyDefaultedSpecialMember(MD);
12265
Richard Smithbd305122012-12-11 01:14:52 +000012266 // The exception specification is needed because we are defining the
12267 // function.
12268 ResolveExceptionSpec(DefaultLoc,
12269 MD->getType()->castAs<FunctionProtoType>());
12270
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012271 if (MD->isInvalidDecl())
12272 return;
12273
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012274 switch (Member) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012275 case CXXDefaultConstructor:
12276 DefineImplicitDefaultConstructor(DefaultLoc,
12277 cast<CXXConstructorDecl>(MD));
Alexis Hunt913820d2011-05-13 06:10:58 +000012278 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012279 case CXXCopyConstructor:
12280 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012281 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012282 case CXXCopyAssignment:
12283 DefineImplicitCopyAssignment(DefaultLoc, MD);
Alexis Huntc9a55732011-05-14 05:23:28 +000012284 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012285 case CXXDestructor:
12286 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Alexis Huntf91729462011-05-12 22:46:25 +000012287 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012288 case CXXMoveConstructor:
12289 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt119c10e2011-05-25 23:16:36 +000012290 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012291 case CXXMoveAssignment:
12292 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012293 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000012294 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000012295 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012296 }
12297 } else {
12298 Diag(DefaultLoc, diag::err_default_special_members);
12299 }
12300}
12301
Sebastian Redl4c018662009-04-27 21:33:24 +000012302static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000012303 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000012304 Stmt *SubStmt = *CI;
12305 if (!SubStmt)
12306 continue;
12307 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012308 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000012309 diag::err_return_in_constructor_handler);
12310 if (!isa<Expr>(SubStmt))
12311 SearchForReturnInStmt(Self, SubStmt);
12312 }
12313}
12314
12315void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12316 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12317 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12318 SearchForReturnInStmt(*this, Handler);
12319 }
12320}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012321
David Blaikie68f71a32013-01-18 23:03:15 +000012322bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000012323 const CXXMethodDecl *Old) {
12324 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12325 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12326
12327 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12328
12329 // If the calling conventions match, everything is fine
12330 if (NewCC == OldCC)
12331 return false;
12332
Hans Wennborg2545efe2013-12-11 17:42:11 +000012333 // If the calling conventions mismatch because the new function is static,
12334 // suppress the calling convention mismatch error; the error about static
12335 // function override (err_static_overrides_virtual from
12336 // Sema::CheckFunctionDeclaration) is more clear.
12337 if (New->getStorageClass() == SC_Static)
12338 return false;
12339
Reid Kleckner78af0702013-08-27 23:08:25 +000012340 Diag(New->getLocation(),
12341 diag::err_conflicting_overriding_cc_attributes)
12342 << New->getDeclName() << New->getType() << Old->getType();
12343 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12344 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000012345}
12346
Mike Stump11289f42009-09-09 15:08:12 +000012347bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012348 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000012349 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12350 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012351
Chandler Carruth284bb2e2010-02-15 11:53:20 +000012352 if (Context.hasSameType(NewTy, OldTy) ||
12353 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012354 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012355
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012356 // Check if the return types are covariant
12357 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000012358
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012359 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012360 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12361 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012362 NewClassTy = NewPT->getPointeeType();
12363 OldClassTy = OldPT->getPointeeType();
12364 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012365 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12366 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12367 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12368 NewClassTy = NewRT->getPointeeType();
12369 OldClassTy = OldRT->getPointeeType();
12370 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012371 }
12372 }
Mike Stump11289f42009-09-09 15:08:12 +000012373
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012374 // The return types aren't either both pointers or references to a class type.
12375 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000012376 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012377 diag::err_different_return_type_for_overriding_virtual_function)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012378 << New->getDeclName() << NewTy << OldTy
12379 << New->getReturnTypeSourceRange();
12380 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12381 << Old->getReturnTypeSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000012382
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012383 return true;
12384 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012385
Anders Carlssone60365b2009-12-31 18:34:24 +000012386 // C++ [class.virtual]p6:
12387 // If the return type of D::f differs from the return type of B::f, the
12388 // class type in the return type of D::f shall be complete at the point of
12389 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012390 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12391 if (!RT->isBeingDefined() &&
12392 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012393 diag::err_covariant_return_incomplete,
12394 New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000012395 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012396 }
Anders Carlssone60365b2009-12-31 18:34:24 +000012397
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000012398 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012399 // Check if the new class derives from the old class.
12400 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
Alp Tokerd0787eb2014-07-02 01:47:15 +000012401 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
12402 << New->getDeclName() << NewTy << OldTy
12403 << New->getReturnTypeSourceRange();
12404 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12405 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012406 return true;
12407 }
Mike Stump11289f42009-09-09 15:08:12 +000012408
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012409 // Check if we the conversion from derived to base is valid.
Alp Tokerd0787eb2014-07-02 01:47:15 +000012410 if (CheckDerivedToBaseConversion(
12411 NewClassTy, OldClassTy,
12412 diag::err_covariant_return_inaccessible_base,
12413 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12414 New->getLocation(), New->getReturnTypeSourceRange(),
12415 New->getDeclName(), nullptr)) {
John McCallc1465822011-02-14 07:13:47 +000012416 // FIXME: this note won't trigger for delayed access control
12417 // diagnostics, and it's impossible to get an undelayed error
12418 // here from access control during the original parse because
12419 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Alp Tokerd0787eb2014-07-02 01:47:15 +000012420 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12421 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012422 return true;
12423 }
12424 }
Mike Stump11289f42009-09-09 15:08:12 +000012425
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012426 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012427 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012428 Diag(New->getLocation(),
12429 diag::err_covariant_return_type_different_qualifications)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012430 << New->getDeclName() << NewTy << OldTy
12431 << New->getReturnTypeSourceRange();
12432 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12433 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012434 return true;
12435 };
Mike Stump11289f42009-09-09 15:08:12 +000012436
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012437
12438 // The new class type must have the same or less qualifiers as the old type.
12439 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12440 Diag(New->getLocation(),
12441 diag::err_covariant_return_type_class_type_more_qualified)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012442 << New->getDeclName() << NewTy << OldTy
12443 << New->getReturnTypeSourceRange();
12444 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12445 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012446 return true;
12447 };
Mike Stump11289f42009-09-09 15:08:12 +000012448
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012449 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012450}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012451
Douglas Gregor21920e372009-12-01 17:24:26 +000012452/// \brief Mark the given method pure.
12453///
12454/// \param Method the method to be marked pure.
12455///
12456/// \param InitRange the source range that covers the "0" initializer.
12457bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012458 SourceLocation EndLoc = InitRange.getEnd();
12459 if (EndLoc.isValid())
12460 Method->setRangeEnd(EndLoc);
12461
Douglas Gregor21920e372009-12-01 17:24:26 +000012462 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12463 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000012464 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012465 }
Douglas Gregor21920e372009-12-01 17:24:26 +000012466
12467 if (!Method->isInvalidDecl())
12468 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12469 << Method->getDeclName() << InitRange;
12470 return true;
12471}
12472
Douglas Gregor926410d2012-02-21 02:22:07 +000012473/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012474static bool isStaticDataMember(const Decl *D) {
12475 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12476 return Var->isStaticDataMember();
12477
12478 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000012479}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012480
John McCall1f4ee7b2009-12-19 09:28:58 +000012481/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12482/// an initializer for the out-of-line declaration 'Dcl'. The scope
12483/// is a fresh scope pushed for just this purpose.
12484///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012485/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12486/// static data member of class X, names should be looked up in the scope of
12487/// class X.
John McCall48871652010-08-21 09:40:31 +000012488void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012489 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000012490 if (!D || D->isInvalidDecl())
12491 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012492
Richard Smitha2302242013-12-05 07:51:02 +000012493 // We will always have a nested name specifier here, but this declaration
12494 // might not be out of line if the specifier names the current namespace:
12495 // extern int n;
12496 // int ::n = 0;
12497 if (D->isOutOfLine())
12498 EnterDeclaratorContext(S, D->getDeclContext());
12499
Douglas Gregor926410d2012-02-21 02:22:07 +000012500 // If we are parsing the initializer for a static data member, push a
12501 // new expression evaluation context that is associated with this static
12502 // data member.
12503 if (isStaticDataMember(D))
12504 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012505}
12506
12507/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000012508/// initializer for the out-of-line declaration 'D'.
12509void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012510 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000012511 if (!D || D->isInvalidDecl())
12512 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012513
Douglas Gregor926410d2012-02-21 02:22:07 +000012514 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000012515 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000012516
Richard Smitha2302242013-12-05 07:51:02 +000012517 if (D->isOutOfLine())
12518 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012519}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012520
12521/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12522/// C++ if/switch/while/for statement.
12523/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000012524DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012525 // C++ 6.4p2:
12526 // The declarator shall not specify a function or an array.
12527 // The type-specifier-seq shall not contain typedef and shall not declare a
12528 // new class or enumeration.
12529 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12530 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012531
12532 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012533 if (!Dcl)
12534 return true;
12535
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012536 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12537 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012538 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012539 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012540 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012541
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012542 return Dcl;
12543}
Anders Carlssonf98849e2009-12-02 17:15:43 +000012544
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012545void Sema::LoadExternalVTableUses() {
12546 if (!ExternalSource)
12547 return;
12548
12549 SmallVector<ExternalVTableUse, 4> VTables;
12550 ExternalSource->ReadUsedVTables(VTables);
12551 SmallVector<VTableUse, 4> NewUses;
12552 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12553 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12554 = VTablesUsed.find(VTables[I].Record);
12555 // Even if a definition wasn't required before, it may be required now.
12556 if (Pos != VTablesUsed.end()) {
12557 if (!Pos->second && VTables[I].DefinitionRequired)
12558 Pos->second = true;
12559 continue;
12560 }
12561
12562 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12563 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12564 }
12565
12566 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12567}
12568
Douglas Gregor88d292c2010-05-13 16:44:06 +000012569void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12570 bool DefinitionRequired) {
12571 // Ignore any vtable uses in unevaluated operands or for classes that do
12572 // not have a vtable.
12573 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000012574 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000012575 return;
12576
Douglas Gregor88d292c2010-05-13 16:44:06 +000012577 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012578 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012579 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12580 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12581 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12582 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000012583 // If we already had an entry, check to see if we are promoting this vtable
12584 // to required a definition. If so, we need to reappend to the VTableUses
12585 // list, since we may have already processed the first entry.
12586 if (DefinitionRequired && !Pos.first->second) {
12587 Pos.first->second = true;
12588 } else {
12589 // Otherwise, we can early exit.
12590 return;
12591 }
Hans Wennborg3d791542014-02-24 15:58:24 +000012592 } else {
12593 // The Microsoft ABI requires that we perform the destructor body
12594 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
12595 // the deleting destructor is emitted with the vtable, not with the
12596 // destructor definition as in the Itanium ABI.
12597 // If it has a definition, we do the check at that point instead.
12598 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12599 Class->hasUserDeclaredDestructor() &&
12600 !Class->getDestructor()->isDefined() &&
12601 !Class->getDestructor()->isDeleted()) {
Reid Kleckner67130862014-06-12 22:39:12 +000012602 CXXDestructorDecl *DD = Class->getDestructor();
12603 ContextRAII SavedContext(*this, DD);
12604 CheckDestructor(DD);
Hans Wennborg3d791542014-02-24 15:58:24 +000012605 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012606 }
12607
12608 // Local classes need to have their virtual members marked
12609 // immediately. For all other classes, we mark their virtual members
12610 // at the end of the translation unit.
12611 if (Class->isLocalClass())
12612 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000012613 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000012614 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000012615}
12616
Douglas Gregor88d292c2010-05-13 16:44:06 +000012617bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012618 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012619 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000012620 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000012621
Douglas Gregor88d292c2010-05-13 16:44:06 +000012622 // Note: The VTableUses vector could grow as a result of marking
12623 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000012624 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000012625 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000012626 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012627 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000012628 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012629 if (!Class)
12630 continue;
12631
12632 SourceLocation Loc = VTableUses[I].second;
12633
Richard Smithd3b5c9082012-07-27 04:22:15 +000012634 bool DefineVTable = true;
12635
Douglas Gregor88d292c2010-05-13 16:44:06 +000012636 // If this class has a key function, but that key function is
12637 // defined in another translation unit, we don't need to emit the
12638 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000012639 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000012640 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000012641 // The key function is in another translation unit.
12642 DefineVTable = false;
12643 TemplateSpecializationKind TSK =
12644 KeyFunction->getTemplateSpecializationKind();
12645 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12646 TSK != TSK_ImplicitInstantiation &&
12647 "Instantiations don't have key functions");
12648 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012649 } else if (!KeyFunction) {
12650 // If we have a class with no key function that is the subject
12651 // of an explicit instantiation declaration, suppress the
12652 // vtable; it will live with the explicit instantiation
12653 // definition.
12654 bool IsExplicitInstantiationDeclaration
12655 = Class->getTemplateSpecializationKind()
12656 == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000012657 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000012658 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000012659 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012660 if (TSK == TSK_ExplicitInstantiationDeclaration)
12661 IsExplicitInstantiationDeclaration = true;
12662 else if (TSK == TSK_ExplicitInstantiationDefinition) {
12663 IsExplicitInstantiationDeclaration = false;
12664 break;
12665 }
12666 }
12667
12668 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000012669 DefineVTable = false;
12670 }
12671
12672 // The exception specifications for all virtual members may be needed even
12673 // if we are not providing an authoritative form of the vtable in this TU.
12674 // We may choose to emit it available_externally anyway.
12675 if (!DefineVTable) {
12676 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12677 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012678 }
12679
12680 // Mark all of the virtual members of this class as referenced, so
12681 // that we can build a vtable. Then, tell the AST consumer that a
12682 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000012683 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012684 MarkVirtualMembersReferenced(Loc, Class);
12685 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12686 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12687
12688 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000012689 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000012690 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012691 const FunctionDecl *KeyFunctionDef = nullptr;
Douglas Gregor34bc6e52011-09-23 19:04:03 +000012692 if (!KeyFunction ||
12693 (KeyFunction->hasBody(KeyFunctionDef) &&
12694 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000012695 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12696 TSK_ExplicitInstantiationDefinition
12697 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12698 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012699 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000012700 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012701 VTableUses.clear();
12702
Douglas Gregor97509692011-04-22 22:25:37 +000012703 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000012704}
Anders Carlsson82fccd02009-12-07 08:24:59 +000012705
Richard Smithd3b5c9082012-07-27 04:22:15 +000012706void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12707 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000012708 for (const auto *I : RD->methods())
12709 if (I->isVirtual() && !I->isPure())
12710 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000012711}
12712
Rafael Espindola5b334082010-03-26 00:36:59 +000012713void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12714 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000012715 // Mark all functions which will appear in RD's vtable as used.
12716 CXXFinalOverriderMap FinalOverriders;
12717 RD->getFinalOverriders(FinalOverriders);
12718 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12719 E = FinalOverriders.end();
12720 I != E; ++I) {
12721 for (OverridingMethods::const_iterator OI = I->second.begin(),
12722 OE = I->second.end();
12723 OI != OE; ++OI) {
12724 assert(OI->second.size() > 0 && "no final overrider");
12725 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000012726
Richard Smith4ff9ff92012-07-07 06:59:51 +000012727 // C++ [basic.def.odr]p2:
12728 // [...] A virtual member function is used if it is not pure. [...]
12729 if (!Overrider->isPure())
12730 MarkFunctionReferenced(Loc, Overrider);
12731 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012732 }
Rafael Espindola5b334082010-03-26 00:36:59 +000012733
12734 // Only classes that have virtual bases need a VTT.
12735 if (RD->getNumVBases() == 0)
12736 return;
12737
Aaron Ballman574705e2014-03-13 15:41:46 +000012738 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000012739 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000012740 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000012741 if (Base->getNumVBases() == 0)
12742 continue;
12743 MarkVirtualMembersReferenced(Loc, Base);
12744 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012745}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012746
12747/// SetIvarInitializers - This routine builds initialization ASTs for the
12748/// Objective-C implementation whose ivars need be initialized.
12749void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000012750 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012751 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000012752 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012753 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012754 CollectIvarsToConstructOrDestruct(OID, ivars);
12755 if (ivars.empty())
12756 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012757 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012758 for (unsigned i = 0; i < ivars.size(); i++) {
12759 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000012760 if (Field->isInvalidDecl())
12761 continue;
12762
Alexis Hunt1d792652011-01-08 20:30:50 +000012763 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012764 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12765 InitializationKind InitKind =
12766 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000012767
12768 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12769 ExprResult MemberInit =
12770 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000012771 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012772 // Note, MemberInit could actually come back empty if no initialization
12773 // is required (e.g., because it would call a trivial default constructor)
12774 if (!MemberInit.get() || MemberInit.isInvalid())
12775 continue;
John McCallacf0ee52010-10-08 02:01:28 +000012776
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012777 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000012778 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12779 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012780 MemberInit.getAs<Expr>(),
Alexis Hunt1d792652011-01-08 20:30:50 +000012781 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012782 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000012783
12784 // Be sure that the destructor is accessible and is marked as referenced.
12785 if (const RecordType *RecordTy
12786 = Context.getBaseElementType(Field->getType())
12787 ->getAs<RecordType>()) {
12788 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000012789 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000012790 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000012791 CheckDestructorAccess(Field->getLocation(), Destructor,
12792 PDiag(diag::err_access_dtor_ivar)
12793 << Context.getBaseElementType(Field->getType()));
12794 }
12795 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012796 }
12797 ObjCImplementation->setIvarInitializers(Context,
12798 AllToInit.data(), AllToInit.size());
12799 }
12800}
Alexis Hunt6118d662011-05-04 05:57:24 +000012801
Alexis Hunt27a761d2011-05-04 23:29:54 +000012802static
12803void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12804 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12805 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12806 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12807 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000012808 if (Ctor->isInvalidDecl())
12809 return;
12810
Richard Smith802c4b72012-08-23 06:16:52 +000012811 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12812
12813 // Target may not be determinable yet, for instance if this is a dependent
12814 // call in an uninstantiated template.
12815 if (Target) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012816 const FunctionDecl *FNTarget = nullptr;
Richard Smith802c4b72012-08-23 06:16:52 +000012817 (void)Target->hasBody(FNTarget);
12818 Target = const_cast<CXXConstructorDecl*>(
12819 cast_or_null<CXXConstructorDecl>(FNTarget));
12820 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000012821
12822 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12823 // Avoid dereferencing a null pointer here.
Craig Topperc3ec1492014-05-26 06:22:03 +000012824 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000012825
12826 if (!Current.insert(Canonical))
12827 return;
12828
12829 // We know that beyond here, we aren't chaining into a cycle.
12830 if (!Target || !Target->isDelegatingConstructor() ||
12831 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012832 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012833 Current.clear();
12834 // We've hit a cycle.
12835 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12836 Current.count(TCanonical)) {
12837 // If we haven't diagnosed this cycle yet, do so now.
12838 if (!Invalid.count(TCanonical)) {
12839 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000012840 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012841 << Ctor;
12842
Richard Smith802c4b72012-08-23 06:16:52 +000012843 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000012844 if (TCanonical != Canonical)
12845 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12846
12847 CXXConstructorDecl *C = Target;
12848 while (C->getCanonicalDecl() != Canonical) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012849 const FunctionDecl *FNTarget = nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000012850 (void)C->getTargetConstructor()->hasBody(FNTarget);
12851 assert(FNTarget && "Ctor cycle through bodiless function");
12852
Richard Smith802c4b72012-08-23 06:16:52 +000012853 C = const_cast<CXXConstructorDecl*>(
12854 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000012855 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12856 }
12857 }
12858
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012859 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012860 Current.clear();
12861 } else {
12862 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12863 }
12864}
12865
12866
Alexis Hunt6118d662011-05-04 05:57:24 +000012867void Sema::CheckDelegatingCtorCycles() {
12868 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12869
Douglas Gregorbae31202011-07-27 21:57:17 +000012870 for (DelegatingCtorDeclsType::iterator
12871 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000012872 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000012873 I != E; ++I)
12874 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000012875
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012876 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12877 CE = Invalid.end();
12878 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012879 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000012880}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012881
Douglas Gregor3024f072012-04-16 07:05:22 +000012882namespace {
12883 /// \brief AST visitor that finds references to the 'this' expression.
12884 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12885 Sema &S;
12886
12887 public:
12888 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12889
12890 bool VisitCXXThisExpr(CXXThisExpr *E) {
12891 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12892 << E->isImplicit();
12893 return false;
12894 }
12895 };
12896}
12897
12898bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12899 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12900 if (!TSInfo)
12901 return false;
12902
12903 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012904 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000012905 if (!ProtoTL)
12906 return false;
12907
12908 // C++11 [expr.prim.general]p3:
12909 // [The expression this] shall not appear before the optional
12910 // cv-qualifier-seq and it shall not appear within the declaration of a
12911 // static member function (although its type and value category are defined
12912 // within a static member function as they are within a non-static member
12913 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000012914 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000012915 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000012916 FindCXXThisExpr Finder(*this);
12917
12918 // If the return type came after the cv-qualifier-seq, check it now.
12919 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000012920 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000012921 return true;
12922
12923 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000012924 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12925 return true;
12926
12927 return checkThisInStaticMemberFunctionAttributes(Method);
12928}
12929
12930bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12931 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12932 if (!TSInfo)
12933 return false;
12934
12935 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012936 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000012937 if (!ProtoTL)
12938 return false;
12939
David Blaikie6adc78e2013-02-18 22:06:02 +000012940 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000012941 FindCXXThisExpr Finder(*this);
12942
Douglas Gregor3024f072012-04-16 07:05:22 +000012943 switch (Proto->getExceptionSpecType()) {
Richard Smithf623c962012-04-17 00:58:00 +000012944 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000012945 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000012946 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000012947 case EST_DynamicNone:
12948 case EST_MSAny:
12949 case EST_None:
12950 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000012951
Douglas Gregor3024f072012-04-16 07:05:22 +000012952 case EST_ComputedNoexcept:
12953 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12954 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000012955
Douglas Gregor3024f072012-04-16 07:05:22 +000012956 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000012957 for (const auto &E : Proto->exceptions()) {
12958 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000012959 return true;
12960 }
12961 break;
12962 }
Douglas Gregor433e0532012-04-16 18:27:27 +000012963
12964 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000012965}
12966
12967bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12968 FindCXXThisExpr Finder(*this);
12969
12970 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012971 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012972 // FIXME: This should be emitted by tblgen.
Craig Topperc3ec1492014-05-26 06:22:03 +000012973 Expr *Arg = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +000012974 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012975 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012976 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012977 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012978 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012979 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012980 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012981 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012982 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012983 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012984 Arg = ETLF->getSuccessValue();
12985 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012986 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012987 Arg = STLF->getSuccessValue();
12988 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
Aaron Ballman18d85ae2014-03-20 16:02:49 +000012989 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012990 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012991 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012992 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012993 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Aaron Ballmanefe348e2014-02-18 17:36:50 +000012994 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012995 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Aaron Ballman9e9d1842014-02-21 21:05:14 +000012996 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012997 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
12998 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
12999 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Aaron Ballman9e9d1842014-02-21 21:05:14 +000013000 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000013001
13002 if (Arg && !Finder.TraverseStmt(Arg))
13003 return true;
13004
13005 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13006 if (!Finder.TraverseStmt(Args[I]))
13007 return true;
13008 }
13009 }
13010
13011 return false;
13012}
13013
Douglas Gregor433e0532012-04-16 18:27:27 +000013014void
13015Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
13016 ArrayRef<ParsedType> DynamicExceptions,
13017 ArrayRef<SourceRange> DynamicExceptionRanges,
13018 Expr *NoexceptExpr,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013019 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +000013020 FunctionProtoType::ExceptionSpecInfo &ESI) {
Douglas Gregor433e0532012-04-16 18:27:27 +000013021 Exceptions.clear();
Richard Smith8acb4282014-07-31 21:57:55 +000013022 ESI.Type = EST;
Douglas Gregor433e0532012-04-16 18:27:27 +000013023 if (EST == EST_Dynamic) {
13024 Exceptions.reserve(DynamicExceptions.size());
13025 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13026 // FIXME: Preserve type source info.
13027 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13028
13029 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13030 collectUnexpandedParameterPacks(ET, Unexpanded);
13031 if (!Unexpanded.empty()) {
13032 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
13033 UPPC_ExceptionType,
13034 Unexpanded);
13035 continue;
13036 }
13037
13038 // Check that the type is valid for an exception spec, and
13039 // drop it if not.
13040 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13041 Exceptions.push_back(ET);
13042 }
Richard Smith8acb4282014-07-31 21:57:55 +000013043 ESI.Exceptions = Exceptions;
Douglas Gregor433e0532012-04-16 18:27:27 +000013044 return;
13045 }
Richard Smith8acb4282014-07-31 21:57:55 +000013046
Douglas Gregor433e0532012-04-16 18:27:27 +000013047 if (EST == EST_ComputedNoexcept) {
13048 // If an error occurred, there's no expression here.
13049 if (NoexceptExpr) {
13050 assert((NoexceptExpr->isTypeDependent() ||
13051 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13052 Context.BoolTy) &&
13053 "Parser should have made sure that the expression is boolean");
13054 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
Richard Smith8acb4282014-07-31 21:57:55 +000013055 ESI.Type = EST_BasicNoexcept;
Douglas Gregor433e0532012-04-16 18:27:27 +000013056 return;
13057 }
Richard Smith8acb4282014-07-31 21:57:55 +000013058
Douglas Gregor433e0532012-04-16 18:27:27 +000013059 if (!NoexceptExpr->isValueDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +000013060 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
Douglas Gregore2b37442012-05-04 22:38:52 +000013061 diag::err_noexcept_needs_constant_expression,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013062 /*AllowFold*/ false).get();
Richard Smith8acb4282014-07-31 21:57:55 +000013063 ESI.NoexceptExpr = NoexceptExpr;
Douglas Gregor433e0532012-04-16 18:27:27 +000013064 }
13065 return;
13066 }
13067}
13068
Peter Collingbourne7277fe82011-10-02 23:49:40 +000013069/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
13070Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
13071 // Implicitly declared functions (e.g. copy constructors) are
13072 // __host__ __device__
13073 if (D->isImplicit())
13074 return CFT_HostDevice;
13075
13076 if (D->hasAttr<CUDAGlobalAttr>())
13077 return CFT_Global;
13078
13079 if (D->hasAttr<CUDADeviceAttr>()) {
13080 if (D->hasAttr<CUDAHostAttr>())
13081 return CFT_HostDevice;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013082 return CFT_Device;
Peter Collingbourne7277fe82011-10-02 23:49:40 +000013083 }
13084
13085 return CFT_Host;
13086}
13087
13088bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
13089 CUDAFunctionTarget CalleeTarget) {
13090 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
13091 // Callable from the device only."
13092 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
13093 return true;
13094
13095 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
13096 // Callable from the host only."
13097 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
13098 // Callable from the host only."
13099 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
13100 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
13101 return true;
13102
13103 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
13104 return true;
13105
13106 return false;
13107}
John McCall5e77d762013-04-16 07:28:30 +000013108
13109/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13110///
13111MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13112 SourceLocation DeclStart,
13113 Declarator &D, Expr *BitWidth,
13114 InClassInitStyle InitStyle,
13115 AccessSpecifier AS,
13116 AttributeList *MSPropertyAttr) {
13117 IdentifierInfo *II = D.getIdentifier();
13118 if (!II) {
13119 Diag(DeclStart, diag::err_anonymous_property);
Craig Topperc3ec1492014-05-26 06:22:03 +000013120 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013121 }
13122 SourceLocation Loc = D.getIdentifierLoc();
13123
13124 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13125 QualType T = TInfo->getType();
13126 if (getLangOpts().CPlusPlus) {
13127 CheckExtraCXXDefaultArguments(D);
13128
13129 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13130 UPPC_DataMemberType)) {
13131 D.setInvalidType();
13132 T = Context.IntTy;
13133 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13134 }
13135 }
13136
13137 DiagnoseFunctionSpecifiers(D.getDeclSpec());
13138
13139 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13140 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13141 diag::err_invalid_thread)
13142 << DeclSpec::getSpecifierName(TSCS);
13143
13144 // Check to see if this name was declared as a member previously
Craig Topperc3ec1492014-05-26 06:22:03 +000013145 NamedDecl *PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013146 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13147 LookupName(Previous, S);
13148 switch (Previous.getResultKind()) {
13149 case LookupResult::Found:
13150 case LookupResult::FoundUnresolvedValue:
13151 PrevDecl = Previous.getAsSingle<NamedDecl>();
13152 break;
13153
13154 case LookupResult::FoundOverloaded:
13155 PrevDecl = Previous.getRepresentativeDecl();
13156 break;
13157
13158 case LookupResult::NotFound:
13159 case LookupResult::NotFoundInCurrentInstantiation:
13160 case LookupResult::Ambiguous:
13161 break;
13162 }
13163
13164 if (PrevDecl && PrevDecl->isTemplateParameter()) {
13165 // Maybe we will complain about the shadowed template parameter.
13166 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13167 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000013168 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013169 }
13170
13171 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Craig Topperc3ec1492014-05-26 06:22:03 +000013172 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013173
13174 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000013175 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000013176 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13177 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000013178 ProcessDeclAttributes(TUScope, NewPD, D);
13179 NewPD->setAccess(AS);
13180
13181 if (NewPD->isInvalidDecl())
13182 Record->setInvalidDecl();
13183
13184 if (D.getDeclSpec().isModulePrivateSpecified())
13185 NewPD->setModulePrivate();
13186
13187 if (NewPD->isInvalidDecl() && PrevDecl) {
13188 // Don't introduce NewFD into scope; there's already something
13189 // with the same name in the same scope.
13190 } else if (II) {
13191 PushOnScopeChains(NewPD, S);
13192 } else
13193 Record->addDecl(NewPD);
13194
13195 return NewPD;
13196}