blob: f7183bc2c4a6a5b77cdf6edfd42bc14d839e5a75 [file] [log] [blame]
Chris Lattner3d1cee32008-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 McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Faisal Valifad9e132013-09-26 19:54:12 +000017#include "clang/AST/ASTLambda.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000018#include "clang/AST/ASTMutationListener.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/AST/CharUnits.h"
Richard Trieude5e75c2012-06-14 23:11:34 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000023#include "clang/AST/RecordLayout.h"
Douglas Gregorcefc3af2012-04-16 07:05:22 +000024#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000025#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballmanfff32482012-12-09 17:45:41 +000029#include "clang/Basic/TargetInfo.h"
Richard Smith4ac537b2013-07-23 08:14:48 +000030#include "clang/Lex/LiteralSupport.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000031#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-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"
Stephen Hines176edba2014-12-01 14:53:08 -080039#include "clang/Sema/Template.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000040#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000041#include "llvm/ADT/SmallString.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000042#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000043#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000044
45using namespace clang;
46
Chris Lattner8123a952008-04-10 02:22:51 +000047//===----------------------------------------------------------------------===//
48// CheckDefaultArgumentVisitor
49//===----------------------------------------------------------------------===//
50
Chris Lattner9e979552008-04-12 23:52:44 +000051namespace {
52 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
53 /// the default argument of a parameter to determine whether it
54 /// contains any ill-formed subexpressions. For example, this will
55 /// diagnose the use of local variables or parameters within the
56 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000057 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000058 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000059 Expr *DefaultArg;
60 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000061
Chris Lattner9e979552008-04-12 23:52:44 +000062 public:
Mike Stump1eb44332009-09-09 15:08:12 +000063 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000064 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000065
Chris Lattner9e979552008-04-12 23:52:44 +000066 bool VisitExpr(Expr *Node);
67 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000068 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000069 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall045d2522013-04-09 01:56:28 +000070 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattner9e979552008-04-12 23:52:44 +000071 };
Chris Lattner8123a952008-04-10 02:22:51 +000072
Chris Lattner9e979552008-04-12 23:52:44 +000073 /// VisitExpr - Visit all of the children of this expression.
74 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
75 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000076 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000077 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000078 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000079 }
80
Chris Lattner9e979552008-04-12 23:52:44 +000081 /// VisitDeclRefExpr - Visit a reference to a declaration, to
82 /// determine whether this declaration can be used in the default
83 /// argument expression.
84 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000085 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000086 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
87 // C++ [dcl.fct.default]p9
88 // Default arguments are evaluated each time the function is
89 // called. The order of evaluation of function arguments is
90 // unspecified. Consequently, parameters of a function shall not
91 // be used in default argument expressions, even if they are not
92 // evaluated. Parameters of a function declared before a default
93 // argument expression are in scope and can hide namespace and
94 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000095 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000096 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000097 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000098 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000099 // C++ [dcl.fct.default]p7
100 // Local variables shall not be used in default argument
101 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +0000102 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000103 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000104 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000105 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000106 }
Chris Lattner8123a952008-04-10 02:22:51 +0000107
Douglas Gregor3996f232008-11-04 13:41:56 +0000108 return false;
109 }
Chris Lattner9e979552008-04-12 23:52:44 +0000110
Douglas Gregor796da182008-11-04 14:32:21 +0000111 /// VisitCXXThisExpr - Visit a C++ "this" expression.
112 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
113 // C++ [dcl.fct.default]p8:
114 // The keyword this shall not be used in a default argument of a
115 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000116 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000117 diag::err_param_default_argument_references_this)
118 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000119 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000120
John McCall045d2522013-04-09 01:56:28 +0000121 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
122 bool Invalid = false;
123 for (PseudoObjectExpr::semantics_iterator
124 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
125 Expr *E = *i;
126
127 // Look through bindings.
128 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
129 E = OVE->getSourceExpr();
130 assert(E && "pseudo-object binding without source expression?");
131 }
132
133 Invalid |= Visit(E);
134 }
135 return Invalid;
136 }
137
Douglas Gregorf0459f82012-02-10 23:30:22 +0000138 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
139 // C++11 [expr.lambda.prim]p13:
140 // A lambda-expression appearing in a default argument shall not
141 // implicitly or explicitly capture any entity.
142 if (Lambda->capture_begin() == Lambda->capture_end())
143 return false;
144
145 return S->Diag(Lambda->getLocStart(),
146 diag::err_lambda_capture_default_arg);
147 }
Chris Lattner8123a952008-04-10 02:22:51 +0000148}
149
Richard Smith0b0ca472013-04-10 06:11:48 +0000150void
151Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152 const CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000153 // If we have an MSAny spec already, don't bother.
154 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000155 return;
156
157 const FunctionProtoType *Proto
158 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160 if (!Proto)
161 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000162
163 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
164
165 // If this function can throw any exceptions, make a note of that.
Richard Smithb9d0b762012-07-27 04:22:15 +0000166 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000167 ClearExceptions();
168 ComputedEST = EST;
169 return;
170 }
171
Richard Smith7a614d82011-06-11 17:19:42 +0000172 // FIXME: If the call to this decl is using any of its default arguments, we
173 // need to search them for potentially-throwing calls.
174
Sean Hunt001cad92011-05-10 00:49:42 +0000175 // If this function has a basic noexcept, it doesn't affect the outcome.
176 if (EST == EST_BasicNoexcept)
177 return;
178
179 // If we have a throw-all spec at this point, ignore the function.
180 if (ComputedEST == EST_None)
181 return;
182
183 // If we're still at noexcept(true) and there's a nothrow() callee,
184 // change to that specification.
185 if (EST == EST_DynamicNone) {
186 if (ComputedEST == EST_BasicNoexcept)
187 ComputedEST = EST_DynamicNone;
188 return;
189 }
190
191 // Check out noexcept specs.
192 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000193 FunctionProtoType::NoexceptResult NR =
194 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000195 assert(NR != FunctionProtoType::NR_NoNoexcept &&
196 "Must have noexcept result for EST_ComputedNoexcept.");
197 assert(NR != FunctionProtoType::NR_Dependent &&
198 "Should not generate implicit declarations for dependent cases, "
199 "and don't know how to handle them anyway.");
200
201 // noexcept(false) -> no spec on the new function
202 if (NR == FunctionProtoType::NR_Throw) {
203 ClearExceptions();
204 ComputedEST = EST_None;
205 }
206 // noexcept(true) won't change anything either.
207 return;
208 }
209
210 assert(EST == EST_Dynamic && "EST case not considered earlier.");
211 assert(ComputedEST != EST_None &&
212 "Shouldn't collect exceptions when throw-all is guaranteed.");
213 ComputedEST = EST_Dynamic;
214 // Record the exceptions in this function's exception specification.
Stephen Hines651f13c2014-04-23 16:59:28 -0700215 for (const auto &E : Proto->exceptions())
Stephen Hines176edba2014-12-01 14:53:08 -0800216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
Stephen Hines651f13c2014-04-23 16:59:28 -0700217 Exceptions.push_back(E);
Sean Hunt001cad92011-05-10 00:49:42 +0000218}
219
Richard Smith7a614d82011-06-11 17:19:42 +0000220void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000221 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000222 return;
223
224 // FIXME:
225 //
226 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000227 // [An] implicit exception-specification specifies the type-id T if and
228 // only if T is allowed by the exception-specification of a function directly
229 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000230 // function it directly invokes allows all exceptions, and f shall allow no
231 // exceptions if every function it directly invokes allows no exceptions.
232 //
233 // Note in particular that if an implicit exception-specification is generated
234 // for a function containing a throw-expression, that specification can still
235 // be noexcept(true).
236 //
237 // Note also that 'directly invoked' is not defined in the standard, and there
238 // is no indication that we should only consider potentially-evaluated calls.
239 //
240 // Ultimately we should implement the intent of the standard: the exception
241 // specification should be the set of exceptions which can be thrown by the
242 // implicit definition. For now, we assume that any non-nothrow expression can
243 // throw any exception.
244
Richard Smithe6975e92012-04-17 00:58:00 +0000245 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000246 ComputedEST = EST_None;
247}
248
Anders Carlssoned961f92009-08-25 02:29:20 +0000249bool
John McCall9ae2f072010-08-23 23:25:46 +0000250Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000251 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000252 if (RequireCompleteType(Param->getLocation(), Param->getType(),
253 diag::err_typecheck_decl_incomplete_type)) {
254 Param->setInvalidDecl();
255 return true;
256 }
257
Anders Carlssoned961f92009-08-25 02:29:20 +0000258 // C++ [dcl.fct.default]p5
259 // A default argument expression is implicitly converted (clause
260 // 4) to the parameter type. The default argument expression has
261 // the same semantic constraints as the initializer expression in
262 // a declaration of a variable of the parameter type, using the
263 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267 EqualLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000268 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000270 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000271 return true;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700272 Arg = Result.getAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000273
Richard Smith6c3af3d2013-01-17 01:17:56 +0000274 CheckCompletedExpr(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000275 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Anders Carlssoned961f92009-08-25 02:29:20 +0000277 // Okay: add the default argument to the parameter
278 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000280 // We have already instantiated this parameter; provide each of the
281 // instantiations with the uninstantiated default argument.
282 UnparsedDefaultArgInstantiationsMap::iterator InstPos
283 = UnparsedDefaultArgInstantiations.find(Param);
284 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287
288 // We're done tracking this parameter's instantiations.
289 UnparsedDefaultArgInstantiations.erase(InstPos);
290 }
291
Anders Carlsson9351c172009-08-25 03:18:48 +0000292 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000293}
294
Chris Lattner8123a952008-04-10 02:22:51 +0000295/// ActOnParamDefaultArgument - Check whether the default argument
296/// provided for a function parameter is well-formed. If so, attach it
297/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000298void
John McCalld226f652010-08-21 09:40:31 +0000299Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000300 Expr *DefaultArg) {
301 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000302 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000303
John McCalld226f652010-08-21 09:40:31 +0000304 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000305 UnparsedDefaultArgLocs.erase(Param);
306
Chris Lattner3d1cee32008-04-08 05:04:30 +0000307 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000308 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000309 Diag(EqualLoc, diag::err_param_default_argument)
310 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000311 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000312 return;
313 }
314
Douglas Gregor6f526752010-12-16 08:48:57 +0000315 // Check for unexpanded parameter packs.
316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317 Param->setInvalidDecl();
318 return;
319 }
320
Anders Carlsson66e30672009-08-25 01:02:06 +0000321 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
323 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000324 Param->setInvalidDecl();
325 return;
326 }
Mike Stump1eb44332009-09-09 15:08:12 +0000327
John McCall9ae2f072010-08-23 23:25:46 +0000328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000329}
330
Douglas Gregor61366e92008-12-24 00:01:03 +0000331/// ActOnParamUnparsedDefaultArgument - We've seen a default
332/// argument for a function parameter, but we can't parse it yet
333/// because we're inside a class definition. Note that this default
334/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000335void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000336 SourceLocation EqualLoc,
337 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000338 if (!param)
339 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000340
John McCalld226f652010-08-21 09:40:31 +0000341 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Nick Lewyckyee0bc3b2013-09-22 10:06:57 +0000342 Param->setUnparsedDefaultArg();
Anders Carlsson5e300d12009-06-12 16:51:40 +0000343 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000344}
345
Douglas Gregor72b505b2008-12-16 21:30:33 +0000346/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
347/// the default argument for the parameter param failed.
Stephen Hines176edba2014-12-01 14:53:08 -0800348void Sema::ActOnParamDefaultArgumentError(Decl *param,
349 SourceLocation EqualLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000350 if (!param)
351 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000352
John McCalld226f652010-08-21 09:40:31 +0000353 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000354 Param->setInvalidDecl();
Anders Carlsson5e300d12009-06-12 16:51:40 +0000355 UnparsedDefaultArgLocs.erase(Param);
Stephen Hines176edba2014-12-01 14:53:08 -0800356 Param->setDefaultArg(new(Context)
357 OpaqueValueExpr(EqualLoc,
358 Param->getType().getNonReferenceType(),
359 VK_RValue));
Douglas Gregor72b505b2008-12-16 21:30:33 +0000360}
361
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000362/// CheckExtraCXXDefaultArguments - Check for any extra default
363/// arguments in the declarator, which is not a function declaration
364/// or definition and therefore is not permitted to have default
365/// arguments. This routine should be invoked for every declarator
366/// that is not a function declaration or definition.
367void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
368 // C++ [dcl.fct.default]p3
369 // A default argument expression shall be specified only in the
370 // parameter-declaration-clause of a function declaration or in a
371 // template-parameter (14.1). It shall not be specified for a
372 // parameter pack. If it is specified in a
373 // parameter-declaration-clause, it shall not occur within a
374 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000375 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattnerb28317a2009-03-28 19:18:32 +0000376 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000377 DeclaratorChunk &chunk = D.getTypeObject(i);
378 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000379 if (MightBeFunction) {
380 // This is a function declaration. It can have default arguments, but
381 // keep looking in case its return type is a function type with default
382 // arguments.
383 MightBeFunction = false;
384 continue;
385 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700386 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
387 ++argIdx) {
388 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000389 if (Param->hasUnparsedDefaultArg()) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700390 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700391 SourceRange SR;
392 if (Toks->size() > 1)
393 SR = SourceRange((*Toks)[1].getLocation(),
394 Toks->back().getLocation());
395 else
396 SR = UnparsedDefaultArgLocs[Param];
Douglas Gregor72b505b2008-12-16 21:30:33 +0000397 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700398 << SR;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000399 delete Toks;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700400 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
Douglas Gregor61366e92008-12-24 00:01:03 +0000401 } else if (Param->getDefaultArg()) {
402 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
403 << Param->getDefaultArg()->getSourceRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700404 Param->setDefaultArg(nullptr);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000405 }
406 }
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000407 } else if (chunk.Kind != DeclaratorChunk::Paren) {
408 MightBeFunction = false;
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000409 }
410 }
411}
412
David Majnemerf6a144f2013-06-25 23:09:30 +0000413static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
414 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
415 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
416 if (!PVD->hasDefaultArg())
417 return false;
418 if (!PVD->hasInheritedDefaultArg())
419 return true;
420 }
421 return false;
422}
423
Craig Topper1a6eac82012-09-21 04:33:26 +0000424/// MergeCXXFunctionDecl - Merge two declarations of the same C++
425/// function, once we already know that they have the same
426/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
427/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000428bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
429 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000430 bool Invalid = false;
431
Chris Lattner3d1cee32008-04-08 05:04:30 +0000432 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000433 // For non-template functions, default arguments can be added in
434 // later declarations of a function in the same
435 // scope. Declarations in different scopes have completely
436 // distinct sets of default arguments. That is, declarations in
437 // inner scopes do not acquire default arguments from
438 // declarations in outer scopes, and vice versa. In a given
439 // function declaration, all parameters subsequent to a
440 // parameter with a default argument shall have default
441 // arguments supplied in this or previous declarations. A
442 // default argument shall not be redefined by a later
443 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000444 //
445 // C++ [dcl.fct.default]p6:
Richard Smitha41c97a2013-09-20 01:15:31 +0000446 // Except for member functions of class templates, the default arguments
447 // in a member function definition that appears outside of the class
448 // definition are added to the set of default arguments provided by the
Douglas Gregor6cc15182009-09-11 18:44:32 +0000449 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000450 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
451 ParmVarDecl *OldParam = Old->getParamDecl(p);
452 ParmVarDecl *NewParam = New->getParamDecl(p);
453
James Molloy9cda03f2012-03-13 08:55:35 +0000454 bool OldParamHasDfl = OldParam->hasDefaultArg();
455 bool NewParamHasDfl = NewParam->hasDefaultArg();
456
Richard Smitha41c97a2013-09-20 01:15:31 +0000457 // The declaration context corresponding to the scope is the semantic
458 // parent, unless this is a local function declaration, in which case
459 // it is that surrounding function.
Stephen Hines176edba2014-12-01 14:53:08 -0800460 DeclContext *ScopeDC = New->isLocalExternDecl()
461 ? New->getLexicalDeclContext()
462 : New->getDeclContext();
463 if (S && !isDeclInScope(Old, ScopeDC, S) &&
Richard Smitha41c97a2013-09-20 01:15:31 +0000464 !New->getDeclContext()->isRecord())
James Molloy9cda03f2012-03-13 08:55:35 +0000465 // Ignore default parameters of old decl if they are not in
Richard Smitha41c97a2013-09-20 01:15:31 +0000466 // the same scope and this is not an out-of-line definition of
467 // a member function.
James Molloy9cda03f2012-03-13 08:55:35 +0000468 OldParamHasDfl = false;
Stephen Hines176edba2014-12-01 14:53:08 -0800469 if (New->isLocalExternDecl() != Old->isLocalExternDecl())
470 // If only one of these is a local function declaration, then they are
471 // declared in different scopes, even though isDeclInScope may think
472 // they're in the same scope. (If both are local, the scope check is
473 // sufficent, and if neither is local, then they are in the same scope.)
474 OldParamHasDfl = false;
James Molloy9cda03f2012-03-13 08:55:35 +0000475
476 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000477
Francois Pichet8d051e02011-04-10 03:03:52 +0000478 unsigned DiagDefaultParamID =
479 diag::err_param_default_argument_redefinition;
480
481 // MSVC accepts that default parameters be redefined for member functions
482 // of template class. The new default parameter's value is ignored.
483 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000484 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000485 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
486 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000487 // Merge the old default argument into the new parameter.
488 NewParam->setHasInheritedDefaultArg();
489 if (OldParam->hasUninstantiatedDefaultArg())
490 NewParam->setUninstantiatedDefaultArg(
491 OldParam->getUninstantiatedDefaultArg());
492 else
493 NewParam->setDefaultArg(OldParam->getInit());
Stephen Hines176edba2014-12-01 14:53:08 -0800494 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000495 Invalid = false;
496 }
497 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000498
Francois Pichet8cf90492011-04-10 04:58:30 +0000499 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
500 // hint here. Alternatively, we could walk the type-source information
501 // for NewParam to find the last source location in the type... but it
502 // isn't worth the effort right now. This is the kind of test case that
503 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000504 // int f(int);
505 // void g(int (*fp)(int) = f);
506 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000507 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000508 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000509
510 // Look for the function declaration where the default argument was
511 // actually written, which may be a declaration prior to Old.
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700512 for (auto Older = Old; OldParam->hasInheritedDefaultArg();) {
513 Older = Older->getPreviousDecl();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000514 OldParam = Older->getParamDecl(p);
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700515 }
516
Douglas Gregor6cc15182009-09-11 18:44:32 +0000517 Diag(OldParam->getLocation(), diag::note_previous_definition)
518 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000519 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000520 // Merge the old default argument into the new parameter.
521 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000522 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000523 NewParam->setHasInheritedDefaultArg();
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700524 if (OldParam->hasUnparsedDefaultArg())
525 NewParam->setUnparsedDefaultArg();
526 else if (OldParam->hasUninstantiatedDefaultArg())
Douglas Gregord85cef52009-09-17 19:51:30 +0000527 NewParam->setUninstantiatedDefaultArg(
528 OldParam->getUninstantiatedDefaultArg());
529 else
John McCall3d6c1782010-05-04 01:53:42 +0000530 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000531 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000532 if (New->getDescribedFunctionTemplate()) {
533 // Paragraph 4, quoted above, only applies to non-template functions.
534 Diag(NewParam->getLocation(),
535 diag::err_param_default_argument_template_redecl)
536 << NewParam->getDefaultArgRange();
537 Diag(Old->getLocation(), diag::note_template_prev_declaration)
538 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000539 } else if (New->getTemplateSpecializationKind()
540 != TSK_ImplicitInstantiation &&
541 New->getTemplateSpecializationKind() != TSK_Undeclared) {
542 // C++ [temp.expr.spec]p21:
543 // Default function arguments shall not be specified in a declaration
544 // or a definition for one of the following explicit specializations:
545 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000546 // - the explicit specialization of a member function template;
547 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000548 // template where the class template specialization to which the
549 // member function specialization belongs is implicitly
550 // instantiated.
551 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
552 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
553 << New->getDeclName()
554 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000555 } else if (New->getDeclContext()->isDependentContext()) {
556 // C++ [dcl.fct.default]p6 (DR217):
557 // Default arguments for a member function of a class template shall
558 // be specified on the initial declaration of the member function
559 // within the class template.
560 //
561 // Reading the tea leaves a bit in DR217 and its reference to DR205
562 // leads me to the conclusion that one cannot add default function
563 // arguments for an out-of-line definition of a member function of a
564 // dependent type.
565 int WhichKind = 2;
566 if (CXXRecordDecl *Record
567 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
568 if (Record->getDescribedClassTemplate())
569 WhichKind = 0;
570 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
571 WhichKind = 1;
572 else
573 WhichKind = 2;
574 }
575
576 Diag(NewParam->getLocation(),
577 diag::err_param_default_argument_member_template_redecl)
578 << WhichKind
579 << NewParam->getDefaultArgRange();
580 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000581 }
582 }
583
Richard Smithb8abff62012-11-28 03:45:24 +0000584 // DR1344: If a default argument is added outside a class definition and that
585 // default argument makes the function a special member function, the program
586 // is ill-formed. This can only happen for constructors.
587 if (isa<CXXConstructorDecl>(New) &&
588 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
589 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
590 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
591 if (NewSM != OldSM) {
592 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
593 assert(NewParam->hasDefaultArg());
594 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
595 << NewParam->getDefaultArgRange() << NewSM;
596 Diag(Old->getLocation(), diag::note_previous_declaration);
597 }
598 }
599
Stephen Hines651f13c2014-04-23 16:59:28 -0700600 const FunctionDecl *Def;
Richard Smithff234882012-02-20 23:28:05 +0000601 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000602 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000603 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000604 if (New->isConstexpr() != Old->isConstexpr()) {
605 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
606 << New << New->isConstexpr();
607 Diag(Old->getLocation(), diag::note_previous_declaration);
608 Invalid = true;
Stephen Hines651f13c2014-04-23 16:59:28 -0700609 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) {
610 // C++11 [dcl.fcn.spec]p4:
611 // If the definition of a function appears in a translation unit before its
612 // first declaration as inline, the program is ill-formed.
613 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
614 Diag(Def->getLocation(), diag::note_previous_definition);
615 Invalid = true;
Richard Smith9f569cc2011-10-01 02:31:28 +0000616 }
617
David Majnemerf6a144f2013-06-25 23:09:30 +0000618 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumifd527a42013-07-17 17:57:52 +0000619 // argument expression, that declaration shall be a definition and shall be
David Majnemerf6a144f2013-06-25 23:09:30 +0000620 // the only declaration of the function or function template in the
621 // translation unit.
622 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
623 functionDeclHasDefaultArgument(Old)) {
624 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
625 Diag(Old->getLocation(), diag::note_previous_declaration);
626 Invalid = true;
627 }
628
Douglas Gregore13ad832010-02-12 07:32:17 +0000629 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000630 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000631
Douglas Gregorcda9c672009-02-16 17:45:42 +0000632 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000633}
634
Sebastian Redl60618fa2011-03-12 11:50:43 +0000635/// \brief Merge the exception specifications of two variable declarations.
636///
637/// This is called when there's a redeclaration of a VarDecl. The function
638/// checks if the redeclaration might have an exception specification and
639/// validates compatibility and merges the specs if necessary.
640void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
641 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000642 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000643 return;
644
645 assert(Context.hasSameType(New->getType(), Old->getType()) &&
646 "Should only be called if types are otherwise the same.");
647
648 QualType NewType = New->getType();
649 QualType OldType = Old->getType();
650
651 // We're only interested in pointers and references to functions, as well
652 // as pointers to member functions.
653 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
654 NewType = R->getPointeeType();
655 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
656 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
657 NewType = P->getPointeeType();
658 OldType = OldType->getAs<PointerType>()->getPointeeType();
659 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
660 NewType = M->getPointeeType();
661 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
662 }
663
664 if (!NewType->isFunctionProtoType())
665 return;
666
667 // There's lots of special cases for functions. For function pointers, system
668 // libraries are hopefully not as broken so that we don't need these
669 // workarounds.
670 if (CheckEquivalentExceptionSpec(
671 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
672 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
673 New->setInvalidDecl();
674 }
675}
676
Chris Lattner3d1cee32008-04-08 05:04:30 +0000677/// CheckCXXDefaultArguments - Verify that the default arguments for a
678/// function declaration are well-formed according to C++
679/// [dcl.fct.default].
680void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
681 unsigned NumParams = FD->getNumParams();
682 unsigned p;
683
684 // Find first parameter with a default argument
685 for (p = 0; p < NumParams; ++p) {
686 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith7974c602013-04-17 16:25:20 +0000687 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000688 break;
689 }
690
691 // C++ [dcl.fct.default]p4:
692 // In a given function declaration, all parameters
693 // subsequent to a parameter with a default argument shall
694 // have default arguments supplied in this or previous
695 // declarations. A default argument shall not be redefined
696 // by a later declaration (not even to the same value).
697 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000698 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000699 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000700 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000701 if (Param->isInvalidDecl())
702 /* We already complained about this parameter. */;
703 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000704 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000705 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000706 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000707 else
Mike Stump1eb44332009-09-09 15:08:12 +0000708 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000709 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000710
Chris Lattner3d1cee32008-04-08 05:04:30 +0000711 LastMissingDefaultArg = p;
712 }
713 }
714
715 if (LastMissingDefaultArg > 0) {
716 // Some default arguments were missing. Clear out all of the
717 // default arguments up to (and including) the last missing
718 // default argument, so that we leave the function parameters
719 // in a semantically valid state.
720 for (p = 0; p <= LastMissingDefaultArg; ++p) {
721 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000722 if (Param->hasDefaultArg()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700723 Param->setDefaultArg(nullptr);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000724 }
725 }
726 }
727}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000728
Richard Smith9f569cc2011-10-01 02:31:28 +0000729// CheckConstexprParameterTypes - Check whether a function's parameter types
730// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000731// diagnostic and return false.
732static bool CheckConstexprParameterTypes(Sema &SemaRef,
733 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000734 unsigned ArgIndex = 0;
735 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -0700736 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
737 e = FT->param_type_end();
738 i != e; ++i, ++ArgIndex) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000739 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
740 SourceLocation ParamLoc = PD->getLocation();
741 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000742 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000743 diag::err_constexpr_non_literal_param,
744 ArgIndex+1, PD->getSourceRange(),
745 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000746 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000747 }
Joao Matos17d35c32012-08-31 22:18:20 +0000748 return true;
749}
750
751/// \brief Get diagnostic %select index for tag kind for
752/// record diagnostic message.
753/// WARNING: Indexes apply to particular diagnostics only!
754///
755/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000756static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000757 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000758 case TTK_Struct: return 0;
759 case TTK_Interface: return 1;
760 case TTK_Class: return 2;
761 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000762 }
Joao Matos17d35c32012-08-31 22:18:20 +0000763}
764
765// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
766// the requirements of a constexpr function definition or a constexpr
767// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000768// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000769//
Richard Smith86c3ae42012-02-13 03:54:03 +0000770// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
771bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000772 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
773 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000774 // C++11 [dcl.constexpr]p4:
775 // The definition of a constexpr constructor shall satisfy the following
776 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000777 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000778 const CXXRecordDecl *RD = MD->getParent();
779 if (RD->getNumVBases()) {
780 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
781 << isa<CXXConstructorDecl>(NewFD)
782 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Stephen Hines651f13c2014-04-23 16:59:28 -0700783 for (const auto &I : RD->vbases())
784 Diag(I.getLocStart(),
785 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000786 return false;
787 }
Richard Smith35340502012-01-13 04:54:00 +0000788 }
789
790 if (!isa<CXXConstructorDecl>(NewFD)) {
791 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000792 // The definition of a constexpr function shall satisfy the following
793 // constraints:
794 // - it shall not be virtual;
795 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
796 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000797 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000798
Richard Smith86c3ae42012-02-13 03:54:03 +0000799 // If it's not obvious why this function is virtual, find an overridden
800 // function which uses the 'virtual' keyword.
801 const CXXMethodDecl *WrittenVirtual = Method;
802 while (!WrittenVirtual->isVirtualAsWritten())
803 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
804 if (WrittenVirtual != Method)
805 Diag(WrittenVirtual->getLocation(),
806 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000807 return false;
808 }
809
810 // - its return type shall be a literal type;
Stephen Hines651f13c2014-04-23 16:59:28 -0700811 QualType RT = NewFD->getReturnType();
Richard Smith9f569cc2011-10-01 02:31:28 +0000812 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000813 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000814 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000815 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000816 }
817
Richard Smith35340502012-01-13 04:54:00 +0000818 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000819 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000820 return false;
821
Richard Smith9f569cc2011-10-01 02:31:28 +0000822 return true;
823}
824
825/// Check the given declaration statement is legal within a constexpr function
Richard Smitha10b9782013-04-22 15:31:51 +0000826/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smith9f569cc2011-10-01 02:31:28 +0000827///
Richard Smitha10b9782013-04-22 15:31:51 +0000828/// \return true if the body is OK (maybe only as an extension), false if we
829/// have diagnosed a problem.
Richard Smith9f569cc2011-10-01 02:31:28 +0000830static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smitha10b9782013-04-22 15:31:51 +0000831 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
832 // C++11 [dcl.constexpr]p3 and p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000833 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
834 // contain only
Stephen Hines651f13c2014-04-23 16:59:28 -0700835 for (const auto *DclIt : DS->decls()) {
836 switch (DclIt->getKind()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000837 case Decl::StaticAssert:
838 case Decl::Using:
839 case Decl::UsingShadow:
840 case Decl::UsingDirective:
841 case Decl::UnresolvedUsingTypename:
Richard Smitha10b9782013-04-22 15:31:51 +0000842 case Decl::UnresolvedUsingValue:
Richard Smith9f569cc2011-10-01 02:31:28 +0000843 // - static_assert-declarations
844 // - using-declarations,
845 // - using-directives,
846 continue;
847
848 case Decl::Typedef:
849 case Decl::TypeAlias: {
850 // - typedef declarations and alias-declarations that do not define
851 // classes or enumerations,
Stephen Hines651f13c2014-04-23 16:59:28 -0700852 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smith9f569cc2011-10-01 02:31:28 +0000853 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
854 // Don't allow variably-modified types in constexpr functions.
855 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
856 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
857 << TL.getSourceRange() << TL.getType()
858 << isa<CXXConstructorDecl>(Dcl);
859 return false;
860 }
861 continue;
862 }
863
864 case Decl::Enum:
865 case Decl::CXXRecord:
Richard Smitha10b9782013-04-22 15:31:51 +0000866 // C++1y allows types to be defined, not just declared.
Stephen Hines651f13c2014-04-23 16:59:28 -0700867 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smitha10b9782013-04-22 15:31:51 +0000868 SemaRef.Diag(DS->getLocStart(),
Stephen Hines176edba2014-12-01 14:53:08 -0800869 SemaRef.getLangOpts().CPlusPlus14
Richard Smitha10b9782013-04-22 15:31:51 +0000870 ? diag::warn_cxx11_compat_constexpr_type_definition
871 : diag::ext_constexpr_type_definition)
Richard Smith9f569cc2011-10-01 02:31:28 +0000872 << isa<CXXConstructorDecl>(Dcl);
Richard Smith9f569cc2011-10-01 02:31:28 +0000873 continue;
874
Richard Smitha10b9782013-04-22 15:31:51 +0000875 case Decl::EnumConstant:
876 case Decl::IndirectField:
877 case Decl::ParmVar:
878 // These can only appear with other declarations which are banned in
879 // C++11 and permitted in C++1y, so ignore them.
880 continue;
881
882 case Decl::Var: {
883 // C++1y [dcl.constexpr]p3 allows anything except:
884 // a definition of a variable of non-literal type or of static or
885 // thread storage duration or for which no initialization is performed.
Stephen Hines651f13c2014-04-23 16:59:28 -0700886 const auto *VD = cast<VarDecl>(DclIt);
Richard Smitha10b9782013-04-22 15:31:51 +0000887 if (VD->isThisDeclarationADefinition()) {
888 if (VD->isStaticLocal()) {
889 SemaRef.Diag(VD->getLocation(),
890 diag::err_constexpr_local_var_static)
891 << isa<CXXConstructorDecl>(Dcl)
892 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
893 return false;
894 }
Richard Smithbebf5b12013-04-26 14:36:30 +0000895 if (!VD->getType()->isDependentType() &&
896 SemaRef.RequireLiteralType(
Richard Smitha10b9782013-04-22 15:31:51 +0000897 VD->getLocation(), VD->getType(),
898 diag::err_constexpr_local_var_non_literal_type,
899 isa<CXXConstructorDecl>(Dcl)))
900 return false;
Stephen Hines651f13c2014-04-23 16:59:28 -0700901 if (!VD->getType()->isDependentType() &&
902 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smitha10b9782013-04-22 15:31:51 +0000903 SemaRef.Diag(VD->getLocation(),
904 diag::err_constexpr_local_var_no_init)
905 << isa<CXXConstructorDecl>(Dcl);
906 return false;
907 }
908 }
909 SemaRef.Diag(VD->getLocation(),
Stephen Hines176edba2014-12-01 14:53:08 -0800910 SemaRef.getLangOpts().CPlusPlus14
Richard Smitha10b9782013-04-22 15:31:51 +0000911 ? diag::warn_cxx11_compat_constexpr_local_var
912 : diag::ext_constexpr_local_var)
Richard Smith9f569cc2011-10-01 02:31:28 +0000913 << isa<CXXConstructorDecl>(Dcl);
Richard Smitha10b9782013-04-22 15:31:51 +0000914 continue;
915 }
916
917 case Decl::NamespaceAlias:
918 case Decl::Function:
919 // These are disallowed in C++11 and permitted in C++1y. Allow them
920 // everywhere as an extension.
921 if (!Cxx1yLoc.isValid())
922 Cxx1yLoc = DS->getLocStart();
923 continue;
Richard Smith9f569cc2011-10-01 02:31:28 +0000924
925 default:
926 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
927 << isa<CXXConstructorDecl>(Dcl);
928 return false;
929 }
930 }
931
932 return true;
933}
934
935/// Check that the given field is initialized within a constexpr constructor.
936///
937/// \param Dcl The constexpr constructor being checked.
938/// \param Field The field being checked. This may be a member of an anonymous
939/// struct or union nested within the class being checked.
940/// \param Inits All declarations, including anonymous struct/union members and
941/// indirect members, for which any initialization was provided.
942/// \param Diagnosed Set to true if an error is produced.
943static void CheckConstexprCtorInitializer(Sema &SemaRef,
944 const FunctionDecl *Dcl,
945 FieldDecl *Field,
946 llvm::SmallSet<Decl*, 16> &Inits,
947 bool &Diagnosed) {
Eli Friedman5fb478b2013-06-28 21:07:41 +0000948 if (Field->isInvalidDecl())
949 return;
950
Douglas Gregord61db332011-10-10 17:22:13 +0000951 if (Field->isUnnamedBitfield())
952 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000953
Stephen Hines651f13c2014-04-23 16:59:28 -0700954 // Anonymous unions with no variant members and empty anonymous structs do not
955 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
956 // indirect fields don't need initializing.
Richard Smith30ecfad2012-02-09 06:40:58 +0000957 if (Field->isAnonymousStructOrUnion() &&
Stephen Hines651f13c2014-04-23 16:59:28 -0700958 (Field->getType()->isUnionType()
959 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
960 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith30ecfad2012-02-09 06:40:58 +0000961 return;
962
Richard Smith9f569cc2011-10-01 02:31:28 +0000963 if (!Inits.count(Field)) {
964 if (!Diagnosed) {
965 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
966 Diagnosed = true;
967 }
968 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
969 } else if (Field->isAnonymousStructOrUnion()) {
970 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Stephen Hines651f13c2014-04-23 16:59:28 -0700971 for (auto *I : RD->fields())
Richard Smith9f569cc2011-10-01 02:31:28 +0000972 // If an anonymous union contains an anonymous struct of which any member
973 // is initialized, all members must be initialized.
Stephen Hines651f13c2014-04-23 16:59:28 -0700974 if (!RD->isUnion() || Inits.count(I))
975 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000976 }
977}
978
Richard Smitha10b9782013-04-22 15:31:51 +0000979/// Check the provided statement is allowed in a constexpr function
980/// definition.
981static bool
982CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelme7205c02013-08-10 12:33:24 +0000983 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smitha10b9782013-04-22 15:31:51 +0000984 SourceLocation &Cxx1yLoc) {
985 // - its function-body shall be [...] a compound-statement that contains only
986 switch (S->getStmtClass()) {
987 case Stmt::NullStmtClass:
988 // - null statements,
989 return true;
990
991 case Stmt::DeclStmtClass:
992 // - static_assert-declarations
993 // - using-declarations,
994 // - using-directives,
995 // - typedef declarations and alias-declarations that do not define
996 // classes or enumerations,
997 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
998 return false;
999 return true;
1000
1001 case Stmt::ReturnStmtClass:
1002 // - and exactly one return statement;
1003 if (isa<CXXConstructorDecl>(Dcl)) {
1004 // C++1y allows return statements in constexpr constructors.
1005 if (!Cxx1yLoc.isValid())
1006 Cxx1yLoc = S->getLocStart();
1007 return true;
1008 }
1009
1010 ReturnStmts.push_back(S->getLocStart());
1011 return true;
1012
1013 case Stmt::CompoundStmtClass: {
1014 // C++1y allows compound-statements.
1015 if (!Cxx1yLoc.isValid())
1016 Cxx1yLoc = S->getLocStart();
1017
1018 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Stephen Hines651f13c2014-04-23 16:59:28 -07001019 for (auto *BodyIt : CompStmt->body()) {
1020 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smitha10b9782013-04-22 15:31:51 +00001021 Cxx1yLoc))
1022 return false;
1023 }
1024 return true;
1025 }
1026
1027 case Stmt::AttributedStmtClass:
1028 if (!Cxx1yLoc.isValid())
1029 Cxx1yLoc = S->getLocStart();
1030 return true;
1031
1032 case Stmt::IfStmtClass: {
1033 // C++1y allows if-statements.
1034 if (!Cxx1yLoc.isValid())
1035 Cxx1yLoc = S->getLocStart();
1036
1037 IfStmt *If = cast<IfStmt>(S);
1038 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1039 Cxx1yLoc))
1040 return false;
1041 if (If->getElse() &&
1042 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1043 Cxx1yLoc))
1044 return false;
1045 return true;
1046 }
1047
1048 case Stmt::WhileStmtClass:
1049 case Stmt::DoStmtClass:
1050 case Stmt::ForStmtClass:
1051 case Stmt::CXXForRangeStmtClass:
1052 case Stmt::ContinueStmtClass:
1053 // C++1y allows all of these. We don't allow them as extensions in C++11,
1054 // because they don't make sense without variable mutation.
Stephen Hines176edba2014-12-01 14:53:08 -08001055 if (!SemaRef.getLangOpts().CPlusPlus14)
Richard Smitha10b9782013-04-22 15:31:51 +00001056 break;
1057 if (!Cxx1yLoc.isValid())
1058 Cxx1yLoc = S->getLocStart();
1059 for (Stmt::child_range Children = S->children(); Children; ++Children)
1060 if (*Children &&
1061 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1062 Cxx1yLoc))
1063 return false;
1064 return true;
1065
1066 case Stmt::SwitchStmtClass:
1067 case Stmt::CaseStmtClass:
1068 case Stmt::DefaultStmtClass:
1069 case Stmt::BreakStmtClass:
1070 // C++1y allows switch-statements, and since they don't need variable
1071 // mutation, we can reasonably allow them in C++11 as an extension.
1072 if (!Cxx1yLoc.isValid())
1073 Cxx1yLoc = S->getLocStart();
1074 for (Stmt::child_range Children = S->children(); Children; ++Children)
1075 if (*Children &&
1076 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1077 Cxx1yLoc))
1078 return false;
1079 return true;
1080
1081 default:
1082 if (!isa<Expr>(S))
1083 break;
1084
1085 // C++1y allows expression-statements.
1086 if (!Cxx1yLoc.isValid())
1087 Cxx1yLoc = S->getLocStart();
1088 return true;
1089 }
1090
1091 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1092 << isa<CXXConstructorDecl>(Dcl);
1093 return false;
1094}
1095
Richard Smith9f569cc2011-10-01 02:31:28 +00001096/// Check the body for the given constexpr function declaration only contains
1097/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1098///
1099/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +00001100bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001101 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +00001102 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +00001103 // The definition of a constexpr function shall satisfy the following
1104 // constraints: [...]
1105 // - its function-body shall be = delete, = default, or a
1106 // compound-statement
1107 //
Richard Smith5ba73e12012-02-04 00:33:54 +00001108 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +00001109 // In the definition of a constexpr constructor, [...]
1110 // - its function-body shall not be a function-try-block;
1111 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1112 << isa<CXXConstructorDecl>(Dcl);
1113 return false;
1114 }
1115
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001116 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smitha10b9782013-04-22 15:31:51 +00001117
1118 // - its function-body shall be [...] a compound-statement that contains only
1119 // [... list of cases ...]
1120 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1121 SourceLocation Cxx1yLoc;
Stephen Hines651f13c2014-04-23 16:59:28 -07001122 for (auto *BodyIt : CompBody->body()) {
1123 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smitha10b9782013-04-22 15:31:51 +00001124 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +00001125 }
1126
Richard Smitha10b9782013-04-22 15:31:51 +00001127 if (Cxx1yLoc.isValid())
1128 Diag(Cxx1yLoc,
Stephen Hines176edba2014-12-01 14:53:08 -08001129 getLangOpts().CPlusPlus14
Richard Smitha10b9782013-04-22 15:31:51 +00001130 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1131 : diag::ext_constexpr_body_invalid_stmt)
1132 << isa<CXXConstructorDecl>(Dcl);
1133
Richard Smith9f569cc2011-10-01 02:31:28 +00001134 if (const CXXConstructorDecl *Constructor
1135 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1136 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +00001137 // DR1359:
1138 // - every non-variant non-static data member and base class sub-object
1139 // shall be initialized;
Stephen Hines651f13c2014-04-23 16:59:28 -07001140 // DR1460:
1141 // - if the class is a union having variant members, exactly one of them
Richard Smith30ecfad2012-02-09 06:40:58 +00001142 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +00001143 if (RD->isUnion()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001144 if (Constructor->getNumCtorInitializers() == 0 &&
1145 RD->hasVariantMembers()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001146 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1147 return false;
1148 }
Richard Smith6e433752011-10-10 16:38:04 +00001149 } else if (!Constructor->isDependentContext() &&
1150 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001151 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1152
1153 // Skip detailed checking if we have enough initializers, and we would
1154 // allow at most one initializer per member.
1155 bool AnyAnonStructUnionMembers = false;
1156 unsigned Fields = 0;
1157 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1158 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +00001159 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001160 AnyAnonStructUnionMembers = true;
1161 break;
1162 }
1163 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001164 // DR1460:
1165 // - if the class is a union-like class, but is not a union, for each of
1166 // its anonymous union members having variant members, exactly one of
1167 // them shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +00001168 if (AnyAnonStructUnionMembers ||
1169 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1170 // Check initialization of non-static data members. Base classes are
1171 // always initialized so do not need to be checked. Dependent bases
1172 // might not have initializers in the member initializer list.
1173 llvm::SmallSet<Decl*, 16> Inits;
Stephen Hines651f13c2014-04-23 16:59:28 -07001174 for (const auto *I: Constructor->inits()) {
1175 if (FieldDecl *FD = I->getMember())
Richard Smith9f569cc2011-10-01 02:31:28 +00001176 Inits.insert(FD);
Stephen Hines651f13c2014-04-23 16:59:28 -07001177 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smith9f569cc2011-10-01 02:31:28 +00001178 Inits.insert(ID->chain_begin(), ID->chain_end());
1179 }
1180
1181 bool Diagnosed = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07001182 for (auto *I : RD->fields())
1183 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +00001184 if (Diagnosed)
1185 return false;
1186 }
1187 }
Richard Smith9f569cc2011-10-01 02:31:28 +00001188 } else {
1189 if (ReturnStmts.empty()) {
Richard Smitha10b9782013-04-22 15:31:51 +00001190 // C++1y doesn't require constexpr functions to contain a 'return'
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001191 // statement. We still do, unless the return type might be void, because
Richard Smitha10b9782013-04-22 15:31:51 +00001192 // otherwise if there's no return statement, the function cannot
1193 // be used in a core constant expression.
Stephen Hines176edba2014-12-01 14:53:08 -08001194 bool OK = getLangOpts().CPlusPlus14 &&
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001195 (Dcl->getReturnType()->isVoidType() ||
1196 Dcl->getReturnType()->isDependentType());
Richard Smitha10b9782013-04-22 15:31:51 +00001197 Diag(Dcl->getLocation(),
Richard Smithbebf5b12013-04-26 14:36:30 +00001198 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1199 : diag::err_constexpr_body_no_return);
1200 return OK;
Richard Smith9f569cc2011-10-01 02:31:28 +00001201 }
1202 if (ReturnStmts.size() > 1) {
Richard Smitha10b9782013-04-22 15:31:51 +00001203 Diag(ReturnStmts.back(),
Stephen Hines176edba2014-12-01 14:53:08 -08001204 getLangOpts().CPlusPlus14
Richard Smitha10b9782013-04-22 15:31:51 +00001205 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1206 : diag::ext_constexpr_body_multiple_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001207 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1208 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001209 }
1210 }
1211
Richard Smith5ba73e12012-02-04 00:33:54 +00001212 // C++11 [dcl.constexpr]p5:
1213 // if no function argument values exist such that the function invocation
1214 // substitution would produce a constant expression, the program is
1215 // ill-formed; no diagnostic required.
1216 // C++11 [dcl.constexpr]p3:
1217 // - every constructor call and implicit conversion used in initializing the
1218 // return value shall be one of those allowed in a constant expression.
1219 // C++11 [dcl.constexpr]p4:
1220 // - every constructor involved in initializing non-static data members and
1221 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001222 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +00001223 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +00001224 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +00001225 << isa<CXXConstructorDecl>(Dcl);
1226 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1227 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001228 // Don't return false here: we allow this for compatibility in
1229 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001230 }
1231
Richard Smith9f569cc2011-10-01 02:31:28 +00001232 return true;
1233}
1234
Douglas Gregorb48fe382008-10-31 09:07:45 +00001235/// isCurrentClassName - Determine whether the identifier II is the
1236/// name of the class type currently being defined. In the case of
1237/// nested classes, this will only return true if II is the name of
1238/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001239bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1240 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001241 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001242
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001243 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001244 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001245 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001246 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1247 } else
1248 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1249
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001250 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001251 return &II == CurDecl->getIdentifier();
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00001252 return false;
Douglas Gregorb48fe382008-10-31 09:07:45 +00001253}
1254
Richard Smithb79b17b2013-10-15 00:00:26 +00001255/// \brief Determine whether the identifier II is a typo for the name of
1256/// the class type currently being defined. If so, update it to the identifier
1257/// that should have been used.
1258bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1259 assert(getLangOpts().CPlusPlus && "No class names in C!");
1260
1261 if (!getLangOpts().SpellChecking)
1262 return false;
1263
1264 CXXRecordDecl *CurDecl;
1265 if (SS && SS->isSet() && !SS->isInvalid()) {
1266 DeclContext *DC = computeDeclContext(*SS, true);
1267 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1268 } else
1269 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1270
1271 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1272 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1273 < II->getLength()) {
1274 II = CurDecl->getIdentifier();
1275 return true;
1276 }
1277
1278 return false;
1279}
1280
Douglas Gregor229d47a2012-11-10 07:24:09 +00001281/// \brief Determine whether the given class is a base class of the given
1282/// class, including looking at dependent bases.
1283static bool findCircularInheritance(const CXXRecordDecl *Class,
1284 const CXXRecordDecl *Current) {
1285 SmallVector<const CXXRecordDecl*, 8> Queue;
1286
1287 Class = Class->getCanonicalDecl();
1288 while (true) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001289 for (const auto &I : Current->bases()) {
1290 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregor229d47a2012-11-10 07:24:09 +00001291 if (!Base)
1292 continue;
1293
1294 Base = Base->getDefinition();
1295 if (!Base)
1296 continue;
1297
1298 if (Base->getCanonicalDecl() == Class)
1299 return true;
1300
1301 Queue.push_back(Base);
1302 }
1303
1304 if (Queue.empty())
1305 return false;
1306
Robert Wilhelm344472e2013-08-23 16:11:15 +00001307 Current = Queue.pop_back_val();
Douglas Gregor229d47a2012-11-10 07:24:09 +00001308 }
1309
1310 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001311}
1312
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001313/// \brief Perform propagation of DLL attributes from a derived class to a
1314/// templated base class for MS compatibility.
1315static void propagateDLLAttrToBaseClassTemplate(
1316 Sema &S, CXXRecordDecl *Class, Attr *ClassAttr,
1317 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
1318 if (getDLLAttr(
1319 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
1320 // If the base class template has a DLL attribute, don't try to change it.
1321 return;
1322 }
1323
1324 if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
1325 // If the base class is not already specialized, we can do the propagation.
1326 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
1327 NewAttr->setInherited(true);
1328 BaseTemplateSpec->addAttr(NewAttr);
1329 return;
1330 }
1331
1332 bool DifferentAttribute = false;
1333 if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) {
1334 if (!SpecializationAttr->isInherited()) {
1335 // The template has previously been specialized or instantiated with an
1336 // explicit attribute. We should not try to change it.
1337 return;
1338 }
1339 if (SpecializationAttr->getKind() == ClassAttr->getKind()) {
1340 // The specialization already has the right attribute.
1341 return;
1342 }
1343 DifferentAttribute = true;
1344 }
1345
1346 // The template was previously instantiated or explicitly specialized without
1347 // a dll attribute, or the template was previously instantiated with a
1348 // different inherited attribute. It's too late for us to change the
1349 // attribute, so warn that this is unsupported.
1350 S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
1351 << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute;
1352 S.Diag(ClassAttr->getLocation(), diag::note_attribute);
1353 if (BaseTemplateSpec->isExplicitSpecialization()) {
1354 S.Diag(BaseTemplateSpec->getLocation(),
1355 diag::note_template_class_explicit_specialization_was_here)
1356 << BaseTemplateSpec;
1357 } else {
1358 S.Diag(BaseTemplateSpec->getPointOfInstantiation(),
1359 diag::note_template_class_instantiation_was_here)
1360 << BaseTemplateSpec;
1361 }
1362}
1363
Mike Stump1eb44332009-09-09 15:08:12 +00001364/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001365///
1366/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1367/// and returns NULL otherwise.
1368CXXBaseSpecifier *
1369Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1370 SourceRange SpecifierRange,
1371 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001372 TypeSourceInfo *TInfo,
1373 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001374 QualType BaseType = TInfo->getType();
1375
Douglas Gregor2943aed2009-03-03 04:44:36 +00001376 // C++ [class.union]p1:
1377 // A union shall not have base classes.
1378 if (Class->isUnion()) {
1379 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1380 << SpecifierRange;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001381 return nullptr;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001382 }
1383
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001384 if (EllipsisLoc.isValid() &&
1385 !TInfo->getType()->containsUnexpandedParameterPack()) {
1386 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1387 << TInfo->getTypeLoc().getSourceRange();
1388 EllipsisLoc = SourceLocation();
1389 }
Douglas Gregord777e282012-11-10 01:18:17 +00001390
1391 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1392
1393 if (BaseType->isDependentType()) {
1394 // Make sure that we don't have circular inheritance among our dependent
1395 // bases. For non-dependent bases, the check for completeness below handles
1396 // this.
1397 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1398 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1399 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001400 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001401 Diag(BaseLoc, diag::err_circular_inheritance)
1402 << BaseType << Context.getTypeDeclType(Class);
1403
1404 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1405 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1406 << BaseType;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001407
1408 return nullptr;
Douglas Gregord777e282012-11-10 01:18:17 +00001409 }
1410 }
1411
Mike Stump1eb44332009-09-09 15:08:12 +00001412 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001413 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001414 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001415 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001416
1417 // Base specifiers must be record types.
1418 if (!BaseType->isRecordType()) {
1419 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001420 return nullptr;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001421 }
1422
1423 // C++ [class.union]p1:
1424 // A union shall not be used as a base class.
1425 if (BaseType->isUnionType()) {
1426 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001427 return nullptr;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001428 }
1429
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001430 // For the MS ABI, propagate DLL attributes to base class templates.
1431 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1432 if (Attr *ClassAttr = getDLLAttr(Class)) {
1433 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1434 BaseType->getAsCXXRecordDecl())) {
1435 propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr,
1436 BaseTemplate, BaseLoc);
1437 }
1438 }
1439 }
1440
Douglas Gregor2943aed2009-03-03 04:44:36 +00001441 // C++ [class.derived]p2:
1442 // The class-name in a base-specifier shall not be an incompletely
1443 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001444 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001445 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001446 Class->setInvalidDecl();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001447 return nullptr;
John McCall572fc622010-08-17 07:23:57 +00001448 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001449
Eli Friedman1d954f62009-08-15 21:55:26 +00001450 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001451 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001452 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001453 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001454 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer2f686692013-06-22 06:43:58 +00001455 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedman1d954f62009-08-15 21:55:26 +00001456 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001457
David Majnemer28165b72013-11-02 12:00:36 +00001458 // A class which contains a flexible array member is not suitable for use as a
1459 // base class:
1460 // - If the layout determines that a base comes before another base,
1461 // the flexible array member would index into the subsequent base.
1462 // - If the layout determines that base comes before the derived class,
1463 // the flexible array member would index into the derived class.
1464 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1465 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1466 << CXXBaseDecl->getDeclName();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001467 return nullptr;
David Majnemer28165b72013-11-02 12:00:36 +00001468 }
1469
Anders Carlsson1d209272011-03-25 14:55:14 +00001470 // C++ [class]p3:
David Majnemer7041fcc2013-11-02 11:24:41 +00001471 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson1d209272011-03-25 14:55:14 +00001472 // base-clause, the program is ill-formed.
David Majnemer7121bdb2013-10-18 00:33:31 +00001473 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer7041fcc2013-11-02 11:24:41 +00001474 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemer7121bdb2013-10-18 00:33:31 +00001475 << CXXBaseDecl->getDeclName()
1476 << FA->isSpelledAsSealed();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001477 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1478 << CXXBaseDecl->getDeclName() << FA->getRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001479 return nullptr;
Anders Carlssondfc2f102011-01-22 17:51:53 +00001480 }
1481
John McCall572fc622010-08-17 07:23:57 +00001482 if (BaseDecl->isInvalidDecl())
1483 Class->setInvalidDecl();
David Majnemer7041fcc2013-11-02 11:24:41 +00001484
Anders Carlsson51f94042009-12-03 17:49:57 +00001485 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001486 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001487 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001488 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001489}
1490
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001491/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1492/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001493/// example:
1494/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001495/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001496BaseResult
John McCalld226f652010-08-21 09:40:31 +00001497Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001498 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001499 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001500 ParsedType basetype, SourceLocation BaseLoc,
1501 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001502 if (!classdecl)
1503 return true;
1504
Douglas Gregor40808ce2009-03-09 23:48:35 +00001505 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001506 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001507 if (!Class)
1508 return true;
1509
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001510 // We haven't yet attached the base specifiers.
1511 Class->setIsParsingBaseSpecifiers();
1512
Richard Smith05321402013-02-19 23:47:15 +00001513 // We do not support any C++11 attributes on base-specifiers yet.
1514 // Diagnose any attributes we see.
1515 if (!Attributes.empty()) {
1516 for (AttributeList *Attr = Attributes.getList(); Attr;
1517 Attr = Attr->getNext()) {
1518 if (Attr->isInvalid() ||
1519 Attr->getKind() == AttributeList::IgnoredAttribute)
1520 continue;
1521 Diag(Attr->getLoc(),
1522 Attr->getKind() == AttributeList::UnknownAttribute
1523 ? diag::warn_unknown_attribute_ignored
1524 : diag::err_base_specifier_attribute)
1525 << Attr->getName();
1526 }
1527 }
1528
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001529 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky56062202010-07-26 16:56:01 +00001530 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001531
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001532 if (EllipsisLoc.isInvalid() &&
1533 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001534 UPPC_BaseType))
1535 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001536
Douglas Gregor2943aed2009-03-03 04:44:36 +00001537 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001538 Virtual, Access, TInfo,
1539 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001540 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001541 else
1542 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001543
Douglas Gregor2943aed2009-03-03 04:44:36 +00001544 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001545}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001546
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001547/// Use small set to collect indirect bases. As this is only used
1548/// locally, there's no need to abstract the small size parameter.
1549typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
1550
1551/// \brief Recursively add the bases of Type. Don't add Type itself.
1552static void
1553NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
1554 const QualType &Type)
1555{
1556 // Even though the incoming type is a base, it might not be
1557 // a class -- it could be a template parm, for instance.
1558 if (auto Rec = Type->getAs<RecordType>()) {
1559 auto Decl = Rec->getAsCXXRecordDecl();
1560
1561 // Iterate over its bases.
1562 for (const auto &BaseSpec : Decl->bases()) {
1563 QualType Base = Context.getCanonicalType(BaseSpec.getType())
1564 .getUnqualifiedType();
1565 if (Set.insert(Base).second)
1566 // If we've not already seen it, recurse.
1567 NoteIndirectBases(Context, Set, Base);
1568 }
1569 }
1570}
1571
Douglas Gregor2943aed2009-03-03 04:44:36 +00001572/// \brief Performs the actual work of attaching the given base class
1573/// specifiers to a C++ class.
1574bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1575 unsigned NumBases) {
1576 if (NumBases == 0)
1577 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001578
1579 // Used to keep track of which base types we have already seen, so
1580 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001581 // that the key is always the unqualified canonical type of the base
1582 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001583 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1584
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001585 // Used to track indirect bases so we can see if a direct base is
1586 // ambiguous.
1587 IndirectBaseSet IndirectBaseTypes;
1588
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001589 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001590 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001591 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001592 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001593 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001594 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001595 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001596
1597 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1598 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001599 // C++ [class.mi]p3:
1600 // A class shall not be specified as a direct base class of a
1601 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001602 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001603 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001604 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001605 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001606
1607 // Delete the duplicate base class specifier; we're going to
1608 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001609 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001610
1611 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001612 } else {
1613 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001614 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001615 Bases[NumGoodBases++] = Bases[idx];
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001616
1617 // Note this base's direct & indirect bases, if there could be ambiguity.
1618 if (NumBases > 1)
1619 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
1620
John McCalle402e722012-09-25 07:32:39 +00001621 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1622 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1623 if (Class->isInterface() &&
1624 (!RD->isInterface() ||
1625 KnownBase->getAccessSpecifier() != AS_public)) {
1626 // The Microsoft extension __interface does not permit bases that
1627 // are not themselves public interfaces.
1628 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1629 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1630 << RD->getSourceRange();
1631 Invalid = true;
1632 }
1633 if (RD->hasAttr<WeakAttr>())
Stephen Hines651f13c2014-04-23 16:59:28 -07001634 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalle402e722012-09-25 07:32:39 +00001635 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001636 }
1637 }
1638
1639 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001640 Class->setBases(Bases, NumGoodBases);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001641
1642 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
1643 // Check whether this direct base is inaccessible due to ambiguity.
1644 QualType BaseType = Bases[idx]->getType();
1645 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
1646 .getUnqualifiedType();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001647
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001648 if (IndirectBaseTypes.count(CanonicalBase)) {
1649 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1650 /*DetectVirtual=*/true);
1651 bool found
1652 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
1653 assert(found);
1654 (void)found;
1655
1656 if (Paths.isAmbiguous(CanonicalBase))
1657 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
1658 << BaseType << getAmbiguousPathsDisplayString(Paths)
1659 << Bases[idx]->getSourceRange();
1660 else
1661 assert(Bases[idx]->isVirtual());
1662 }
1663
1664 // Delete the base class specifier, since its data has been copied
1665 // into the CXXRecordDecl.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001666 Context.Deallocate(Bases[idx]);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001667 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001668
1669 return Invalid;
1670}
1671
1672/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1673/// class, after checking whether there are any duplicate base
1674/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001675void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001676 unsigned NumBases) {
1677 if (!ClassDecl || !Bases || !NumBases)
1678 return;
1679
1680 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelm0d317a02013-07-22 05:04:01 +00001681 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001682}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001683
Douglas Gregora8f32e02009-10-06 17:59:45 +00001684/// \brief Determine whether the type \p Derived is a C++ class that is
1685/// derived from the type \p Base.
1686bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001687 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001688 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001689
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001690 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001691 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001692 return false;
1693
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001694 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001695 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001696 return false;
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001697
1698 // If either the base or the derived type is invalid, don't try to
1699 // check whether one is derived from the other.
1700 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1701 return false;
1702
John McCall86ff3082010-02-04 22:26:26 +00001703 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1704 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001705}
1706
1707/// \brief Determine whether the type \p Derived is a C++ class that is
1708/// derived from the type \p Base.
1709bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001710 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001711 return false;
1712
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001713 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001714 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001715 return false;
1716
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001717 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001718 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001719 return false;
1720
Douglas Gregora8f32e02009-10-06 17:59:45 +00001721 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1722}
1723
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001724void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001725 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001726 assert(BasePathArray.empty() && "Base path array must be empty!");
1727 assert(Paths.isRecordingPaths() && "Must record paths!");
1728
1729 const CXXBasePath &Path = Paths.front();
1730
1731 // We first go backward and check if we have a virtual base.
1732 // FIXME: It would be better if CXXBasePath had the base specifier for
1733 // the nearest virtual base.
1734 unsigned Start = 0;
1735 for (unsigned I = Path.size(); I != 0; --I) {
1736 if (Path[I - 1].Base->isVirtual()) {
1737 Start = I - 1;
1738 break;
1739 }
1740 }
1741
1742 // Now add all bases.
1743 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001744 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001745}
1746
Douglas Gregora8f32e02009-10-06 17:59:45 +00001747/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1748/// conversion (where Derived and Base are class types) is
1749/// well-formed, meaning that the conversion is unambiguous (and
1750/// that all of the base classes are accessible). Returns true
1751/// and emits a diagnostic if the code is ill-formed, returns false
1752/// otherwise. Loc is the location where this routine should point to
1753/// if there is an error, and Range is the source range to highlight
1754/// if there is an error.
1755bool
1756Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001757 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001758 unsigned AmbigiousBaseConvID,
1759 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001760 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001761 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001762 // First, determine whether the path from Derived to Base is
1763 // ambiguous. This is slightly more expensive than checking whether
1764 // the Derived to Base conversion exists, because here we need to
1765 // explore multiple paths to determine if there is an ambiguity.
1766 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1767 /*DetectVirtual=*/false);
1768 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1769 assert(DerivationOkay &&
1770 "Can only be used with a derived-to-base conversion");
1771 (void)DerivationOkay;
1772
1773 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001774 if (InaccessibleBaseID) {
1775 // Check that the base class can be accessed.
1776 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1777 InaccessibleBaseID)) {
1778 case AR_inaccessible:
1779 return true;
1780 case AR_accessible:
1781 case AR_dependent:
1782 case AR_delayed:
1783 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001784 }
John McCall6b2accb2010-02-10 09:31:12 +00001785 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001786
1787 // Build a base path if necessary.
1788 if (BasePath)
1789 BuildBasePathArray(Paths, *BasePath);
1790 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001791 }
1792
David Majnemer2f686692013-06-22 06:43:58 +00001793 if (AmbigiousBaseConvID) {
1794 // We know that the derived-to-base conversion is ambiguous, and
1795 // we're going to produce a diagnostic. Perform the derived-to-base
1796 // search just one more time to compute all of the possible paths so
1797 // that we can print them out. This is more expensive than any of
1798 // the previous derived-to-base checks we've done, but at this point
1799 // performance isn't as much of an issue.
1800 Paths.clear();
1801 Paths.setRecordingPaths(true);
1802 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1803 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1804 (void)StillOkay;
1805
1806 // Build up a textual representation of the ambiguous paths, e.g.,
1807 // D -> B -> A, that will be used to illustrate the ambiguous
1808 // conversions in the diagnostic. We only print one of the paths
1809 // to each base class subobject.
1810 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1811
1812 Diag(Loc, AmbigiousBaseConvID)
1813 << Derived << Base << PathDisplayStr << Range << Name;
1814 }
Douglas Gregora8f32e02009-10-06 17:59:45 +00001815 return true;
1816}
1817
1818bool
1819Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001820 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001821 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001822 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001823 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001824 IgnoreAccess ? 0
1825 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001826 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001827 Loc, Range, DeclarationName(),
1828 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001829}
1830
1831
1832/// @brief Builds a string representing ambiguous paths from a
1833/// specific derived class to different subobjects of the same base
1834/// class.
1835///
1836/// This function builds a string that can be used in error messages
1837/// to show the different paths that one can take through the
1838/// inheritance hierarchy to go from the derived class to different
1839/// subobjects of a base class. The result looks something like this:
1840/// @code
1841/// struct D -> struct B -> struct A
1842/// struct D -> struct C -> struct A
1843/// @endcode
1844std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1845 std::string PathDisplayStr;
1846 std::set<unsigned> DisplayedPaths;
1847 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1848 Path != Paths.end(); ++Path) {
1849 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1850 // We haven't displayed a path to this particular base
1851 // class subobject yet.
1852 PathDisplayStr += "\n ";
1853 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1854 for (CXXBasePath::const_iterator Element = Path->begin();
1855 Element != Path->end(); ++Element)
1856 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1857 }
1858 }
1859
1860 return PathDisplayStr;
1861}
1862
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001863//===----------------------------------------------------------------------===//
1864// C++ class member Handling
1865//===----------------------------------------------------------------------===//
1866
Abramo Bagnara6206d532010-06-05 05:09:32 +00001867/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001868bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1869 SourceLocation ASLoc,
1870 SourceLocation ColonLoc,
1871 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001872 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001873 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001874 ASLoc, ColonLoc);
1875 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001876 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001877}
1878
Richard Smitha4b39652012-08-06 03:25:17 +00001879/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmandae92712013-09-05 23:51:03 +00001880void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001881 if (D->isInvalidDecl())
1882 return;
1883
Eli Friedmandae92712013-09-05 23:51:03 +00001884 // We only care about "override" and "final" declarations.
1885 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1886 return;
Anders Carlsson9e682d92011-01-20 05:57:14 +00001887
Eli Friedmandae92712013-09-05 23:51:03 +00001888 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001889
Eli Friedmandae92712013-09-05 23:51:03 +00001890 // We can't check dependent instance methods.
1891 if (MD && MD->isInstance() &&
1892 (MD->getParent()->hasAnyDependentBases() ||
1893 MD->getType()->isDependentType()))
1894 return;
1895
1896 if (MD && !MD->isVirtual()) {
1897 // If we have a non-virtual method, check if if hides a virtual method.
1898 // (In that case, it's most likely the method has the wrong type.)
1899 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1900 FindHiddenVirtualMethods(MD, OverloadedMethods);
1901
1902 if (!OverloadedMethods.empty()) {
Richard Smitha4b39652012-08-06 03:25:17 +00001903 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1904 Diag(OA->getLocation(),
Eli Friedmandae92712013-09-05 23:51:03 +00001905 diag::override_keyword_hides_virtual_member_function)
1906 << "override" << (OverloadedMethods.size() > 1);
1907 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smitha4b39652012-08-06 03:25:17 +00001908 Diag(FA->getLocation(),
Eli Friedmandae92712013-09-05 23:51:03 +00001909 diag::override_keyword_hides_virtual_member_function)
David Majnemer7121bdb2013-10-18 00:33:31 +00001910 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1911 << (OverloadedMethods.size() > 1);
Richard Smitha4b39652012-08-06 03:25:17 +00001912 }
Eli Friedmandae92712013-09-05 23:51:03 +00001913 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1914 MD->setInvalidDecl();
1915 return;
1916 }
1917 // Fall through into the general case diagnostic.
1918 // FIXME: We might want to attempt typo correction here.
1919 }
1920
1921 if (!MD || !MD->isVirtual()) {
1922 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1923 Diag(OA->getLocation(),
1924 diag::override_keyword_only_allowed_on_virtual_member_functions)
1925 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1926 D->dropAttr<OverrideAttr>();
1927 }
1928 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1929 Diag(FA->getLocation(),
1930 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemer7121bdb2013-10-18 00:33:31 +00001931 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1932 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmandae92712013-09-05 23:51:03 +00001933 D->dropAttr<FinalAttr>();
Richard Smitha4b39652012-08-06 03:25:17 +00001934 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001935 return;
1936 }
Richard Smitha4b39652012-08-06 03:25:17 +00001937
Richard Smitha4b39652012-08-06 03:25:17 +00001938 // C++11 [class.virtual]p5:
Stephen Hines176edba2014-12-01 14:53:08 -08001939 // If a function is marked with the virt-specifier override and
Richard Smitha4b39652012-08-06 03:25:17 +00001940 // does not override a member function of a base class, the program is
1941 // ill-formed.
1942 bool HasOverriddenMethods =
1943 MD->begin_overridden_methods() != MD->end_overridden_methods();
1944 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1945 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1946 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001947}
1948
Stephen Hines176edba2014-12-01 14:53:08 -08001949void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
1950 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
1951 return;
1952 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1953 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
1954 isa<CXXDestructorDecl>(MD))
1955 return;
1956
1957 SourceLocation Loc = MD->getLocation();
1958 SourceLocation SpellingLoc = Loc;
1959 if (getSourceManager().isMacroArgExpansion(Loc))
1960 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
1961 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
1962 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
1963 return;
1964
1965 if (MD->size_overridden_methods() > 0) {
1966 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
1967 << MD->getDeclName();
1968 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
1969 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
1970 }
1971}
1972
Richard Smitha4b39652012-08-06 03:25:17 +00001973/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001974/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001975/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001976bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1977 const CXXMethodDecl *Old) {
David Majnemer7121bdb2013-10-18 00:33:31 +00001978 FinalAttr *FA = Old->getAttr<FinalAttr>();
1979 if (!FA)
Anders Carlssonf89e0422011-01-23 21:07:30 +00001980 return false;
1981
1982 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemer7121bdb2013-10-18 00:33:31 +00001983 << New->getDeclName()
1984 << FA->isSpelledAsSealed();
Anders Carlssonf89e0422011-01-23 21:07:30 +00001985 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1986 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001987}
1988
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001989static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001990 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1991 // FIXME: Destruction of ObjC lifetime types has side-effects.
1992 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1993 return !RD->isCompleteDefinition() ||
1994 !RD->hasTrivialDefaultConstructor() ||
1995 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001996 return false;
1997}
1998
John McCall76da55d2013-04-16 07:28:30 +00001999static AttributeList *getMSPropertyAttr(AttributeList *list) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002000 for (AttributeList *it = list; it != nullptr; it = it->getNext())
John McCall76da55d2013-04-16 07:28:30 +00002001 if (it->isDeclspecPropertyAttribute())
2002 return it;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002003 return nullptr;
John McCall76da55d2013-04-16 07:28:30 +00002004}
2005
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002006/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2007/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00002008/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00002009/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2010/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00002011NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002012Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00002013 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00002014 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00002015 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002016 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00002017 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2018 DeclarationName Name = NameInfo.getName();
2019 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00002020
2021 // For anonymous bitfields, the location should point to the type.
2022 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00002023 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00002024
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002025 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002026
John McCall4bde1e12010-06-04 08:34:12 +00002027 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00002028 assert(!DS.isFriendSpecified());
2029
Richard Smith1ab0d902011-06-25 02:28:38 +00002030 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00002031
John McCalle402e722012-09-25 07:32:39 +00002032 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2033 // The Microsoft extension __interface only permits public member functions
2034 // and prohibits constructors, destructors, operators, non-public member
2035 // functions, static methods and data members.
2036 unsigned InvalidDecl;
2037 bool ShowDeclName = true;
2038 if (!isFunc)
2039 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2040 else if (AS != AS_public)
2041 InvalidDecl = 2;
2042 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2043 InvalidDecl = 3;
2044 else switch (Name.getNameKind()) {
2045 case DeclarationName::CXXConstructorName:
2046 InvalidDecl = 4;
2047 ShowDeclName = false;
2048 break;
2049
2050 case DeclarationName::CXXDestructorName:
2051 InvalidDecl = 5;
2052 ShowDeclName = false;
2053 break;
2054
2055 case DeclarationName::CXXOperatorName:
2056 case DeclarationName::CXXConversionFunctionName:
2057 InvalidDecl = 6;
2058 break;
2059
2060 default:
2061 InvalidDecl = 0;
2062 break;
2063 }
2064
2065 if (InvalidDecl) {
2066 if (ShowDeclName)
2067 Diag(Loc, diag::err_invalid_member_in_interface)
2068 << (InvalidDecl-1) << Name;
2069 else
2070 Diag(Loc, diag::err_invalid_member_in_interface)
2071 << (InvalidDecl-1) << "";
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002072 return nullptr;
John McCalle402e722012-09-25 07:32:39 +00002073 }
2074 }
2075
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002076 // C++ 9.2p6: A member shall not be declared to have automatic storage
2077 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00002078 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2079 // data members and cannot be applied to names declared const or static,
2080 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002081 switch (DS.getStorageClassSpec()) {
Richard Smithec642442013-04-12 22:46:28 +00002082 case DeclSpec::SCS_unspecified:
2083 case DeclSpec::SCS_typedef:
2084 case DeclSpec::SCS_static:
2085 break;
2086 case DeclSpec::SCS_mutable:
2087 if (isFunc) {
2088 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00002089
Richard Smithec642442013-04-12 22:46:28 +00002090 // FIXME: It would be nicer if the keyword was ignored only for this
2091 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002092 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithec642442013-04-12 22:46:28 +00002093 }
2094 break;
2095 default:
2096 Diag(DS.getStorageClassSpecLoc(),
2097 diag::err_storageclass_invalid_for_member);
2098 D.getMutableDeclSpec().ClearStorageClassSpecs();
2099 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002100 }
2101
Sebastian Redl669d5d72008-11-14 23:42:31 +00002102 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2103 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00002104 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002105
David Blaikie1d87fba2013-01-30 01:22:18 +00002106 if (DS.isConstexprSpecified() && isInstField) {
2107 SemaDiagnosticBuilder B =
2108 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2109 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2110 if (InitStyle == ICIS_NoInit) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002111 B << 0 << 0;
2112 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2113 B << FixItHint::CreateRemoval(ConstexprLoc);
2114 else {
2115 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2116 D.getMutableDeclSpec().ClearConstexprSpec();
2117 const char *PrevSpec;
2118 unsigned DiagID;
2119 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2120 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2121 (void)Failed;
2122 assert(!Failed && "Making a constexpr member const shouldn't fail");
2123 }
David Blaikie1d87fba2013-01-30 01:22:18 +00002124 } else {
2125 B << 1;
2126 const char *PrevSpec;
2127 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00002128 if (D.getMutableDeclSpec().SetStorageClassSpec(
Stephen Hines651f13c2014-04-23 16:59:28 -07002129 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2130 Context.getPrintingPolicy())) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00002131 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00002132 "This is the only DeclSpec that should fail to be applied");
2133 B << 1;
2134 } else {
2135 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2136 isInstField = false;
2137 }
2138 }
2139 }
2140
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00002141 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00002142 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00002143 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00002144
2145 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00002146 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00002147 Diag(Loc, diag::err_bad_variable_name)
2148 << Name;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002149 return nullptr;
Douglas Gregorb5a01872011-10-09 18:55:59 +00002150 }
Douglas Gregorf2503652011-09-21 14:40:46 +00002151
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00002152 IdentifierInfo *II = Name.getAsIdentifierInfo();
2153
Douglas Gregorf2503652011-09-21 14:40:46 +00002154 // Member field could not be with "template" keyword.
2155 // So TemplateParameterLists should be empty in this case.
2156 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002157 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00002158 if (TemplateParams->size()) {
2159 // There is no such thing as a member field template.
2160 Diag(D.getIdentifierLoc(), diag::err_template_member)
2161 << II
2162 << SourceRange(TemplateParams->getTemplateLoc(),
2163 TemplateParams->getRAngleLoc());
2164 } else {
2165 // There is an extraneous 'template<>' for this member.
2166 Diag(TemplateParams->getTemplateLoc(),
2167 diag::err_template_member_noparams)
2168 << II
2169 << SourceRange(TemplateParams->getTemplateLoc(),
2170 TemplateParams->getRAngleLoc());
2171 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002172 return nullptr;
Douglas Gregorf2503652011-09-21 14:40:46 +00002173 }
2174
Douglas Gregor922fff22010-10-13 22:19:53 +00002175 if (SS.isSet() && !SS.isInvalid()) {
2176 // The user provided a superfluous scope specifier inside a class
2177 // definition:
2178 //
2179 // class X {
2180 // int X::member;
2181 // };
Douglas Gregor69605872012-03-28 16:01:27 +00002182 if (DeclContext *DC = computeDeclContext(SS, false))
2183 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00002184 else
2185 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2186 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00002187
Douglas Gregor922fff22010-10-13 22:19:53 +00002188 SS.clear();
2189 }
Douglas Gregorf2503652011-09-21 14:40:46 +00002190
John McCall76da55d2013-04-16 07:28:30 +00002191 AttributeList *MSPropertyAttr =
2192 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanb26f0122013-06-28 20:48:34 +00002193 if (MSPropertyAttr) {
2194 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2195 BitWidth, InitStyle, AS, MSPropertyAttr);
2196 if (!Member)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002197 return nullptr;
Eli Friedmanb26f0122013-06-28 20:48:34 +00002198 isInstField = false;
2199 } else {
2200 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2201 BitWidth, InitStyle, AS);
2202 assert(Member && "HandleField never returns null");
2203 }
2204 } else {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002205 assert(InitStyle == ICIS_NoInit ||
2206 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
Eli Friedmanb26f0122013-06-28 20:48:34 +00002207
2208 Member = HandleDeclarator(S, D, TemplateParameterLists);
2209 if (!Member)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002210 return nullptr;
Eli Friedmanb26f0122013-06-28 20:48:34 +00002211
2212 // Non-instance-fields can't have a bitfield.
2213 if (BitWidth) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00002214 if (Member->isInvalidDecl()) {
2215 // don't emit another diagnostic.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002216 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00002217 // C++ 9.6p3: A bit-field shall not be a static member.
2218 // "static member 'A' cannot be a bit-field"
2219 Diag(Loc, diag::err_static_not_bitfield)
2220 << Name << BitWidth->getSourceRange();
2221 } else if (isa<TypedefDecl>(Member)) {
2222 // "typedef member 'x' cannot be a bit-field"
2223 Diag(Loc, diag::err_typedef_not_bitfield)
2224 << Name << BitWidth->getSourceRange();
2225 } else {
2226 // A function typedef ("typedef int f(); f a;").
2227 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2228 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00002229 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00002230 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00002231 }
Mike Stump1eb44332009-09-09 15:08:12 +00002232
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002233 BitWidth = nullptr;
Chris Lattner8b963ef2009-03-05 23:01:03 +00002234 Member->setInvalidDecl();
2235 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00002236
2237 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00002238
Larisse Voufoef4579c2013-08-06 01:03:05 +00002239 // If we have declared a member function template or static data member
2240 // template, set the access of the templated declaration as well.
Douglas Gregor37b372b2009-08-20 22:52:58 +00002241 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2242 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufoef4579c2013-08-06 01:03:05 +00002243 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2244 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00002245 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002246
Richard Smitha4b39652012-08-06 03:25:17 +00002247 if (VS.isOverrideSpecified())
Stephen Hines651f13c2014-04-23 16:59:28 -07002248 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smitha4b39652012-08-06 03:25:17 +00002249 if (VS.isFinalSpecified())
David Majnemer7121bdb2013-10-18 00:33:31 +00002250 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2251 VS.isFinalSpelledSealed()));
Anders Carlsson9e682d92011-01-20 05:57:14 +00002252
Douglas Gregorf5251602011-03-08 17:10:18 +00002253 if (VS.getLastLocation().isValid()) {
2254 // Update the end location of a method that has a virt-specifiers.
2255 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2256 MD->setRangeEnd(VS.getLastLocation());
2257 }
Richard Smitha4b39652012-08-06 03:25:17 +00002258
Anders Carlsson4ebf1602011-01-20 06:29:02 +00002259 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00002260
Douglas Gregor10bd3682008-11-17 22:58:34 +00002261 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002262
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002263 if (isInstField) {
2264 FieldDecl *FD = cast<FieldDecl>(Member);
2265 FieldCollector->Add(FD);
2266
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002267 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002268 // Remember all explicit private FieldDecls that have a name, no side
2269 // effects and are not part of a dependent type declaration.
2270 if (!FD->isImplicit() && FD->getDeclName() &&
2271 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00002272 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00002273 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002274 !InitializationHasSideEffects(*FD))
2275 UnusedPrivateFields.insert(FD);
2276 }
2277 }
2278
John McCalld226f652010-08-21 09:40:31 +00002279 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002280}
2281
Hans Wennborg471f9852012-09-18 15:58:06 +00002282namespace {
2283 class UninitializedFieldVisitor
2284 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2285 Sema &S;
Richard Trieu858d2ba2013-10-25 00:56:00 +00002286 // List of Decls to generate a warning on. Also remove Decls that become
2287 // initialized.
Stephen Hines176edba2014-12-01 14:53:08 -08002288 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002289 // List of base classes of the record. Classes are removed after their
2290 // initializers.
2291 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
Stephen Hines176edba2014-12-01 14:53:08 -08002292 // Vector of decls to be removed from the Decl set prior to visiting the
2293 // nodes. These Decls may have been initialized in the prior initializer.
2294 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
Richard Trieuef8f90c2013-09-20 03:03:06 +00002295 // If non-null, add a note to the warning pointing back to the constructor.
2296 const CXXConstructorDecl *Constructor;
Stephen Hines176edba2014-12-01 14:53:08 -08002297 // Variables to hold state when processing an initializer list. When
2298 // InitList is true, special case initialization of FieldDecls matching
2299 // InitListFieldDecl.
2300 bool InitList;
2301 FieldDecl *InitListFieldDecl;
2302 llvm::SmallVector<unsigned, 4> InitFieldIndex;
2303
Hans Wennborg471f9852012-09-18 15:58:06 +00002304 public:
2305 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieu858d2ba2013-10-25 00:56:00 +00002306 UninitializedFieldVisitor(Sema &S,
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002307 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
2308 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
2309 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
2310 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
Hans Wennborg471f9852012-09-18 15:58:06 +00002311
Stephen Hines176edba2014-12-01 14:53:08 -08002312 // Returns true if the use of ME is not an uninitialized use.
2313 bool IsInitListMemberExprInitialized(MemberExpr *ME,
2314 bool CheckReferenceOnly) {
2315 llvm::SmallVector<FieldDecl*, 4> Fields;
2316 bool ReferenceField = false;
2317 while (ME) {
2318 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
2319 if (!FD)
2320 return false;
2321 Fields.push_back(FD);
2322 if (FD->getType()->isReferenceType())
2323 ReferenceField = true;
2324 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
2325 }
2326
2327 // Binding a reference to an unintialized field is not an
2328 // uninitialized use.
2329 if (CheckReferenceOnly && !ReferenceField)
2330 return true;
2331
2332 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
2333 // Discard the first field since it is the field decl that is being
2334 // initialized.
2335 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
2336 UsedFieldIndex.push_back((*I)->getFieldIndex());
2337 }
2338
2339 for (auto UsedIter = UsedFieldIndex.begin(),
2340 UsedEnd = UsedFieldIndex.end(),
2341 OrigIter = InitFieldIndex.begin(),
2342 OrigEnd = InitFieldIndex.end();
2343 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
2344 if (*UsedIter < *OrigIter)
2345 return true;
2346 if (*UsedIter > *OrigIter)
2347 break;
2348 }
2349
2350 return false;
2351 }
2352
2353 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
2354 bool AddressOf) {
Richard Trieufbb08b52013-09-13 03:20:53 +00002355 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2356 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002357
Richard Trieufbb08b52013-09-13 03:20:53 +00002358 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2359 // or union.
2360 MemberExpr *FieldME = ME;
2361
Stephen Hines176edba2014-12-01 14:53:08 -08002362 bool AllPODFields = FieldME->getType().isPODType(S.Context);
Richard Trieufbb08b52013-09-13 03:20:53 +00002363
Stephen Hines176edba2014-12-01 14:53:08 -08002364 Expr *Base = ME;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002365 while (MemberExpr *SubME =
2366 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
Stephen Hines176edba2014-12-01 14:53:08 -08002367
2368 if (isa<VarDecl>(SubME->getMemberDecl()))
Richard Trieufbb08b52013-09-13 03:20:53 +00002369 return;
2370
Stephen Hines176edba2014-12-01 14:53:08 -08002371 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
Richard Trieufbb08b52013-09-13 03:20:53 +00002372 if (!FD->isAnonymousStructOrUnion())
Stephen Hines176edba2014-12-01 14:53:08 -08002373 FieldME = SubME;
Richard Trieufbb08b52013-09-13 03:20:53 +00002374
Stephen Hines176edba2014-12-01 14:53:08 -08002375 if (!FieldME->getType().isPODType(S.Context))
2376 AllPODFields = false;
2377
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002378 Base = SubME->getBase();
Richard Trieufbb08b52013-09-13 03:20:53 +00002379 }
2380
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002381 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
Richard Trieu3ddec882013-09-16 20:46:50 +00002382 return;
2383
Stephen Hines176edba2014-12-01 14:53:08 -08002384 if (AddressOf && AllPODFields)
2385 return;
2386
Richard Trieuef8f90c2013-09-20 03:03:06 +00002387 ValueDecl* FoundVD = FieldME->getMemberDecl();
2388
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002389 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
2390 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
2391 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
2392 }
2393
2394 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
2395 QualType T = BaseCast->getType();
2396 if (T->isPointerType() &&
2397 BaseClasses.count(T->getPointeeType())) {
2398 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
2399 << T->getPointeeType() << FoundVD;
2400 }
2401 }
2402 }
2403
Richard Trieu858d2ba2013-10-25 00:56:00 +00002404 if (!Decls.count(FoundVD))
Richard Trieuef8f90c2013-09-20 03:03:06 +00002405 return;
2406
Richard Trieu858d2ba2013-10-25 00:56:00 +00002407 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieuef8f90c2013-09-20 03:03:06 +00002408
Stephen Hines176edba2014-12-01 14:53:08 -08002409 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
2410 // Special checking for initializer lists.
2411 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
2412 return;
2413 }
2414 } else {
2415 // Prevent double warnings on use of unbounded references.
2416 if (CheckReferenceOnly && !IsReference)
2417 return;
2418 }
Richard Trieu858d2ba2013-10-25 00:56:00 +00002419
2420 unsigned diag = IsReference
2421 ? diag::warn_reference_field_is_uninit
2422 : diag::warn_field_is_uninit;
2423 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2424 if (Constructor)
2425 S.Diag(Constructor->getLocation(),
2426 diag::note_uninit_in_this_constructor)
2427 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2428
Hans Wennborg471f9852012-09-18 15:58:06 +00002429 }
2430
Stephen Hines176edba2014-12-01 14:53:08 -08002431 void HandleValue(Expr *E, bool AddressOf) {
Hans Wennborg471f9852012-09-18 15:58:06 +00002432 E = E->IgnoreParens();
2433
2434 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Stephen Hines176edba2014-12-01 14:53:08 -08002435 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
2436 AddressOf /*AddressOf*/);
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002437 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002438 }
2439
2440 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
Stephen Hines176edba2014-12-01 14:53:08 -08002441 Visit(CO->getCond());
2442 HandleValue(CO->getTrueExpr(), AddressOf);
2443 HandleValue(CO->getFalseExpr(), AddressOf);
Hans Wennborg471f9852012-09-18 15:58:06 +00002444 return;
2445 }
2446
2447 if (BinaryConditionalOperator *BCO =
2448 dyn_cast<BinaryConditionalOperator>(E)) {
Stephen Hines176edba2014-12-01 14:53:08 -08002449 Visit(BCO->getCond());
2450 HandleValue(BCO->getFalseExpr(), AddressOf);
2451 return;
2452 }
2453
2454 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
2455 HandleValue(OVE->getSourceExpr(), AddressOf);
Hans Wennborg471f9852012-09-18 15:58:06 +00002456 return;
2457 }
2458
2459 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2460 switch (BO->getOpcode()) {
2461 default:
Stephen Hines176edba2014-12-01 14:53:08 -08002462 break;
Hans Wennborg471f9852012-09-18 15:58:06 +00002463 case(BO_PtrMemD):
2464 case(BO_PtrMemI):
Stephen Hines176edba2014-12-01 14:53:08 -08002465 HandleValue(BO->getLHS(), AddressOf);
2466 Visit(BO->getRHS());
Hans Wennborg471f9852012-09-18 15:58:06 +00002467 return;
2468 case(BO_Comma):
Stephen Hines176edba2014-12-01 14:53:08 -08002469 Visit(BO->getLHS());
2470 HandleValue(BO->getRHS(), AddressOf);
Hans Wennborg471f9852012-09-18 15:58:06 +00002471 return;
2472 }
2473 }
Stephen Hines176edba2014-12-01 14:53:08 -08002474
2475 Visit(E);
2476 }
2477
2478 void CheckInitListExpr(InitListExpr *ILE) {
2479 InitFieldIndex.push_back(0);
2480 for (auto Child : ILE->children()) {
2481 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
2482 CheckInitListExpr(SubList);
2483 } else {
2484 Visit(Child);
2485 }
2486 ++InitFieldIndex.back();
2487 }
2488 InitFieldIndex.pop_back();
2489 }
2490
2491 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002492 FieldDecl *Field, const Type *BaseClass) {
Stephen Hines176edba2014-12-01 14:53:08 -08002493 // Remove Decls that may have been initialized in the previous
2494 // initializer.
2495 for (ValueDecl* VD : DeclsToRemove)
2496 Decls.erase(VD);
2497 DeclsToRemove.clear();
2498
2499 Constructor = FieldConstructor;
2500 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
2501
2502 if (ILE && Field) {
2503 InitList = true;
2504 InitListFieldDecl = Field;
2505 InitFieldIndex.clear();
2506 CheckInitListExpr(ILE);
2507 } else {
2508 InitList = false;
2509 Visit(E);
2510 }
2511
2512 if (Field)
2513 Decls.erase(Field);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002514 if (BaseClass)
2515 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
Hans Wennborg471f9852012-09-18 15:58:06 +00002516 }
2517
Richard Trieufbb08b52013-09-13 03:20:53 +00002518 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieu858d2ba2013-10-25 00:56:00 +00002519 // All uses of unbounded reference fields will warn.
Stephen Hines176edba2014-12-01 14:53:08 -08002520 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
Richard Trieufbb08b52013-09-13 03:20:53 +00002521 }
2522
Hans Wennborg471f9852012-09-18 15:58:06 +00002523 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Stephen Hines176edba2014-12-01 14:53:08 -08002524 if (E->getCastKind() == CK_LValueToRValue) {
2525 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2526 return;
2527 }
Hans Wennborg471f9852012-09-18 15:58:06 +00002528
2529 Inherited::VisitImplicitCastExpr(E);
2530 }
2531
Richard Trieufbb08b52013-09-13 03:20:53 +00002532 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Stephen Hines176edba2014-12-01 14:53:08 -08002533 if (E->getConstructor()->isCopyConstructor()) {
2534 Expr *ArgExpr = E->getArg(0);
2535 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
2536 if (ILE->getNumInits() == 1)
2537 ArgExpr = ILE->getInit(0);
2538 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
Richard Trieufbb08b52013-09-13 03:20:53 +00002539 if (ICE->getCastKind() == CK_NoOp)
Stephen Hines176edba2014-12-01 14:53:08 -08002540 ArgExpr = ICE->getSubExpr();
2541 HandleValue(ArgExpr, false /*AddressOf*/);
2542 return;
2543 }
Richard Trieufbb08b52013-09-13 03:20:53 +00002544 Inherited::VisitCXXConstructExpr(E);
2545 }
2546
Hans Wennborg471f9852012-09-18 15:58:06 +00002547 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2548 Expr *Callee = E->getCallee();
Stephen Hines176edba2014-12-01 14:53:08 -08002549 if (isa<MemberExpr>(Callee)) {
2550 HandleValue(Callee, false /*AddressOf*/);
2551 for (auto Arg : E->arguments())
2552 Visit(Arg);
2553 return;
2554 }
Hans Wennborg471f9852012-09-18 15:58:06 +00002555
2556 Inherited::VisitCXXMemberCallExpr(E);
2557 }
Richard Trieuef8f90c2013-09-20 03:03:06 +00002558
Stephen Hines176edba2014-12-01 14:53:08 -08002559 void VisitCallExpr(CallExpr *E) {
2560 // Treat std::move as a use.
2561 if (E->getNumArgs() == 1) {
2562 if (FunctionDecl *FD = E->getDirectCallee()) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002563 if (FD->isInStdNamespace() && FD->getIdentifier() &&
2564 FD->getIdentifier()->isStr("move")) {
Stephen Hines176edba2014-12-01 14:53:08 -08002565 HandleValue(E->getArg(0), false /*AddressOf*/);
2566 return;
2567 }
2568 }
2569 }
2570
2571 Inherited::VisitCallExpr(E);
2572 }
2573
2574 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
2575 Expr *Callee = E->getCallee();
2576
2577 if (isa<UnresolvedLookupExpr>(Callee))
2578 return Inherited::VisitCXXOperatorCallExpr(E);
2579
2580 Visit(Callee);
2581 for (auto Arg : E->arguments())
2582 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
2583 }
2584
Richard Trieuef8f90c2013-09-20 03:03:06 +00002585 void VisitBinaryOperator(BinaryOperator *E) {
2586 // If a field assignment is detected, remove the field from the
2587 // uninitiailized field set.
2588 if (E->getOpcode() == BO_Assign)
2589 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2590 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieu858d2ba2013-10-25 00:56:00 +00002591 if (!FD->getType()->isReferenceType())
Stephen Hines176edba2014-12-01 14:53:08 -08002592 DeclsToRemove.push_back(FD);
2593
2594 if (E->isCompoundAssignmentOp()) {
2595 HandleValue(E->getLHS(), false /*AddressOf*/);
2596 Visit(E->getRHS());
2597 return;
2598 }
Richard Trieuef8f90c2013-09-20 03:03:06 +00002599
2600 Inherited::VisitBinaryOperator(E);
2601 }
Richard Trieuef8f90c2013-09-20 03:03:06 +00002602
Stephen Hines176edba2014-12-01 14:53:08 -08002603 void VisitUnaryOperator(UnaryOperator *E) {
2604 if (E->isIncrementDecrementOp()) {
2605 HandleValue(E->getSubExpr(), false /*AddressOf*/);
Richard Trieu858d2ba2013-10-25 00:56:00 +00002606 return;
Stephen Hines176edba2014-12-01 14:53:08 -08002607 }
2608 if (E->getOpcode() == UO_AddrOf) {
2609 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
2610 HandleValue(ME->getBase(), true /*AddressOf*/);
2611 return;
2612 }
2613 }
2614
2615 Inherited::VisitUnaryOperator(E);
Richard Trieu858d2ba2013-10-25 00:56:00 +00002616 }
Stephen Hines176edba2014-12-01 14:53:08 -08002617 };
Richard Trieu858d2ba2013-10-25 00:56:00 +00002618
2619 // Diagnose value-uses of fields to initialize themselves, e.g.
2620 // foo(foo)
2621 // where foo is not also a parameter to the constructor.
2622 // Also diagnose across field uninitialized use such as
2623 // x(y), y(x)
2624 // TODO: implement -Wuninitialized and fold this into that framework.
2625 static void DiagnoseUninitializedFields(
2626 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2627
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002628 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2629 Constructor->getLocation())) {
Richard Trieu858d2ba2013-10-25 00:56:00 +00002630 return;
2631 }
2632
2633 if (Constructor->isInvalidDecl())
2634 return;
2635
2636 const CXXRecordDecl *RD = Constructor->getParent();
2637
Stephen Hines176edba2014-12-01 14:53:08 -08002638 if (RD->getDescribedClassTemplate())
2639 return;
2640
Richard Trieu858d2ba2013-10-25 00:56:00 +00002641 // Holds fields that are uninitialized.
2642 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2643
2644 // At the beginning, all fields are uninitialized.
Stephen Hines651f13c2014-04-23 16:59:28 -07002645 for (auto *I : RD->decls()) {
2646 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieu858d2ba2013-10-25 00:56:00 +00002647 UninitializedFields.insert(FD);
Stephen Hines651f13c2014-04-23 16:59:28 -07002648 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieu858d2ba2013-10-25 00:56:00 +00002649 UninitializedFields.insert(IFD->getAnonField());
2650 }
2651 }
2652
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002653 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
2654 for (auto I : RD->bases())
2655 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
2656
2657 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Stephen Hines176edba2014-12-01 14:53:08 -08002658 return;
2659
2660 UninitializedFieldVisitor UninitializedChecker(SemaRef,
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002661 UninitializedFields,
2662 UninitializedBaseClasses);
Stephen Hines176edba2014-12-01 14:53:08 -08002663
Stephen Hines651f13c2014-04-23 16:59:28 -07002664 for (const auto *FieldInit : Constructor->inits()) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002665 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Stephen Hines176edba2014-12-01 14:53:08 -08002666 break;
2667
Stephen Hines651f13c2014-04-23 16:59:28 -07002668 Expr *InitExpr = FieldInit->getInit();
Stephen Hines176edba2014-12-01 14:53:08 -08002669 if (!InitExpr)
2670 continue;
Richard Trieu858d2ba2013-10-25 00:56:00 +00002671
Stephen Hines176edba2014-12-01 14:53:08 -08002672 if (CXXDefaultInitExpr *Default =
2673 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
2674 InitExpr = Default->getExpr();
2675 if (!InitExpr)
2676 continue;
2677 // In class initializers will point to the constructor.
2678 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002679 FieldInit->getAnyMember(),
2680 FieldInit->getBaseClass());
Stephen Hines176edba2014-12-01 14:53:08 -08002681 } else {
2682 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002683 FieldInit->getAnyMember(),
2684 FieldInit->getBaseClass());
Stephen Hines176edba2014-12-01 14:53:08 -08002685 }
Richard Trieu858d2ba2013-10-25 00:56:00 +00002686 }
Hans Wennborg471f9852012-09-18 15:58:06 +00002687 }
2688} // namespace
2689
Stephen Hines651f13c2014-04-23 16:59:28 -07002690/// \brief Enter a new C++ default initializer scope. After calling this, the
2691/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2692/// parsing or instantiating the initializer failed.
2693void Sema::ActOnStartCXXInClassMemberInitializer() {
2694 // Create a synthetic function scope to represent the call to the constructor
2695 // that notionally surrounds a use of this initializer.
2696 PushFunctionScope();
2697}
2698
2699/// \brief This is invoked after parsing an in-class initializer for a
2700/// non-static C++ class member, and after instantiating an in-class initializer
2701/// in a class template. Such actions are deferred until the class is complete.
2702void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2703 SourceLocation InitLoc,
2704 Expr *InitExpr) {
2705 // Pop the notional constructor scope we created earlier.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002706 PopFunctionScopeInfo(nullptr, D);
Stephen Hines651f13c2014-04-23 16:59:28 -07002707
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002708 FieldDecl *FD = dyn_cast<FieldDecl>(D);
2709 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
Richard Smithca523302012-06-10 03:12:00 +00002710 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00002711
2712 if (!InitExpr) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002713 D->setInvalidDecl();
2714 if (FD)
2715 FD->removeInClassInitializer();
Richard Smith7a614d82011-06-11 17:19:42 +00002716 return;
2717 }
2718
Peter Collingbournefef21892011-10-23 18:59:44 +00002719 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2720 FD->setInvalidDecl();
2721 FD->removeInClassInitializer();
2722 return;
2723 }
2724
Richard Smith7a614d82011-06-11 17:19:42 +00002725 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00002726 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002727 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002728 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002729 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002730 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002731 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2732 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith7a614d82011-06-11 17:19:42 +00002733 if (Init.isInvalid()) {
2734 FD->setInvalidDecl();
2735 return;
2736 }
Richard Smith7a614d82011-06-11 17:19:42 +00002737 }
2738
Richard Smith41956372013-01-14 22:39:08 +00002739 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002740 // The initialization of each base and member constitutes a
2741 // full-expression.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002742 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002743 if (Init.isInvalid()) {
2744 FD->setInvalidDecl();
2745 return;
2746 }
2747
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002748 InitExpr = Init.get();
Richard Smith7a614d82011-06-11 17:19:42 +00002749
2750 FD->setInClassInitializer(InitExpr);
2751}
2752
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002753/// \brief Find the direct and/or virtual base specifiers that
2754/// correspond to the given base type, for use in base initialization
2755/// within a constructor.
2756static bool FindBaseInitializer(Sema &SemaRef,
2757 CXXRecordDecl *ClassDecl,
2758 QualType BaseType,
2759 const CXXBaseSpecifier *&DirectBaseSpec,
2760 const CXXBaseSpecifier *&VirtualBaseSpec) {
2761 // First, check for a direct base class.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002762 DirectBaseSpec = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07002763 for (const auto &Base : ClassDecl->bases()) {
2764 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002765 // We found a direct base of this type. That's what we're
2766 // initializing.
Stephen Hines651f13c2014-04-23 16:59:28 -07002767 DirectBaseSpec = &Base;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002768 break;
2769 }
2770 }
2771
2772 // Check for a virtual base class.
2773 // FIXME: We might be able to short-circuit this if we know in advance that
2774 // there are no virtual bases.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002775 VirtualBaseSpec = nullptr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002776 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2777 // We haven't found a base yet; search the class hierarchy for a
2778 // virtual base class.
2779 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2780 /*DetectVirtual=*/false);
2781 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2782 BaseType, Paths)) {
2783 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2784 Path != Paths.end(); ++Path) {
2785 if (Path->back().Base->isVirtual()) {
2786 VirtualBaseSpec = Path->back().Base;
2787 break;
2788 }
2789 }
2790 }
2791 }
2792
2793 return DirectBaseSpec || VirtualBaseSpec;
2794}
2795
Sebastian Redl6df65482011-09-24 17:48:25 +00002796/// \brief Handle a C++ member initializer using braced-init-list syntax.
2797MemInitResult
2798Sema::ActOnMemInitializer(Decl *ConstructorD,
2799 Scope *S,
2800 CXXScopeSpec &SS,
2801 IdentifierInfo *MemberOrBase,
2802 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002803 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002804 SourceLocation IdLoc,
2805 Expr *InitList,
2806 SourceLocation EllipsisLoc) {
2807 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002808 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002809 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002810}
2811
2812/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002813MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002814Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002815 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002816 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002817 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002818 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002819 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002820 SourceLocation IdLoc,
2821 SourceLocation LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002822 ArrayRef<Expr *> Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002823 SourceLocation RParenLoc,
2824 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002825 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002826 Args, RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002827 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002828 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002829}
2830
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002831namespace {
2832
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002833// Callback to only accept typo corrections that can be a valid C++ member
2834// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002835class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002836public:
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002837 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2838 : ClassDecl(ClassDecl) {}
2839
Stephen Hines651f13c2014-04-23 16:59:28 -07002840 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002841 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2842 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2843 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002844 return isa<TypeDecl>(ND);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002845 }
2846 return false;
2847 }
2848
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002849private:
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002850 CXXRecordDecl *ClassDecl;
2851};
2852
2853}
2854
Sebastian Redl6df65482011-09-24 17:48:25 +00002855/// \brief Handle a C++ member initializer.
2856MemInitResult
2857Sema::BuildMemInitializer(Decl *ConstructorD,
2858 Scope *S,
2859 CXXScopeSpec &SS,
2860 IdentifierInfo *MemberOrBase,
2861 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002862 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002863 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002864 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002865 SourceLocation EllipsisLoc) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002866 ExprResult Res = CorrectDelayedTyposInExpr(Init);
2867 if (!Res.isUsable())
2868 return true;
2869 Init = Res.get();
2870
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002871 if (!ConstructorD)
2872 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002873
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002874 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002875
2876 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002877 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002878 if (!Constructor) {
2879 // The user wrote a constructor initializer on a function that is
2880 // not a C++ constructor. Ignore the error for now, because we may
2881 // have more member initializers coming; we'll diagnose it just
2882 // once in ActOnMemInitializers.
2883 return true;
2884 }
2885
2886 CXXRecordDecl *ClassDecl = Constructor->getParent();
2887
2888 // C++ [class.base.init]p2:
2889 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002890 // constructor's class and, if not found in that scope, are looked
2891 // up in the scope containing the constructor's definition.
2892 // [Note: if the constructor's class contains a member with the
2893 // same name as a direct or virtual base class of the class, a
2894 // mem-initializer-id naming the member or base class and composed
2895 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002896 // mem-initializer-id for the hidden base class may be specified
2897 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002898 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002899 // Look for a member, first.
Stephen Hines176edba2014-12-01 14:53:08 -08002900 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002901 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002902 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002903 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2904 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002905 if (EllipsisLoc.isValid())
2906 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002907 << MemberOrBase
2908 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002909
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002910 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002911 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002912 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002913 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002914 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002915 QualType BaseType;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002916 TypeSourceInfo *TInfo = nullptr;
John McCall2b194412009-12-21 10:41:20 +00002917
2918 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002919 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002920 } else if (DS.getTypeSpecType() == TST_decltype) {
2921 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002922 } else {
2923 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2924 LookupParsedName(R, S, &SS);
2925
2926 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2927 if (!TyD) {
2928 if (R.isAmbiguous()) return true;
2929
John McCallfd225442010-04-09 19:01:14 +00002930 // We don't want access-control diagnostics here.
2931 R.suppressDiagnostics();
2932
Douglas Gregor7a886e12010-01-19 06:46:48 +00002933 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2934 bool NotUnknownSpecialization = false;
2935 DeclContext *DC = computeDeclContext(SS, false);
2936 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2937 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2938
2939 if (!NotUnknownSpecialization) {
2940 // When the scope specifier can refer to a member of an unknown
2941 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002942 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2943 SS.getWithLocInContext(Context),
2944 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002945 if (BaseType.isNull())
2946 return true;
2947
Douglas Gregor7a886e12010-01-19 06:46:48 +00002948 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002949 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002950 }
2951 }
2952
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002953 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002954 TypoCorrection Corr;
Douglas Gregor7a886e12010-01-19 06:46:48 +00002955 if (R.empty() && BaseType.isNull() &&
Stephen Hines176edba2014-12-01 14:53:08 -08002956 (Corr = CorrectTypo(
2957 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2958 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
2959 CTK_ErrorRecovery, ClassDecl))) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002960 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002961 // We have found a non-static data member with a similar
2962 // name to what was typed; complain and initialize that
2963 // member.
Richard Smith2d670972013-08-17 00:46:16 +00002964 diagnoseTypo(Corr,
2965 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2966 << MemberOrBase << true);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002967 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002968 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002969 const CXXBaseSpecifier *DirectBaseSpec;
2970 const CXXBaseSpecifier *VirtualBaseSpec;
2971 if (FindBaseInitializer(*this, ClassDecl,
2972 Context.getTypeDeclType(Type),
2973 DirectBaseSpec, VirtualBaseSpec)) {
2974 // We have found a direct or virtual base class with a
2975 // similar name to what was typed; complain and initialize
2976 // that base class.
Richard Smith2d670972013-08-17 00:46:16 +00002977 diagnoseTypo(Corr,
2978 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2979 << MemberOrBase << false,
2980 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002981
Richard Smith2d670972013-08-17 00:46:16 +00002982 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2983 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002984 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002985 diag::note_base_class_specified_here)
2986 << BaseSpec->getType()
2987 << BaseSpec->getSourceRange();
2988
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002989 TyD = Type;
2990 }
2991 }
2992 }
2993
Douglas Gregor7a886e12010-01-19 06:46:48 +00002994 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002995 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002996 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002997 return true;
2998 }
John McCall2b194412009-12-21 10:41:20 +00002999 }
3000
Douglas Gregor7a886e12010-01-19 06:46:48 +00003001 if (BaseType.isNull()) {
3002 BaseType = Context.getTypeDeclType(TyD);
Stephen Hines176edba2014-12-01 14:53:08 -08003003 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
Stephen Hines651f13c2014-04-23 16:59:28 -07003004 if (SS.isSet())
Douglas Gregor7a886e12010-01-19 06:46:48 +00003005 // FIXME: preserve source range information
Stephen Hines651f13c2014-04-23 16:59:28 -07003006 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3007 BaseType);
John McCall2b194412009-12-21 10:41:20 +00003008 }
3009 }
Mike Stump1eb44332009-09-09 15:08:12 +00003010
John McCalla93c9342009-12-07 02:54:59 +00003011 if (!TInfo)
3012 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00003013
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003014 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00003015}
3016
Chandler Carruth81c64772011-09-03 01:14:15 +00003017/// Checks a member initializer expression for cases where reference (or
3018/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00003019static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3020 Expr *Init,
3021 SourceLocation IdLoc) {
3022 QualType MemberTy = Member->getType();
3023
3024 // We only handle pointers and references currently.
3025 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3026 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3027 return;
3028
3029 const bool IsPointer = MemberTy->isPointerType();
3030 if (IsPointer) {
3031 if (const UnaryOperator *Op
3032 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3033 // The only case we're worried about with pointers requires taking the
3034 // address.
3035 if (Op->getOpcode() != UO_AddrOf)
3036 return;
3037
3038 Init = Op->getSubExpr();
3039 } else {
3040 // We only handle address-of expression initializers for pointers.
3041 return;
3042 }
3043 }
3044
Richard Smitha4bb99c2013-06-12 21:51:50 +00003045 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthbf3380a2011-09-03 02:21:57 +00003046 // We only warn when referring to a non-reference parameter declaration.
3047 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3048 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00003049 return;
3050
3051 S.Diag(Init->getExprLoc(),
3052 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3053 : diag::warn_bind_ref_member_to_parameter)
3054 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00003055 } else {
3056 // Other initializers are fine.
3057 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00003058 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00003059
3060 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3061 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00003062}
3063
John McCallf312b1e2010-08-26 23:41:50 +00003064MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003065Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00003066 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00003067 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3068 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3069 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00003070 "Member must be a FieldDecl or IndirectFieldDecl");
3071
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003072 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00003073 return true;
3074
Douglas Gregor464b2f02010-11-05 22:21:31 +00003075 if (Member->isInvalidDecl())
3076 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00003077
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003078 MultiExprArg Args;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003079 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003080 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithc83c2302012-12-19 01:39:02 +00003081 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003082 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithc83c2302012-12-19 01:39:02 +00003083 } else {
3084 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003085 Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003086 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00003087
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003088 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00003089
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003090 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003091 // Can't check initialization for a member of dependent type or when
3092 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00003093 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00003094 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00003095 bool InitList = false;
3096 if (isa<InitListExpr>(Init)) {
3097 InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003098 Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00003099 }
3100
Chandler Carruth894aed92010-12-06 09:23:57 +00003101 // Initialize the member.
3102 InitializedEntity MemberEntity =
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003103 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3104 : InitializedEntity::InitializeMember(IndirectMember,
3105 nullptr);
Chandler Carruth894aed92010-12-06 09:23:57 +00003106 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00003107 InitList ? InitializationKind::CreateDirectList(IdLoc)
3108 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3109 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00003110
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003111 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003112 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3113 nullptr);
Chandler Carruth894aed92010-12-06 09:23:57 +00003114 if (MemberInit.isInvalid())
3115 return true;
3116
Richard Smith8a07cd32013-06-12 20:42:33 +00003117 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3118
Richard Smith41956372013-01-14 22:39:08 +00003119 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00003120 // The initialization of each base and member constitutes a
3121 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00003122 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00003123 if (MemberInit.isInvalid())
3124 return true;
3125
Richard Smithc83c2302012-12-19 01:39:02 +00003126 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003127 }
3128
Chandler Carruth894aed92010-12-06 09:23:57 +00003129 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003130 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3131 InitRange.getBegin(), Init,
3132 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00003133 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003134 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3135 InitRange.getBegin(), Init,
3136 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00003137 }
Eli Friedman59c04372009-07-29 19:44:27 +00003138}
3139
John McCallf312b1e2010-08-26 23:41:50 +00003140MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003141Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00003142 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00003143 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00003144 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00003145 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00003146 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00003147 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00003148
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00003149 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003150 MultiExprArg Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00003151 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3152 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003153 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00003154 }
3155
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003156 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00003157 // Initialize the object.
3158 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3159 QualType(ClassDecl->getTypeForDecl(), 0));
3160 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00003161 InitList ? InitializationKind::CreateDirectList(NameLoc)
3162 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3163 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003164 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003165 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003166 Args, nullptr);
Sean Hunt41717662011-02-26 19:13:13 +00003167 if (DelegationInit.isInvalid())
3168 return true;
3169
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00003170 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3171 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00003172
Richard Smith41956372013-01-14 22:39:08 +00003173 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00003174 // The initialization of each base and member constitutes a
3175 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00003176 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3177 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00003178 if (DelegationInit.isInvalid())
3179 return true;
3180
Eli Friedmand21016f2012-05-19 23:35:23 +00003181 // If we are in a dependent context, template instantiation will
3182 // perform this type-checking again. Just save the arguments that we
3183 // received in a ParenListExpr.
3184 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3185 // of the information that we have about the base
3186 // initializer. However, deconstructing the ASTs is a dicey process,
3187 // and this approach is far more likely to get the corner cases right.
3188 if (CurContext->isDependentContext())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003189 DelegationInit = Init;
Eli Friedmand21016f2012-05-19 23:35:23 +00003190
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003191 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003192 DelegationInit.getAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003193 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00003194}
3195
3196MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00003197Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003198 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003199 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00003200 SourceLocation BaseLoc
3201 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00003202
Douglas Gregor3956b1a2010-06-16 16:03:14 +00003203 if (!BaseType->isDependentType() && !BaseType->isRecordType())
3204 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3205 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3206
3207 // C++ [class.base.init]p2:
3208 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00003209 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00003210 // of that class, the mem-initializer is ill-formed. A
3211 // mem-initializer-list can initialize a base class using any
3212 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003213 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00003214
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003215 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003216 if (EllipsisLoc.isValid()) {
3217 // This is a pack expansion.
3218 if (!BaseType->containsUnexpandedParameterPack()) {
3219 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003220 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00003221
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003222 EllipsisLoc = SourceLocation();
3223 }
3224 } else {
3225 // Check for any unexpanded parameter packs.
3226 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3227 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00003228
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003229 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00003230 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003231 }
Sebastian Redl6df65482011-09-24 17:48:25 +00003232
Douglas Gregor3956b1a2010-06-16 16:03:14 +00003233 // Check for direct and virtual base classes.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003234 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3235 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
Douglas Gregor3956b1a2010-06-16 16:03:14 +00003236 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00003237 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3238 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003239 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00003240
Douglas Gregor3956b1a2010-06-16 16:03:14 +00003241 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
3242 VirtualBaseSpec);
3243
3244 // C++ [base.class.init]p2:
3245 // Unless the mem-initializer-id names a nonstatic data member of the
3246 // constructor's class or a direct or virtual base of that class, the
3247 // mem-initializer is ill-formed.
3248 if (!DirectBaseSpec && !VirtualBaseSpec) {
3249 // If the class has any dependent bases, then it's possible that
3250 // one of those types will resolve to the same type as
3251 // BaseType. Therefore, just treat this as a dependent base
3252 // class initialization. FIXME: Should we try to check the
3253 // initialization anyway? It seems odd.
3254 if (ClassDecl->hasAnyDependentBases())
3255 Dependent = true;
3256 else
3257 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
3258 << BaseType << Context.getTypeDeclType(ClassDecl)
3259 << BaseTInfo->getTypeLoc().getLocalSourceRange();
3260 }
3261 }
3262
3263 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00003264 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00003265
Sebastian Redl6df65482011-09-24 17:48:25 +00003266 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3267 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003268 InitRange.getBegin(), Init,
3269 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00003270 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003271
3272 // C++ [base.class.init]p2:
3273 // If a mem-initializer-id is ambiguous because it designates both
3274 // a direct non-virtual base class and an inherited virtual base
3275 // class, the mem-initializer is ill-formed.
3276 if (DirectBaseSpec && VirtualBaseSpec)
3277 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003278 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003279
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003280 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003281 if (!BaseSpec)
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003282 BaseSpec = VirtualBaseSpec;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003283
3284 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00003285 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003286 MultiExprArg Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003287 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00003288 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003289 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003290 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00003291
3292 InitializedEntity BaseEntity =
3293 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3294 InitializationKind Kind =
3295 InitList ? InitializationKind::CreateDirectList(BaseLoc)
3296 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3297 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003298 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003299 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003300 if (BaseInit.isInvalid())
3301 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00003302
Richard Smith41956372013-01-14 22:39:08 +00003303 // C++11 [class.base.init]p7:
3304 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003305 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00003306 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003307 if (BaseInit.isInvalid())
3308 return true;
3309
3310 // If we are in a dependent context, template instantiation will
3311 // perform this type-checking again. Just save the arguments that we
3312 // received in a ParenListExpr.
3313 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3314 // of the information that we have about the base
3315 // initializer. However, deconstructing the ASTs is a dicey process,
3316 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00003317 if (CurContext->isDependentContext())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003318 BaseInit = Init;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003319
Sean Huntcbb67482011-01-08 20:30:50 +00003320 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00003321 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003322 InitRange.getBegin(),
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003323 BaseInit.getAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003324 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00003325}
3326
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003327// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00003328static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3329 if (T.isNull()) T = E->getType();
3330 QualType TargetType = SemaRef.BuildReferenceType(
3331 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003332 SourceLocation ExprLoc = E->getLocStart();
3333 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3334 TargetType, ExprLoc);
3335
3336 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3337 SourceRange(ExprLoc, ExprLoc),
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003338 E->getSourceRange()).get();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003339}
3340
Anders Carlssone5ef7402010-04-23 03:10:23 +00003341/// ImplicitInitializerKind - How an implicit base or member initializer should
3342/// initialize its base or member.
3343enum ImplicitInitializerKind {
3344 IIK_Default,
3345 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00003346 IIK_Move,
3347 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00003348};
3349
Anders Carlssondefefd22010-04-23 02:00:02 +00003350static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003351BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003352 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00003353 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00003354 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00003355 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00003356 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00003357 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3358 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00003359
John McCall60d7b3a2010-08-24 06:29:42 +00003360 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00003361
3362 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00003363 case IIK_Inherit: {
3364 const CXXRecordDecl *Inherited =
3365 Constructor->getInheritedConstructor()->getParent();
3366 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3367 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3368 // C++11 [class.inhctor]p8:
3369 // Each expression in the expression-list is of the form
3370 // static_cast<T&&>(p), where p is the name of the corresponding
3371 // constructor parameter and T is the declared type of p.
3372 SmallVector<Expr*, 16> Args;
3373 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3374 ParmVarDecl *PD = Constructor->getParamDecl(I);
3375 ExprResult ArgExpr =
3376 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3377 VK_LValue, SourceLocation());
3378 if (ArgExpr.isInvalid())
3379 return true;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003380 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
Richard Smith07b0fdc2013-03-18 21:12:30 +00003381 }
3382
3383 InitializationKind InitKind = InitializationKind::CreateDirect(
3384 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003385 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smith07b0fdc2013-03-18 21:12:30 +00003386 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3387 break;
3388 }
3389 }
3390 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00003391 case IIK_Default: {
3392 InitializationKind InitKind
3393 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003394 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3395 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003396 break;
3397 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003398
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003399 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00003400 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003401 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00003402 ParmVarDecl *Param = Constructor->getParamDecl(0);
3403 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00003404
Anders Carlssone5ef7402010-04-23 03:10:23 +00003405 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00003406 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00003407 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00003408 Constructor->getLocation(), ParamType,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003409 VK_LValue, nullptr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003410
Eli Friedman5f2987c2012-02-02 03:46:19 +00003411 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3412
Anders Carlssonc7957502010-04-24 22:02:54 +00003413 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00003414 QualType ArgTy =
3415 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3416 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00003417
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003418 if (Moving) {
3419 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3420 }
3421
John McCallf871d0c2010-08-07 06:22:56 +00003422 CXXCastPath BasePath;
3423 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00003424 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3425 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003426 Moving ? VK_XValue : VK_LValue,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003427 &BasePath).get();
Anders Carlssonc7957502010-04-24 22:02:54 +00003428
Anders Carlssone5ef7402010-04-23 03:10:23 +00003429 InitializationKind InitKind
3430 = InitializationKind::CreateDirect(Constructor->getLocation(),
3431 SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003432 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3433 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003434 break;
3435 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00003436 }
John McCall9ae2f072010-08-23 23:25:46 +00003437
Douglas Gregor53c374f2010-12-07 00:41:46 +00003438 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00003439 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00003440 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00003441
Anders Carlssondefefd22010-04-23 02:00:02 +00003442 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00003443 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00003444 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3445 SourceLocation()),
3446 BaseSpec->isVirtual(),
3447 SourceLocation(),
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003448 BaseInit.getAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003449 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00003450 SourceLocation());
3451
Anders Carlssondefefd22010-04-23 02:00:02 +00003452 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00003453}
3454
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003455static bool RefersToRValueRef(Expr *MemRef) {
3456 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3457 return Referenced->getType()->isRValueReferenceType();
3458}
3459
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003460static bool
3461BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003462 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003463 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00003464 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00003465 if (Field->isInvalidDecl())
3466 return true;
3467
Chandler Carruthf186b542010-06-29 23:50:44 +00003468 SourceLocation Loc = Constructor->getLocation();
3469
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003470 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3471 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003472 ParmVarDecl *Param = Constructor->getParamDecl(0);
3473 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00003474
3475 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003476 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3477 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00003478
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003479 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00003480 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00003481 SourceLocation(), Param, false,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003482 Loc, ParamType, VK_LValue, nullptr);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003483
Eli Friedman5f2987c2012-02-02 03:46:19 +00003484 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3485
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003486 if (Moving) {
3487 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3488 }
3489
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003490 // Build a reference to this field within the parameter.
3491 CXXScopeSpec SS;
3492 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3493 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003494 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3495 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003496 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00003497 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00003498 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003499 ParamType, Loc,
3500 /*IsArrow=*/false,
3501 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00003502 /*TemplateKWLoc=*/SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003503 /*FirstQualifierInScope=*/nullptr,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003504 MemberLookup,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003505 /*TemplateArgs=*/nullptr);
Sebastian Redl74e611a2011-09-04 18:14:28 +00003506 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003507 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003508
3509 // C++11 [class.copy]p15:
3510 // - if a member m has rvalue reference type T&&, it is direct-initialized
3511 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00003512 if (RefersToRValueRef(CtorArg.get())) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003513 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003514 }
3515
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003516 // When the field we are copying is an array, create index variables for
3517 // each dimension of the array. We use these index variables to subscript
3518 // the source array, and other clients (e.g., CodeGen) will perform the
3519 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003520 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003521 QualType BaseType = Field->getType();
3522 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003523 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003524 while (const ConstantArrayType *Array
3525 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003526 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003527 // Create the iteration variable for this array index.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003528 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003529 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003530 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003531 llvm::raw_svector_ostream OS(Str);
3532 OS << "__i" << IndexVariables.size();
3533 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3534 }
3535 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003536 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003537 IterationVarName, SizeType,
3538 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003539 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003540 IndexVariables.push_back(IterationVar);
3541
3542 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00003543 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00003544 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003545 assert(!IterationVarRef.isInvalid() &&
3546 "Reference to invented variable cannot fail!");
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003547 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
Eli Friedman8c382062012-01-23 02:35:22 +00003548 assert(!IterationVarRef.isInvalid() &&
3549 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00003550
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003551 // Subscript the array with this iteration variable.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003552 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3553 IterationVarRef.get(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00003554 Loc);
3555 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003556 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003557
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003558 BaseType = Array->getElementType();
3559 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003560
3561 // The array subscript expression is an lvalue, which is wrong for moving.
3562 if (Moving && InitializingArray)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003563 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003564
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003565 // Construct the entity that we will be initializing. For an array, this
3566 // will be first element in the array, which may require several levels
3567 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003568 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003569 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003570 if (Indirect)
3571 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3572 else
3573 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003574 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3575 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3576 0,
3577 Entities.back()));
3578
3579 // Direct-initialize to use the copy constructor.
3580 InitializationKind InitKind =
3581 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3582
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003583 Expr *CtorArgE = CtorArg.getAs<Expr>();
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07003584 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
3585 CtorArgE);
3586
John McCall60d7b3a2010-08-24 06:29:42 +00003587 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003588 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003589 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00003590 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003591 if (MemberInit.isInvalid())
3592 return true;
3593
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003594 if (Indirect) {
3595 assert(IndexVariables.size() == 0 &&
3596 "Indirect field improperly initialized");
3597 CXXMemberInit
3598 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3599 Loc, Loc,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003600 MemberInit.getAs<Expr>(),
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003601 Loc);
3602 } else
3603 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003604 Loc, MemberInit.getAs<Expr>(),
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003605 Loc,
3606 IndexVariables.data(),
3607 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00003608 return false;
3609 }
3610
Richard Smith07b0fdc2013-03-18 21:12:30 +00003611 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3612 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003613
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003614 QualType FieldBaseElementType =
3615 SemaRef.Context.getBaseElementType(Field->getType());
3616
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003617 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003618 InitializedEntity InitEntity
3619 = Indirect? InitializedEntity::InitializeMember(Indirect)
3620 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003621 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00003622 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003623
3624 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3625 ExprResult MemberInit =
3626 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCall9ae2f072010-08-23 23:25:46 +00003627
Douglas Gregor53c374f2010-12-07 00:41:46 +00003628 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003629 if (MemberInit.isInvalid())
3630 return true;
3631
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003632 if (Indirect)
3633 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3634 Indirect, Loc,
3635 Loc,
3636 MemberInit.get(),
3637 Loc);
3638 else
3639 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3640 Field, Loc, Loc,
3641 MemberInit.get(),
3642 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003643 return false;
3644 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003645
Sean Hunt1f2f3842011-05-17 00:19:05 +00003646 if (!Field->getParent()->isUnion()) {
3647 if (FieldBaseElementType->isReferenceType()) {
3648 SemaRef.Diag(Constructor->getLocation(),
3649 diag::err_uninitialized_member_in_ctor)
3650 << (int)Constructor->isImplicit()
3651 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3652 << 0 << Field->getDeclName();
3653 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3654 return true;
3655 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003656
Sean Hunt1f2f3842011-05-17 00:19:05 +00003657 if (FieldBaseElementType.isConstQualified()) {
3658 SemaRef.Diag(Constructor->getLocation(),
3659 diag::err_uninitialized_member_in_ctor)
3660 << (int)Constructor->isImplicit()
3661 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3662 << 1 << Field->getDeclName();
3663 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3664 return true;
3665 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003666 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003667
David Blaikie4e4d0842012-03-11 07:00:24 +00003668 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003669 FieldBaseElementType->isObjCRetainableType() &&
3670 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3671 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00003672 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00003673 // Default-initialize Objective-C pointers to NULL.
3674 CXXMemberInit
3675 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3676 Loc, Loc,
3677 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3678 Loc);
3679 return false;
3680 }
3681
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003682 // Nothing to initialize.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003683 CXXMemberInit = nullptr;
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003684 return false;
3685}
John McCallf1860e52010-05-20 23:23:51 +00003686
3687namespace {
3688struct BaseAndFieldInfo {
3689 Sema &S;
3690 CXXConstructorDecl *Ctor;
3691 bool AnyErrorsInInits;
3692 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003693 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003694 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Stephen Hines651f13c2014-04-23 16:59:28 -07003695 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallf1860e52010-05-20 23:23:51 +00003696
3697 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3698 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003699 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3700 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003701 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003702 else if (Generated && Ctor->isMoveConstructor())
3703 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003704 else if (Ctor->getInheritedConstructor())
3705 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003706 else
3707 IIK = IIK_Default;
3708 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003709
3710 bool isImplicitCopyOrMove() const {
3711 switch (IIK) {
3712 case IIK_Copy:
3713 case IIK_Move:
3714 return true;
3715
3716 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003717 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003718 return false;
3719 }
David Blaikie30263482012-01-20 21:50:17 +00003720
3721 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003722 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003723
3724 bool addFieldInitializer(CXXCtorInitializer *Init) {
3725 AllToInit.push_back(Init);
3726
3727 // Check whether this initializer makes the field "used".
Richard Smithc3bf52c2013-04-20 22:23:05 +00003728 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0b8220a2012-08-07 21:30:42 +00003729 S.UnusedPrivateFields.remove(Init->getAnyMember());
3730
3731 return false;
3732 }
John McCallf1860e52010-05-20 23:23:51 +00003733
Stephen Hines651f13c2014-04-23 16:59:28 -07003734 bool isInactiveUnionMember(FieldDecl *Field) {
3735 RecordDecl *Record = Field->getParent();
3736 if (!Record->isUnion())
3737 return false;
3738
3739 if (FieldDecl *Active =
3740 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
3741 return Active != Field->getCanonicalDecl();
3742
3743 // In an implicit copy or move constructor, ignore any in-class initializer.
3744 if (isImplicitCopyOrMove())
3745 return true;
3746
3747 // If there's no explicit initialization, the field is active only if it
3748 // has an in-class initializer...
3749 if (Field->hasInClassInitializer())
3750 return false;
3751 // ... or it's an anonymous struct or union whose class has an in-class
3752 // initializer.
3753 if (!Field->isAnonymousStructOrUnion())
3754 return true;
3755 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3756 return !FieldRD->hasInClassInitializer();
3757 }
3758
3759 /// \brief Determine whether the given field is, or is within, a union member
3760 /// that is inactive (because there was an initializer given for a different
3761 /// member of the union, or because the union was not initialized at all).
3762 bool isWithinInactiveUnionMember(FieldDecl *Field,
3763 IndirectFieldDecl *Indirect) {
3764 if (!Indirect)
3765 return isInactiveUnionMember(Field);
3766
3767 for (auto *C : Indirect->chain()) {
3768 FieldDecl *Field = dyn_cast<FieldDecl>(C);
3769 if (Field && isInactiveUnionMember(Field))
Richard Smitha4950662011-09-19 13:34:43 +00003770 return true;
Stephen Hines651f13c2014-04-23 16:59:28 -07003771 }
3772 return false;
3773 }
3774};
Richard Smitha4950662011-09-19 13:34:43 +00003775}
3776
Douglas Gregorddb21472011-11-02 23:04:16 +00003777/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3778/// array type.
3779static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3780 if (T->isIncompleteArrayType())
3781 return true;
3782
3783 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3784 if (!ArrayT->getSize())
3785 return true;
3786
3787 T = ArrayT->getElementType();
3788 }
3789
3790 return false;
3791}
3792
Richard Smith7a614d82011-06-11 17:19:42 +00003793static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003794 FieldDecl *Field,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003795 IndirectFieldDecl *Indirect = nullptr) {
Eli Friedman5fb478b2013-06-28 21:07:41 +00003796 if (Field->isInvalidDecl())
3797 return false;
John McCallf1860e52010-05-20 23:23:51 +00003798
Chandler Carruthe861c602010-06-30 02:59:29 +00003799 // Overwhelmingly common case: we have a direct initializer for this field.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003800 if (CXXCtorInitializer *Init =
3801 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
Richard Smith0b8220a2012-08-07 21:30:42 +00003802 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003803
Stephen Hines651f13c2014-04-23 16:59:28 -07003804 // C++11 [class.base.init]p8:
3805 // if the entity is a non-static data member that has a
3806 // brace-or-equal-initializer and either
3807 // -- the constructor's class is a union and no other variant member of that
3808 // union is designated by a mem-initializer-id or
3809 // -- the constructor's class is not a union, and, if the entity is a member
3810 // of an anonymous union, no other member of that union is designated by
3811 // a mem-initializer-id,
3812 // the entity is initialized as specified in [dcl.init].
3813 //
3814 // We also apply the same rules to handle anonymous structs within anonymous
3815 // unions.
3816 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3817 return false;
3818
Douglas Gregorf4853882011-11-28 20:03:15 +00003819 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Stephen Hines176edba2014-12-01 14:53:08 -08003820 ExprResult DIE =
3821 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
3822 if (DIE.isInvalid())
3823 return true;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003824 CXXCtorInitializer *Init;
3825 if (Indirect)
Stephen Hines176edba2014-12-01 14:53:08 -08003826 Init = new (SemaRef.Context)
3827 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
3828 SourceLocation(), DIE.get(), SourceLocation());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003829 else
Stephen Hines176edba2014-12-01 14:53:08 -08003830 Init = new (SemaRef.Context)
3831 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
3832 SourceLocation(), DIE.get(), SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003833 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003834 }
3835
Douglas Gregorddb21472011-11-02 23:04:16 +00003836 // Don't initialize incomplete or zero-length arrays.
3837 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3838 return false;
3839
John McCallf1860e52010-05-20 23:23:51 +00003840 // Don't try to build an implicit initializer if there were semantic
3841 // errors in any of the initializers (and therefore we might be
3842 // missing some that the user actually wrote).
Eli Friedman5fb478b2013-06-28 21:07:41 +00003843 if (Info.AnyErrorsInInits)
John McCallf1860e52010-05-20 23:23:51 +00003844 return false;
3845
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003846 CXXCtorInitializer *Init = nullptr;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003847 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3848 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003849 return true;
John McCallf1860e52010-05-20 23:23:51 +00003850
Richard Smith0b8220a2012-08-07 21:30:42 +00003851 if (!Init)
3852 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003853
Richard Smith0b8220a2012-08-07 21:30:42 +00003854 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003855}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003856
3857bool
3858Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3859 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003860 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003861 Constructor->setNumCtorInitializers(1);
3862 CXXCtorInitializer **initializer =
3863 new (Context) CXXCtorInitializer*[1];
3864 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3865 Constructor->setCtorInitializers(initializer);
3866
Sean Huntb76af9c2011-05-03 23:05:34 +00003867 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003868 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003869 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3870 }
3871
Sean Huntc1598702011-05-05 00:05:47 +00003872 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003873
Stephen Hines176edba2014-12-01 14:53:08 -08003874 DiagnoseUninitializedFields(*this, Constructor);
3875
Sean Hunt059ce0d2011-05-01 07:04:31 +00003876 return false;
3877}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003878
David Blaikie93c86172013-01-17 05:26:25 +00003879bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3880 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003881 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003882 // Just store the initializers as written, they will be checked during
3883 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003884 if (!Initializers.empty()) {
3885 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003886 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003887 new (Context) CXXCtorInitializer*[Initializers.size()];
3888 memcpy(baseOrMemberInitializers, Initializers.data(),
3889 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003890 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003891 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003892
3893 // Let template instantiation know whether we had errors.
3894 if (AnyErrors)
3895 Constructor->setInvalidDecl();
3896
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003897 return false;
3898 }
3899
John McCallf1860e52010-05-20 23:23:51 +00003900 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003901
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003902 // We need to build the initializer AST according to order of construction
3903 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003904 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003905 if (!ClassDecl)
3906 return true;
3907
Eli Friedman80c30da2009-11-09 19:20:36 +00003908 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003909
David Blaikie93c86172013-01-17 05:26:25 +00003910 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003911 CXXCtorInitializer *Member = Initializers[i];
Richard Smithcbc820a2013-07-22 02:56:56 +00003912
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003913 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003914 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Stephen Hines651f13c2014-04-23 16:59:28 -07003915 else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003916 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
Stephen Hines651f13c2014-04-23 16:59:28 -07003917
3918 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
3919 for (auto *C : F->chain()) {
3920 FieldDecl *FD = dyn_cast<FieldDecl>(C);
3921 if (FD && FD->getParent()->isUnion())
3922 Info.ActiveUnionMember.insert(std::make_pair(
3923 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3924 }
3925 } else if (FieldDecl *FD = Member->getMember()) {
3926 if (FD->getParent()->isUnion())
3927 Info.ActiveUnionMember.insert(std::make_pair(
3928 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3929 }
3930 }
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003931 }
3932
Anders Carlsson711f34a2010-04-21 19:52:01 +00003933 // Keep track of the direct virtual bases.
3934 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Stephen Hines651f13c2014-04-23 16:59:28 -07003935 for (auto &I : ClassDecl->bases()) {
3936 if (I.isVirtual())
3937 DirectVBases.insert(&I);
Anders Carlsson711f34a2010-04-21 19:52:01 +00003938 }
3939
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003940 // Push virtual bases before others.
Stephen Hines651f13c2014-04-23 16:59:28 -07003941 for (auto &VBase : ClassDecl->vbases()) {
Sean Huntcbb67482011-01-08 20:30:50 +00003942 if (CXXCtorInitializer *Value
Stephen Hines651f13c2014-04-23 16:59:28 -07003943 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithcbc820a2013-07-22 02:56:56 +00003944 // [class.base.init]p7, per DR257:
3945 // A mem-initializer where the mem-initializer-id names a virtual base
3946 // class is ignored during execution of a constructor of any class that
3947 // is not the most derived class.
3948 if (ClassDecl->isAbstract()) {
3949 // FIXME: Provide a fixit to remove the base specifier. This requires
3950 // tracking the location of the associated comma for a base specifier.
3951 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Stephen Hines651f13c2014-04-23 16:59:28 -07003952 << VBase.getType() << ClassDecl;
Richard Smithcbc820a2013-07-22 02:56:56 +00003953 DiagnoseAbstractType(ClassDecl);
3954 }
3955
John McCallf1860e52010-05-20 23:23:51 +00003956 Info.AllToInit.push_back(Value);
Richard Smithcbc820a2013-07-22 02:56:56 +00003957 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3958 // [class.base.init]p8, per DR257:
3959 // If a given [...] base class is not named by a mem-initializer-id
3960 // [...] and the entity is not a virtual base class of an abstract
3961 // class, then [...] the entity is default-initialized.
Stephen Hines651f13c2014-04-23 16:59:28 -07003962 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003963 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003964 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Stephen Hines651f13c2014-04-23 16:59:28 -07003965 &VBase, IsInheritedVirtualBase,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003966 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003967 HadError = true;
3968 continue;
3969 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003970
John McCallf1860e52010-05-20 23:23:51 +00003971 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003972 }
3973 }
Mike Stump1eb44332009-09-09 15:08:12 +00003974
John McCallf1860e52010-05-20 23:23:51 +00003975 // Non-virtual bases.
Stephen Hines651f13c2014-04-23 16:59:28 -07003976 for (auto &Base : ClassDecl->bases()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003977 // Virtuals are in the virtual base list and already constructed.
Stephen Hines651f13c2014-04-23 16:59:28 -07003978 if (Base.isVirtual())
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003979 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003980
Sean Huntcbb67482011-01-08 20:30:50 +00003981 if (CXXCtorInitializer *Value
Stephen Hines651f13c2014-04-23 16:59:28 -07003982 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallf1860e52010-05-20 23:23:51 +00003983 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003984 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003985 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003986 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Stephen Hines651f13c2014-04-23 16:59:28 -07003987 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003988 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003989 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003990 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003991 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003992
John McCallf1860e52010-05-20 23:23:51 +00003993 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003994 }
3995 }
Mike Stump1eb44332009-09-09 15:08:12 +00003996
John McCallf1860e52010-05-20 23:23:51 +00003997 // Fields.
Stephen Hines651f13c2014-04-23 16:59:28 -07003998 for (auto *Mem : ClassDecl->decls()) {
3999 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00004000 // C++ [class.bit]p2:
4001 // A declaration for a bit-field that omits the identifier declares an
4002 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
4003 // initialized.
4004 if (F->isUnnamedBitfield())
4005 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00004006
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004007 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00004008 // handle anonymous struct/union fields based on their individual
4009 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00004010 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00004011 continue;
4012
4013 if (CollectFieldInitializer(*this, Info, F))
4014 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00004015 continue;
4016 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00004017
4018 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00004019 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00004020 continue;
4021
Stephen Hines651f13c2014-04-23 16:59:28 -07004022 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00004023 if (F->getType()->isIncompleteArrayType()) {
4024 assert(ClassDecl->hasFlexibleArrayMember() &&
4025 "Incomplete array type is not valid");
4026 continue;
4027 }
4028
Douglas Gregor4dc41c92011-08-10 15:22:55 +00004029 // Initialize each field of an anonymous struct individually.
4030 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4031 HadError = true;
4032
4033 continue;
4034 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00004035 }
Mike Stump1eb44332009-09-09 15:08:12 +00004036
David Blaikie93c86172013-01-17 05:26:25 +00004037 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00004038 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00004039 Constructor->setNumCtorInitializers(NumInitializers);
4040 CXXCtorInitializer **baseOrMemberInitializers =
4041 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00004042 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00004043 NumInitializers * sizeof(CXXCtorInitializer*));
4044 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00004045
John McCallef027fe2010-03-16 21:39:52 +00004046 // Constructors implicitly reference the base and member
4047 // destructors.
4048 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4049 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00004050 }
Eli Friedman80c30da2009-11-09 19:20:36 +00004051
4052 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00004053}
4054
David Blaikieee000bb2013-01-17 08:49:22 +00004055static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004056 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00004057 const RecordDecl *RD = RT->getDecl();
4058 if (RD->isAnonymousStructOrUnion()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004059 for (auto *Field : RD->fields())
4060 PopulateKeysForFields(Field, IdealInits);
David Blaikieee000bb2013-01-17 08:49:22 +00004061 return;
4062 }
Eli Friedman6347f422009-07-21 19:28:10 +00004063 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004064 IdealInits.push_back(Field->getCanonicalDecl());
Eli Friedman6347f422009-07-21 19:28:10 +00004065}
4066
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00004067static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4068 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssoncdc83c72009-09-01 06:22:14 +00004069}
4070
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00004071static const void *GetKeyForMember(ASTContext &Context,
4072 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00004073 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00004074 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00004075
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004076 return Member->getAnyMember()->getCanonicalDecl();
Eli Friedman6347f422009-07-21 19:28:10 +00004077}
4078
David Blaikie93c86172013-01-17 05:26:25 +00004079static void DiagnoseBaseOrMemInitializerOrder(
4080 Sema &SemaRef, const CXXConstructorDecl *Constructor,
4081 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00004082 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00004083 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004084
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004085 // Don't check initializers order unless the warning is enabled at the
4086 // location of at least one initializer.
4087 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00004088 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00004089 CXXCtorInitializer *Init = Inits[InitIndex];
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004090 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4091 Init->getSourceLocation())) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004092 ShouldCheckOrder = true;
4093 break;
4094 }
4095 }
4096 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00004097 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00004098
John McCalld6ca8da2010-04-10 07:37:23 +00004099 // Build the list of bases and members in the order that they'll
4100 // actually be initialized. The explicit initializers should be in
4101 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004102 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00004103
Anders Carlsson071d6102010-04-02 03:38:04 +00004104 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4105
John McCalld6ca8da2010-04-10 07:37:23 +00004106 // 1. Virtual bases.
Stephen Hines651f13c2014-04-23 16:59:28 -07004107 for (const auto &VBase : ClassDecl->vbases())
4108 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00004109
John McCalld6ca8da2010-04-10 07:37:23 +00004110 // 2. Non-virtual bases.
Stephen Hines651f13c2014-04-23 16:59:28 -07004111 for (const auto &Base : ClassDecl->bases()) {
4112 if (Base.isVirtual())
Anders Carlsson5c36fb22009-08-27 05:45:01 +00004113 continue;
Stephen Hines651f13c2014-04-23 16:59:28 -07004114 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00004115 }
Mike Stump1eb44332009-09-09 15:08:12 +00004116
John McCalld6ca8da2010-04-10 07:37:23 +00004117 // 3. Direct fields.
Stephen Hines651f13c2014-04-23 16:59:28 -07004118 for (auto *Field : ClassDecl->fields()) {
Douglas Gregord61db332011-10-10 17:22:13 +00004119 if (Field->isUnnamedBitfield())
4120 continue;
4121
Stephen Hines651f13c2014-04-23 16:59:28 -07004122 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00004123 }
4124
John McCalld6ca8da2010-04-10 07:37:23 +00004125 unsigned NumIdealInits = IdealInitKeys.size();
4126 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00004127
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004128 CXXCtorInitializer *PrevInit = nullptr;
David Blaikie93c86172013-01-17 05:26:25 +00004129 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00004130 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00004131 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00004132
4133 // Scan forward to try to find this initializer in the idealized
4134 // initializers list.
4135 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4136 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00004137 break;
John McCalld6ca8da2010-04-10 07:37:23 +00004138
4139 // If we didn't find this initializer, it must be because we
4140 // scanned past it on a previous iteration. That can only
4141 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00004142 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00004143 Sema::SemaDiagnosticBuilder D =
4144 SemaRef.Diag(PrevInit->getSourceLocation(),
4145 diag::warn_initializer_out_of_order);
4146
Francois Pichet00eb3f92010-12-04 09:14:42 +00004147 if (PrevInit->isAnyMemberInitializer())
4148 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00004149 else
Douglas Gregor76852c22011-11-01 01:16:03 +00004150 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00004151
Francois Pichet00eb3f92010-12-04 09:14:42 +00004152 if (Init->isAnyMemberInitializer())
4153 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00004154 else
Douglas Gregor76852c22011-11-01 01:16:03 +00004155 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00004156
4157 // Move back to the initializer's location in the ideal list.
4158 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4159 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00004160 break;
John McCalld6ca8da2010-04-10 07:37:23 +00004161
4162 assert(IdealIndex != NumIdealInits &&
4163 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00004164 }
John McCalld6ca8da2010-04-10 07:37:23 +00004165
4166 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00004167 }
Anders Carlssona7b35212009-03-25 02:58:17 +00004168}
4169
John McCall3c3ccdb2010-04-10 09:28:51 +00004170namespace {
4171bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00004172 CXXCtorInitializer *Init,
4173 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00004174 if (!PrevInit) {
4175 PrevInit = Init;
4176 return false;
4177 }
4178
Douglas Gregordc392c12013-03-25 23:28:23 +00004179 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00004180 S.Diag(Init->getSourceLocation(),
4181 diag::err_multiple_mem_initialization)
4182 << Field->getDeclName()
4183 << Init->getSourceRange();
4184 else {
John McCallf4c73712011-01-19 06:33:43 +00004185 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00004186 assert(BaseClass && "neither field nor base");
4187 S.Diag(Init->getSourceLocation(),
4188 diag::err_multiple_base_initialization)
4189 << QualType(BaseClass, 0)
4190 << Init->getSourceRange();
4191 }
4192 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4193 << 0 << PrevInit->getSourceRange();
4194
4195 return true;
4196}
4197
Sean Huntcbb67482011-01-08 20:30:50 +00004198typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00004199typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4200
4201bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00004202 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00004203 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00004204 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00004205 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00004206 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00004207
4208 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00004209 if (Parent->isUnion()) {
4210 UnionEntry &En = Unions[Parent];
4211 if (En.first && En.first != Child) {
4212 S.Diag(Init->getSourceLocation(),
4213 diag::err_multiple_mem_union_initialization)
4214 << Field->getDeclName()
4215 << Init->getSourceRange();
4216 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4217 << 0 << En.second->getSourceRange();
4218 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00004219 }
4220 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00004221 En.first = Child;
4222 En.second = Init;
4223 }
David Blaikie6fe29652011-11-17 06:01:57 +00004224 if (!Parent->isAnonymousStructOrUnion())
4225 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00004226 }
4227
4228 Child = Parent;
4229 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00004230 }
John McCall3c3ccdb2010-04-10 09:28:51 +00004231
4232 return false;
4233}
4234}
4235
Anders Carlsson58cfbde2010-04-02 03:37:03 +00004236/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00004237void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00004238 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00004239 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00004240 bool AnyErrors) {
4241 if (!ConstructorDecl)
4242 return;
4243
4244 AdjustDeclIfTemplate(ConstructorDecl);
4245
4246 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00004247 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00004248
4249 if (!Constructor) {
4250 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4251 return;
4252 }
4253
John McCall3c3ccdb2010-04-10 09:28:51 +00004254 // Mapping for the duplicate initializers check.
4255 // For member initializers, this is keyed with a FieldDecl*.
4256 // For base initializers, this is keyed with a Type*.
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00004257 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00004258
4259 // Mapping for the inconsistent anonymous-union initializers check.
4260 RedundantUnionMap MemberUnions;
4261
Anders Carlssonea356fb2010-04-02 05:42:15 +00004262 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00004263 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00004264 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00004265
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00004266 // Set the source order index.
4267 Init->setSourceOrder(i);
4268
Francois Pichet00eb3f92010-12-04 09:14:42 +00004269 if (Init->isAnyMemberInitializer()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004270 const void *Key = GetKeyForMember(Context, Init);
4271 if (CheckRedundantInit(*this, Init, Members[Key]) ||
John McCall3c3ccdb2010-04-10 09:28:51 +00004272 CheckRedundantUnionInit(*this, Init, MemberUnions))
4273 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00004274 } else if (Init->isBaseInitializer()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004275 const void *Key = GetKeyForMember(Context, Init);
John McCall3c3ccdb2010-04-10 09:28:51 +00004276 if (CheckRedundantInit(*this, Init, Members[Key]))
4277 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00004278 } else {
4279 assert(Init->isDelegatingInitializer());
4280 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00004281 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00004282 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00004283 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00004284 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00004285 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00004286 }
Sean Huntfe57eef2011-05-04 05:57:24 +00004287 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00004288 // Return immediately as the initializer is set.
4289 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00004290 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00004291 }
4292
Anders Carlssonea356fb2010-04-02 05:42:15 +00004293 if (HadError)
4294 return;
4295
David Blaikie93c86172013-01-17 05:26:25 +00004296 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00004297
David Blaikie93c86172013-01-17 05:26:25 +00004298 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu225e9822013-09-16 21:54:53 +00004299
Richard Trieu858d2ba2013-10-25 00:56:00 +00004300 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00004301}
4302
Fariborz Jahanian34374e62009-09-03 23:18:17 +00004303void
John McCallef027fe2010-03-16 21:39:52 +00004304Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4305 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00004306 // Ignore dependent contexts. Also ignore unions, since their members never
4307 // have destructors implicitly called.
4308 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00004309 return;
John McCall58e6f342010-03-16 05:22:47 +00004310
4311 // FIXME: all the access-control diagnostics are positioned on the
4312 // field/base declaration. That's probably good; that said, the
4313 // user might reasonably want to know why the destructor is being
4314 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00004315
Anders Carlsson9f853df2009-11-17 04:44:12 +00004316 // Non-static data members.
Stephen Hines651f13c2014-04-23 16:59:28 -07004317 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00004318 if (Field->isInvalidDecl())
4319 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00004320
4321 // Don't destroy incomplete or zero-length arrays.
4322 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4323 continue;
4324
Anders Carlsson9f853df2009-11-17 04:44:12 +00004325 QualType FieldType = Context.getBaseElementType(Field->getType());
4326
4327 const RecordType* RT = FieldType->getAs<RecordType>();
4328 if (!RT)
4329 continue;
4330
4331 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00004332 if (FieldClassDecl->isInvalidDecl())
4333 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00004334 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00004335 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00004336 // The destructor for an implicit anonymous union member is never invoked.
4337 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4338 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00004339
Douglas Gregordb89f282010-07-01 22:47:18 +00004340 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00004341 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00004342 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004343 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00004344 << Field->getDeclName()
4345 << FieldType);
4346
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00004347 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00004348 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00004349 }
4350
John McCall58e6f342010-03-16 05:22:47 +00004351 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4352
Anders Carlsson9f853df2009-11-17 04:44:12 +00004353 // Bases.
Stephen Hines651f13c2014-04-23 16:59:28 -07004354 for (const auto &Base : ClassDecl->bases()) {
John McCall58e6f342010-03-16 05:22:47 +00004355 // Bases are always records in a well-formed non-dependent class.
Stephen Hines651f13c2014-04-23 16:59:28 -07004356 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00004357
4358 // Remember direct virtual bases.
Stephen Hines651f13c2014-04-23 16:59:28 -07004359 if (Base.isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00004360 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00004361
John McCall58e6f342010-03-16 05:22:47 +00004362 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00004363 // If our base class is invalid, we probably can't get its dtor anyway.
4364 if (BaseClassDecl->isInvalidDecl())
4365 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00004366 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00004367 continue;
John McCall58e6f342010-03-16 05:22:47 +00004368
Douglas Gregordb89f282010-07-01 22:47:18 +00004369 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00004370 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00004371
4372 // FIXME: caret should be on the start of the class name
Stephen Hines651f13c2014-04-23 16:59:28 -07004373 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004374 PDiag(diag::err_access_dtor_base)
Stephen Hines651f13c2014-04-23 16:59:28 -07004375 << Base.getType()
4376 << Base.getSourceRange(),
John McCallb9abd8722012-04-07 03:04:20 +00004377 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00004378
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00004379 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00004380 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00004381 }
4382
4383 // Virtual bases.
Stephen Hines651f13c2014-04-23 16:59:28 -07004384 for (const auto &VBase : ClassDecl->vbases()) {
John McCall58e6f342010-03-16 05:22:47 +00004385 // Bases are always records in a well-formed non-dependent class.
Stephen Hines651f13c2014-04-23 16:59:28 -07004386 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00004387
4388 // Ignore direct virtual bases.
4389 if (DirectVirtualBases.count(RT))
4390 continue;
4391
John McCall58e6f342010-03-16 05:22:47 +00004392 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00004393 // If our base class is invalid, we probably can't get its dtor anyway.
4394 if (BaseClassDecl->isInvalidDecl())
4395 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00004396 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00004397 continue;
John McCall58e6f342010-03-16 05:22:47 +00004398
Douglas Gregordb89f282010-07-01 22:47:18 +00004399 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00004400 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer2f686692013-06-22 06:43:58 +00004401 if (CheckDestructorAccess(
4402 ClassDecl->getLocation(), Dtor,
4403 PDiag(diag::err_access_dtor_vbase)
Stephen Hines651f13c2014-04-23 16:59:28 -07004404 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer2f686692013-06-22 06:43:58 +00004405 Context.getTypeDeclType(ClassDecl)) ==
4406 AR_accessible) {
4407 CheckDerivedToBaseConversion(
Stephen Hines651f13c2014-04-23 16:59:28 -07004408 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer2f686692013-06-22 06:43:58 +00004409 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004410 SourceRange(), DeclarationName(), nullptr);
David Majnemer2f686692013-06-22 06:43:58 +00004411 }
John McCall58e6f342010-03-16 05:22:47 +00004412
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00004413 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00004414 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00004415 }
4416}
4417
John McCalld226f652010-08-21 09:40:31 +00004418void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00004419 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00004420 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004421
Mike Stump1eb44332009-09-09 15:08:12 +00004422 if (CXXConstructorDecl *Constructor
Richard Trieu858d2ba2013-10-25 00:56:00 +00004423 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie93c86172013-01-17 05:26:25 +00004424 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieu858d2ba2013-10-25 00:56:00 +00004425 DiagnoseUninitializedFields(*this, Constructor);
4426 }
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00004427}
4428
Mike Stump1eb44332009-09-09 15:08:12 +00004429bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00004430 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004431 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4432 unsigned DiagID;
4433 AbstractDiagSelID SelID;
4434
4435 public:
4436 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4437 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00004438
Stephen Hines651f13c2014-04-23 16:59:28 -07004439 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Eli Friedman2217f852012-08-14 02:06:07 +00004440 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004441 if (SelID == -1)
4442 S.Diag(Loc, DiagID) << T;
4443 else
4444 S.Diag(Loc, DiagID) << SelID << T;
4445 }
4446 } Diagnoser(DiagID, SelID);
4447
4448 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00004449}
4450
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00004451bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004452 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00004453 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004454 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004455
Anders Carlsson11f21a02009-03-23 19:10:31 +00004456 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004457 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00004458
Ted Kremenek6217b802009-07-29 21:53:49 +00004459 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004460 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004461 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004462 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00004463
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004464 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004465 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004466 }
Mike Stump1eb44332009-09-09 15:08:12 +00004467
Ted Kremenek6217b802009-07-29 21:53:49 +00004468 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004469 if (!RT)
4470 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004471
John McCall86ff3082010-02-04 22:26:26 +00004472 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004473
John McCall94c3b562010-08-18 09:41:07 +00004474 // We can't answer whether something is abstract until it has a
4475 // definition. If it's currently being defined, we'll walk back
4476 // over all the declarations when we have a full definition.
4477 const CXXRecordDecl *Def = RD->getDefinition();
4478 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00004479 return false;
4480
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004481 if (!RD->isAbstract())
4482 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004483
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004484 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00004485 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00004486
John McCall94c3b562010-08-18 09:41:07 +00004487 return true;
4488}
4489
4490void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4491 // Check if we've already emitted the list of pure virtual functions
4492 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004493 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00004494 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004495
Richard Smithcbc820a2013-07-22 02:56:56 +00004496 // If the diagnostic is suppressed, don't emit the notes. We're only
4497 // going to emit them once, so try to attach them to a diagnostic we're
4498 // actually going to show.
4499 if (Diags.isLastDiagnosticIgnored())
4500 return;
4501
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004502 CXXFinalOverriderMap FinalOverriders;
4503 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00004504
Anders Carlssonffdb2d22010-06-03 01:00:02 +00004505 // Keep a set of seen pure methods so we won't diagnose the same method
4506 // more than once.
4507 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4508
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004509 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4510 MEnd = FinalOverriders.end();
4511 M != MEnd;
4512 ++M) {
4513 for (OverridingMethods::iterator SO = M->second.begin(),
4514 SOEnd = M->second.end();
4515 SO != SOEnd; ++SO) {
4516 // C++ [class.abstract]p4:
4517 // A class is abstract if it contains or inherits at least one
4518 // pure virtual function for which the final overrider is pure
4519 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00004520
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004521 //
4522 if (SO->second.size() != 1)
4523 continue;
4524
4525 if (!SO->second.front().Method->isPure())
4526 continue;
4527
Stephen Hines176edba2014-12-01 14:53:08 -08004528 if (!SeenPureMethods.insert(SO->second.front().Method).second)
Anders Carlssonffdb2d22010-06-03 01:00:02 +00004529 continue;
4530
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004531 Diag(SO->second.front().Method->getLocation(),
4532 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00004533 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004534 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004535 }
4536
4537 if (!PureVirtualClassDiagSet)
4538 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4539 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004540}
4541
Anders Carlsson8211eff2009-03-24 01:19:16 +00004542namespace {
John McCall94c3b562010-08-18 09:41:07 +00004543struct AbstractUsageInfo {
4544 Sema &S;
4545 CXXRecordDecl *Record;
4546 CanQualType AbstractType;
4547 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00004548
John McCall94c3b562010-08-18 09:41:07 +00004549 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4550 : S(S), Record(Record),
4551 AbstractType(S.Context.getCanonicalType(
4552 S.Context.getTypeDeclType(Record))),
4553 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00004554
John McCall94c3b562010-08-18 09:41:07 +00004555 void DiagnoseAbstractType() {
4556 if (Invalid) return;
4557 S.DiagnoseAbstractType(Record);
4558 Invalid = true;
4559 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00004560
John McCall94c3b562010-08-18 09:41:07 +00004561 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4562};
4563
4564struct CheckAbstractUsage {
4565 AbstractUsageInfo &Info;
4566 const NamedDecl *Ctx;
4567
4568 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4569 : Info(Info), Ctx(Ctx) {}
4570
4571 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4572 switch (TL.getTypeLocClass()) {
4573#define ABSTRACT_TYPELOC(CLASS, PARENT)
4574#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00004575 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00004576#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00004577 }
John McCall94c3b562010-08-18 09:41:07 +00004578 }
Mike Stump1eb44332009-09-09 15:08:12 +00004579
John McCall94c3b562010-08-18 09:41:07 +00004580 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004581 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
4582 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4583 if (!TL.getParam(I))
Douglas Gregor70191862011-02-22 23:21:06 +00004584 continue;
Stephen Hines651f13c2014-04-23 16:59:28 -07004585
4586 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall94c3b562010-08-18 09:41:07 +00004587 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004588 }
John McCall94c3b562010-08-18 09:41:07 +00004589 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004590
John McCall94c3b562010-08-18 09:41:07 +00004591 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4592 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4593 }
Mike Stump1eb44332009-09-09 15:08:12 +00004594
John McCall94c3b562010-08-18 09:41:07 +00004595 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4596 // Visit the type parameters from a permissive context.
4597 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4598 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4599 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4600 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4601 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4602 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00004603 }
John McCall94c3b562010-08-18 09:41:07 +00004604 }
Mike Stump1eb44332009-09-09 15:08:12 +00004605
John McCall94c3b562010-08-18 09:41:07 +00004606 // Visit pointee types from a permissive context.
4607#define CheckPolymorphic(Type) \
4608 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4609 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4610 }
4611 CheckPolymorphic(PointerTypeLoc)
4612 CheckPolymorphic(ReferenceTypeLoc)
4613 CheckPolymorphic(MemberPointerTypeLoc)
4614 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00004615 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00004616
John McCall94c3b562010-08-18 09:41:07 +00004617 /// Handle all the types we haven't given a more specific
4618 /// implementation for above.
4619 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4620 // Every other kind of type that we haven't called out already
4621 // that has an inner type is either (1) sugar or (2) contains that
4622 // inner type in some way as a subobject.
4623 if (TypeLoc Next = TL.getNextTypeLoc())
4624 return Visit(Next, Sel);
4625
4626 // If there's no inner type and we're in a permissive context,
4627 // don't diagnose.
4628 if (Sel == Sema::AbstractNone) return;
4629
4630 // Check whether the type matches the abstract type.
4631 QualType T = TL.getType();
4632 if (T->isArrayType()) {
4633 Sel = Sema::AbstractArrayType;
4634 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004635 }
John McCall94c3b562010-08-18 09:41:07 +00004636 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4637 if (CT != Info.AbstractType) return;
4638
4639 // It matched; do some magic.
4640 if (Sel == Sema::AbstractArrayType) {
4641 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4642 << T << TL.getSourceRange();
4643 } else {
4644 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4645 << Sel << T << TL.getSourceRange();
4646 }
4647 Info.DiagnoseAbstractType();
4648 }
4649};
4650
4651void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4652 Sema::AbstractDiagSelID Sel) {
4653 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4654}
4655
4656}
4657
4658/// Check for invalid uses of an abstract type in a method declaration.
4659static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4660 CXXMethodDecl *MD) {
4661 // No need to do the check on definitions, which require that
4662 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00004663 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00004664 return;
4665
4666 // For safety's sake, just ignore it if we don't have type source
4667 // information. This should never happen for non-implicit methods,
4668 // but...
4669 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4670 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4671}
4672
4673/// Check for invalid uses of an abstract type within a class definition.
4674static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4675 CXXRecordDecl *RD) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004676 for (auto *D : RD->decls()) {
John McCall94c3b562010-08-18 09:41:07 +00004677 if (D->isImplicit()) continue;
4678
4679 // Methods and method templates.
4680 if (isa<CXXMethodDecl>(D)) {
4681 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4682 } else if (isa<FunctionTemplateDecl>(D)) {
4683 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4684 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4685
4686 // Fields and static variables.
4687 } else if (isa<FieldDecl>(D)) {
4688 FieldDecl *FD = cast<FieldDecl>(D);
4689 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4690 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4691 } else if (isa<VarDecl>(D)) {
4692 VarDecl *VD = cast<VarDecl>(D);
4693 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4694 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4695
4696 // Nested classes and class templates.
4697 } else if (isa<CXXRecordDecl>(D)) {
4698 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4699 } else if (isa<ClassTemplateDecl>(D)) {
4700 CheckAbstractClassUsage(Info,
4701 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4702 }
4703 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004704}
4705
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004706/// \brief Check class-level dllimport/dllexport attribute.
4707static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) {
4708 Attr *ClassAttr = getDLLAttr(Class);
Stephen Hines176edba2014-12-01 14:53:08 -08004709
4710 // MSVC inherits DLL attributes to partial class template specializations.
4711 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
4712 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4713 if (Attr *TemplateAttr =
4714 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
4715 auto *A = cast<InheritableAttr>(TemplateAttr->clone(S.getASTContext()));
4716 A->setInherited(true);
4717 ClassAttr = A;
4718 }
4719 }
4720 }
4721
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004722 if (!ClassAttr)
4723 return;
4724
Stephen Hines176edba2014-12-01 14:53:08 -08004725 if (!Class->isExternallyVisible()) {
4726 S.Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
4727 << Class << ClassAttr;
4728 return;
4729 }
4730
4731 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4732 !ClassAttr->isInherited()) {
4733 // Diagnose dll attributes on members of class with dll attribute.
4734 for (Decl *Member : Class->decls()) {
4735 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4736 continue;
4737 InheritableAttr *MemberAttr = getDLLAttr(Member);
4738 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4739 continue;
4740
4741 S.Diag(MemberAttr->getLocation(),
4742 diag::err_attribute_dll_member_of_dll_class)
4743 << MemberAttr << ClassAttr;
4744 S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4745 Member->setInvalidDecl();
4746 }
4747 }
4748
4749 if (Class->getDescribedClassTemplate())
4750 // Don't inherit dll attribute until the template is instantiated.
4751 return;
4752
4753 // The class is either imported or exported.
4754 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4755 const bool ClassImported = !ClassExported;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004756
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004757 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
4758
4759 // Don't dllexport explicit class template instantiation declarations.
4760 if (ClassExported && TSK == TSK_ExplicitInstantiationDeclaration) {
4761 Class->dropAttr<DLLExportAttr>();
4762 return;
4763 }
4764
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004765 // Force declaration of implicit members so they can inherit the attribute.
4766 S.ForceDeclarationOfImplicitMembers(Class);
4767
4768 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4769 // seem to be true in practice?
4770
4771 for (Decl *Member : Class->decls()) {
4772 VarDecl *VD = dyn_cast<VarDecl>(Member);
4773 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4774
4775 // Only methods and static fields inherit the attributes.
4776 if (!VD && !MD)
4777 continue;
4778
Stephen Hines176edba2014-12-01 14:53:08 -08004779 if (MD) {
4780 // Don't process deleted methods.
4781 if (MD->isDeleted())
4782 continue;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004783
Stephen Hines176edba2014-12-01 14:53:08 -08004784 if (MD->isMoveAssignmentOperator() && ClassImported && MD->isInlined()) {
4785 // Current MSVC versions don't export the move assignment operators, so
4786 // don't attempt to import them if we have a definition.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004787 continue;
4788 }
Stephen Hines176edba2014-12-01 14:53:08 -08004789
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004790 if (MD->isInlined() &&
Stephen Hines176edba2014-12-01 14:53:08 -08004791 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004792 // MinGW does not import or export inline methods.
Stephen Hines176edba2014-12-01 14:53:08 -08004793 continue;
4794 }
4795 }
4796
4797 if (!getDLLAttr(Member)) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004798 auto *NewAttr =
4799 cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
4800 NewAttr->setInherited(true);
4801 Member->addAttr(NewAttr);
4802 }
4803
Stephen Hines176edba2014-12-01 14:53:08 -08004804 if (MD && ClassExported) {
4805 if (MD->isUserProvided()) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004806 // Instantiate non-default class member functions ...
Stephen Hines176edba2014-12-01 14:53:08 -08004807
4808 // .. except for certain kinds of template specializations.
4809 if (TSK == TSK_ExplicitInstantiationDeclaration)
4810 continue;
4811 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4812 continue;
4813
4814 S.MarkFunctionReferenced(Class->getLocation(), MD);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004815
4816 // The function will be passed to the consumer when its definition is
4817 // encountered.
Stephen Hines176edba2014-12-01 14:53:08 -08004818 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4819 MD->isCopyAssignmentOperator() ||
4820 MD->isMoveAssignmentOperator()) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004821 // Synthesize and instantiate non-trivial implicit methods, explicitly
4822 // defaulted methods, and the copy and move assignment operators. The
4823 // latter are exported even if they are trivial, because the address of
4824 // an operator can be taken and should compare equal accross libraries.
4825 DiagnosticErrorTrap Trap(S.Diags);
Stephen Hines176edba2014-12-01 14:53:08 -08004826 S.MarkFunctionReferenced(Class->getLocation(), MD);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07004827 if (Trap.hasErrorOccurred()) {
4828 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
4829 << Class->getName() << !S.getLangOpts().CPlusPlus11;
4830 break;
4831 }
4832
4833 // There is no later point when we will see the definition of this
4834 // function, so pass it to the consumer now.
4835 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004836 }
4837 }
4838 }
4839}
4840
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004841/// \brief Perform semantic checks on a class definition that has been
4842/// completing, introducing implicitly-declared members, checking for
4843/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004844void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00004845 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004846 return;
4847
John McCall94c3b562010-08-18 09:41:07 +00004848 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4849 AbstractUsageInfo Info(*this, Record);
4850 CheckAbstractClassUsage(Info, Record);
4851 }
Douglas Gregor325e5932010-04-15 00:00:53 +00004852
4853 // If this is not an aggregate type and has no user-declared constructor,
4854 // complain about any non-static data members of reference or const scalar
4855 // type, since they will never get initializers.
4856 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00004857 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4858 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004859 bool Complained = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07004860 for (const auto *F : Record->fields()) {
Douglas Gregord61db332011-10-10 17:22:13 +00004861 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004862 continue;
4863
Douglas Gregor325e5932010-04-15 00:00:53 +00004864 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00004865 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004866 if (!Complained) {
4867 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4868 << Record->getTagKind() << Record;
4869 Complained = true;
4870 }
4871
4872 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4873 << F->getType()->isReferenceType()
4874 << F->getDeclName();
4875 }
4876 }
4877 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004878
Douglas Gregora6e937c2010-10-15 13:21:21 +00004879 if (Record->getIdentifier()) {
4880 // C++ [class.mem]p13:
4881 // If T is the name of a class, then each of the following shall have a
4882 // name different from T:
4883 // - every member of every anonymous union that is a member of class T.
4884 //
4885 // C++ [class.mem]p14:
4886 // In addition, if class T has a user-declared constructor (12.1), every
4887 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004888 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4889 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4890 ++I) {
4891 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004892 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4893 isa<IndirectFieldDecl>(D)) {
4894 Diag(D->getLocation(), diag::err_member_name_of_class)
4895 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004896 break;
4897 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004898 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004899 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004900
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004901 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004902 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004903 CXXDestructorDecl *dtor = Record->getDestructor();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004904 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4905 !Record->hasAttr<FinalAttr>())
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004906 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4907 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4908 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004909
David Majnemer7121bdb2013-10-18 00:33:31 +00004910 if (Record->isAbstract()) {
4911 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4912 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4913 << FA->isSpelledAsSealed();
4914 DiagnoseAbstractType(Record);
4915 }
David Blaikieb6b5b972012-09-21 03:21:07 +00004916 }
4917
Stephen Hines176edba2014-12-01 14:53:08 -08004918 bool HasMethodWithOverrideControl = false,
4919 HasOverridingMethodWithoutOverrideControl = false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004920 if (!Record->isDependentType()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004921 for (auto *M : Record->methods()) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004922 // See if a method overloads virtual methods in a base
4923 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004924 if (!M->isStatic())
Stephen Hines651f13c2014-04-23 16:59:28 -07004925 DiagnoseHiddenVirtualMethods(M);
Stephen Hines176edba2014-12-01 14:53:08 -08004926 if (M->hasAttr<OverrideAttr>())
4927 HasMethodWithOverrideControl = true;
4928 else if (M->size_overridden_methods() > 0)
4929 HasOverridingMethodWithoutOverrideControl = true;
Richard Smith1d28caf2012-12-11 01:14:52 +00004930 // Check whether the explicitly-defaulted special members are valid.
4931 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Stephen Hines651f13c2014-04-23 16:59:28 -07004932 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004933
4934 // For an explicitly defaulted or deleted special member, we defer
4935 // determining triviality until the class is complete. That time is now!
4936 if (!M->isImplicit() && !M->isUserProvided()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004937 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004938 if (CSM != CXXInvalid) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004939 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smith1d28caf2012-12-11 01:14:52 +00004940
4941 // Inform the class that we've finished declaring this member.
Stephen Hines651f13c2014-04-23 16:59:28 -07004942 Record->finishedDefaultedOrDeletedMember(M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004943 }
4944 }
4945 }
4946 }
4947
Stephen Hines176edba2014-12-01 14:53:08 -08004948 if (HasMethodWithOverrideControl &&
4949 HasOverridingMethodWithoutOverrideControl) {
4950 // At least one method has the 'override' control declared.
4951 // Diagnose all other overridden methods which do not have 'override' specified on them.
4952 for (auto *M : Record->methods())
4953 DiagnoseAbsenceOfOverrideControl(M);
4954 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004955
Stephen Hines651f13c2014-04-23 16:59:28 -07004956 // ms_struct is a request to use the same ABI rules as MSVC. Check
4957 // whether this class uses any C++ features that are implemented
4958 // completely differently in MSVC, and if so, emit a diagnostic.
4959 // That diagnostic defaults to an error, but we allow projects to
4960 // map it down to a warning (or ignore it). It's a fairly common
4961 // practice among users of the ms_struct pragma to mass-annotate
4962 // headers, sweeping up a bunch of types that the project doesn't
4963 // really rely on MSVC-compatible layout for. We must therefore
4964 // support "ms_struct except for C++ stuff" as a secondary ABI.
4965 if (Record->isMsStruct(Context) &&
4966 (Record->isPolymorphic() || Record->getNumBases())) {
4967 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Huntb2969b12013-10-11 20:19:00 +00004968 }
4969
Richard Smith07b0fdc2013-03-18 21:12:30 +00004970 // Declare inheriting constructors. We do this eagerly here because:
4971 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004972 // constructors from different classes.
4973 // - The lazy declaration of the other implicit constructors is so as to not
4974 // waste space and performance on classes that are not meant to be
4975 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004976 // have inheriting constructors.
4977 DeclareInheritingConstructors(Record);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004978
4979 checkDLLAttribute(*this, Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004980}
4981
Stephen Hines651f13c2014-04-23 16:59:28 -07004982/// Look up the special member function that would be called by a special
4983/// member function for a subobject of class type.
4984///
4985/// \param Class The class type of the subobject.
4986/// \param CSM The kind of special member function.
4987/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4988/// \param ConstRHS True if this is a copy operation with a const object
4989/// on its RHS, that is, if the argument to the outer special member
4990/// function is 'const' and this is not a field marked 'mutable'.
4991static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4992 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4993 unsigned FieldQuals, bool ConstRHS) {
4994 unsigned LHSQuals = 0;
4995 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4996 LHSQuals = FieldQuals;
4997
4998 unsigned RHSQuals = FieldQuals;
4999 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5000 RHSQuals = 0;
5001 else if (ConstRHS)
5002 RHSQuals |= Qualifiers::Const;
5003
5004 return S.LookupSpecialMember(Class, CSM,
5005 RHSQuals & Qualifiers::Const,
5006 RHSQuals & Qualifiers::Volatile,
5007 false,
5008 LHSQuals & Qualifiers::Const,
5009 LHSQuals & Qualifiers::Volatile);
5010}
5011
Richard Smith7756afa2012-06-10 05:43:50 +00005012/// Is the special member function which would be selected to perform the
5013/// specified operation on the specified class type a constexpr constructor?
5014static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5015 Sema::CXXSpecialMember CSM,
Stephen Hines651f13c2014-04-23 16:59:28 -07005016 unsigned Quals, bool ConstRHS) {
Richard Smith7756afa2012-06-10 05:43:50 +00005017 Sema::SpecialMemberOverloadResult *SMOR =
Stephen Hines651f13c2014-04-23 16:59:28 -07005018 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smith7756afa2012-06-10 05:43:50 +00005019 if (!SMOR || !SMOR->getMethod())
5020 // A constructor we wouldn't select can't be "involved in initializing"
5021 // anything.
5022 return true;
5023 return SMOR->getMethod()->isConstexpr();
5024}
5025
5026/// Determine whether the specified special member function would be constexpr
5027/// if it were implicitly defined.
5028static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5029 Sema::CXXSpecialMember CSM,
5030 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00005031 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00005032 return false;
5033
5034 // C++11 [dcl.constexpr]p4:
5035 // In the definition of a constexpr constructor [...]
Richard Smitha8942d72013-05-07 03:19:20 +00005036 bool Ctor = true;
Richard Smith7756afa2012-06-10 05:43:50 +00005037 switch (CSM) {
5038 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00005039 // Since default constructor lookup is essentially trivial (and cannot
5040 // involve, for instance, template instantiation), we compute whether a
5041 // defaulted default constructor is constexpr directly within CXXRecordDecl.
5042 //
5043 // This is important for performance; we need to know whether the default
5044 // constructor is constexpr to determine whether the type is a literal type.
5045 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
5046
Richard Smith7756afa2012-06-10 05:43:50 +00005047 case Sema::CXXCopyConstructor:
5048 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00005049 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00005050 break;
5051
5052 case Sema::CXXCopyAssignment:
5053 case Sema::CXXMoveAssignment:
Stephen Hines176edba2014-12-01 14:53:08 -08005054 if (!S.getLangOpts().CPlusPlus14)
Richard Smitha8942d72013-05-07 03:19:20 +00005055 return false;
5056 // In C++1y, we need to perform overload resolution.
5057 Ctor = false;
5058 break;
5059
Richard Smith7756afa2012-06-10 05:43:50 +00005060 case Sema::CXXDestructor:
5061 case Sema::CXXInvalid:
5062 return false;
5063 }
5064
5065 // -- if the class is a non-empty union, or for each non-empty anonymous
5066 // union member of a non-union class, exactly one non-static data member
5067 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00005068 //
5069 // If we squint, this is guaranteed, since exactly one non-static data member
5070 // will be initialized (if the constructor isn't deleted), we just don't know
5071 // which one.
Richard Smitha8942d72013-05-07 03:19:20 +00005072 if (Ctor && ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00005073 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00005074
5075 // -- the class shall not have any virtual base classes;
Richard Smitha8942d72013-05-07 03:19:20 +00005076 if (Ctor && ClassDecl->getNumVBases())
5077 return false;
5078
5079 // C++1y [class.copy]p26:
5080 // -- [the class] is a literal type, and
5081 if (!Ctor && !ClassDecl->isLiteral())
Richard Smith7756afa2012-06-10 05:43:50 +00005082 return false;
5083
5084 // -- every constructor involved in initializing [...] base class
5085 // sub-objects shall be a constexpr constructor;
Richard Smitha8942d72013-05-07 03:19:20 +00005086 // -- the assignment operator selected to copy/move each direct base
5087 // class is a constexpr function, and
Stephen Hines651f13c2014-04-23 16:59:28 -07005088 for (const auto &B : ClassDecl->bases()) {
5089 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smith7756afa2012-06-10 05:43:50 +00005090 if (!BaseType) continue;
5091
5092 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Stephen Hines651f13c2014-04-23 16:59:28 -07005093 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smith7756afa2012-06-10 05:43:50 +00005094 return false;
5095 }
5096
5097 // -- every constructor involved in initializing non-static data members
5098 // [...] shall be a constexpr constructor;
5099 // -- every non-static data member and base class sub-object shall be
5100 // initialized
Stephen Hines651f13c2014-04-23 16:59:28 -07005101 // -- for each non-static data member of X that is of class type (or array
Richard Smitha8942d72013-05-07 03:19:20 +00005102 // thereof), the assignment operator selected to copy/move that member is
5103 // a constexpr function
Stephen Hines651f13c2014-04-23 16:59:28 -07005104 for (const auto *F : ClassDecl->fields()) {
Richard Smith7756afa2012-06-10 05:43:50 +00005105 if (F->isInvalidDecl())
5106 continue;
Stephen Hines651f13c2014-04-23 16:59:28 -07005107 QualType BaseType = S.Context.getBaseElementType(F->getType());
5108 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00005109 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Stephen Hines651f13c2014-04-23 16:59:28 -07005110 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
5111 BaseType.getCVRQualifiers(),
5112 ConstArg && !F->isMutable()))
Richard Smith7756afa2012-06-10 05:43:50 +00005113 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00005114 }
5115 }
5116
5117 // All OK, it's constexpr!
5118 return true;
5119}
5120
Richard Smithb9d0b762012-07-27 04:22:15 +00005121static Sema::ImplicitExceptionSpecification
5122computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
5123 switch (S.getSpecialMember(MD)) {
5124 case Sema::CXXDefaultConstructor:
5125 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
5126 case Sema::CXXCopyConstructor:
5127 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
5128 case Sema::CXXCopyAssignment:
5129 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
5130 case Sema::CXXMoveConstructor:
5131 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
5132 case Sema::CXXMoveAssignment:
5133 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
5134 case Sema::CXXDestructor:
5135 return S.ComputeDefaultedDtorExceptionSpec(MD);
5136 case Sema::CXXInvalid:
5137 break;
5138 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00005139 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
5140 "only special members have implicit exception specs");
5141 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00005142}
5143
Reid Kleckneref072032013-08-27 23:08:25 +00005144static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
5145 CXXMethodDecl *MD) {
5146 FunctionProtoType::ExtProtoInfo EPI;
5147
5148 // Build an exception specification pointing back at this member.
Stephen Hines176edba2014-12-01 14:53:08 -08005149 EPI.ExceptionSpec.Type = EST_Unevaluated;
5150 EPI.ExceptionSpec.SourceDecl = MD;
Reid Kleckneref072032013-08-27 23:08:25 +00005151
5152 // Set the calling convention to the default for C++ instance methods.
5153 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
5154 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5155 /*IsCXXMethod=*/true));
5156 return EPI;
5157}
5158
Richard Smithb9d0b762012-07-27 04:22:15 +00005159void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
5160 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
5161 if (FPT->getExceptionSpecType() != EST_Unevaluated)
5162 return;
5163
Richard Smithdd25e802012-07-30 23:48:14 +00005164 // Evaluate the exception specification.
Stephen Hines176edba2014-12-01 14:53:08 -08005165 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
Stephen Hines651f13c2014-04-23 16:59:28 -07005166
Richard Smithdd25e802012-07-30 23:48:14 +00005167 // Update the type of the special member to use it.
Stephen Hines176edba2014-12-01 14:53:08 -08005168 UpdateExceptionSpec(MD, ESI);
Richard Smithdd25e802012-07-30 23:48:14 +00005169
5170 // A user-provided destructor can be defined outside the class. When that
5171 // happens, be sure to update the exception specification on both
5172 // declarations.
5173 const FunctionProtoType *CanonicalFPT =
5174 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
5175 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Stephen Hines176edba2014-12-01 14:53:08 -08005176 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
Richard Smithb9d0b762012-07-27 04:22:15 +00005177}
5178
Richard Smith3003e1d2012-05-15 04:39:51 +00005179void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
5180 CXXRecordDecl *RD = MD->getParent();
5181 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00005182
Richard Smith3003e1d2012-05-15 04:39:51 +00005183 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
5184 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00005185
5186 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00005187 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00005188 bool First = MD == MD->getCanonicalDecl();
5189
5190 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00005191
5192 // C++11 [dcl.fct.def.default]p1:
5193 // A function that is explicitly defaulted shall
5194 // -- be a special member function (checked elsewhere),
5195 // -- have the same type (except for ref-qualifiers, and except that a
5196 // copy operation can take a non-const reference) as an implicit
5197 // declaration, and
5198 // -- not have default arguments.
5199 unsigned ExpectedParams = 1;
5200 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
5201 ExpectedParams = 0;
5202 if (MD->getNumParams() != ExpectedParams) {
5203 // This also checks for default arguments: a copy or move constructor with a
5204 // default argument is classified as a default constructor, and assignment
5205 // operations and destructors can't have default arguments.
5206 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
5207 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00005208 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00005209 } else if (MD->isVariadic()) {
5210 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
5211 << CSM << MD->getSourceRange();
5212 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00005213 }
5214
Richard Smith3003e1d2012-05-15 04:39:51 +00005215 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00005216
Richard Smith7756afa2012-06-10 05:43:50 +00005217 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00005218 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00005219 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00005220 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00005221 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00005222
Richard Smith3003e1d2012-05-15 04:39:51 +00005223 QualType ReturnType = Context.VoidTy;
5224 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
5225 // Check for return type matching.
Stephen Hines651f13c2014-04-23 16:59:28 -07005226 ReturnType = Type->getReturnType();
Richard Smith3003e1d2012-05-15 04:39:51 +00005227 QualType ExpectedReturnType =
5228 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
5229 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
5230 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
5231 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
5232 HadError = true;
5233 }
5234
5235 // A defaulted special member cannot have cv-qualifiers.
5236 if (Type->getTypeQuals()) {
5237 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Stephen Hines176edba2014-12-01 14:53:08 -08005238 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
Richard Smith3003e1d2012-05-15 04:39:51 +00005239 HadError = true;
5240 }
5241 }
5242
5243 // Check for parameter type matching.
Stephen Hines651f13c2014-04-23 16:59:28 -07005244 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00005245 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00005246 if (ExpectedParams && ArgType->isReferenceType()) {
5247 // Argument must be reference to possibly-const T.
5248 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00005249 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00005250
5251 if (ReferentType.isVolatileQualified()) {
5252 Diag(MD->getLocation(),
5253 diag::err_defaulted_special_member_volatile_param) << CSM;
5254 HadError = true;
5255 }
5256
Richard Smith7756afa2012-06-10 05:43:50 +00005257 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00005258 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
5259 Diag(MD->getLocation(),
5260 diag::err_defaulted_special_member_copy_const_param)
5261 << (CSM == CXXCopyAssignment);
5262 // FIXME: Explain why this special member can't be const.
5263 } else {
5264 Diag(MD->getLocation(),
5265 diag::err_defaulted_special_member_move_const_param)
5266 << (CSM == CXXMoveAssignment);
5267 }
5268 HadError = true;
5269 }
Richard Smith3003e1d2012-05-15 04:39:51 +00005270 } else if (ExpectedParams) {
5271 // A copy assignment operator can take its argument by value, but a
5272 // defaulted one cannot.
5273 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00005274 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00005275 HadError = true;
5276 }
Sean Huntbe631222011-05-17 20:44:43 +00005277
Richard Smith61802452011-12-22 02:22:31 +00005278 // C++11 [dcl.fct.def.default]p2:
5279 // An explicitly-defaulted function may be declared constexpr only if it
5280 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00005281 // Do not apply this rule to members of class templates, since core issue 1358
5282 // makes such functions always instantiate to constexpr functions. For
Richard Smitha8942d72013-05-07 03:19:20 +00005283 // functions which cannot be constexpr (for non-constructors in C++11 and for
5284 // destructors in C++1y), this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00005285 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5286 HasConstParam);
Stephen Hines176edba2014-12-01 14:53:08 -08005287 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
Richard Smitha8942d72013-05-07 03:19:20 +00005288 : isa<CXXConstructorDecl>(MD)) &&
5289 MD->isConstexpr() && !Constexpr &&
Richard Smith3003e1d2012-05-15 04:39:51 +00005290 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5291 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smitha8942d72013-05-07 03:19:20 +00005292 // FIXME: Explain why the special member can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00005293 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00005294 }
Richard Smith1d28caf2012-12-11 01:14:52 +00005295
Richard Smith61802452011-12-22 02:22:31 +00005296 // and may have an explicit exception-specification only if it is compatible
5297 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00005298 if (Type->hasExceptionSpec()) {
5299 // Delay the check if this is the first declaration of the special member,
5300 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00005301 if (First) {
5302 // If the exception specification needs to be instantiated, do so now,
5303 // before we clobber it with an EST_Unevaluated specification below.
5304 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5305 InstantiateExceptionSpec(MD->getLocStart(), MD);
5306 Type = MD->getType()->getAs<FunctionProtoType>();
5307 }
Richard Smith1d28caf2012-12-11 01:14:52 +00005308 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00005309 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00005310 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5311 }
Richard Smith61802452011-12-22 02:22:31 +00005312
5313 // If a function is explicitly defaulted on its first declaration,
5314 if (First) {
5315 // -- it is implicitly considered to be constexpr if the implicit
5316 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00005317 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00005318
Richard Smith3003e1d2012-05-15 04:39:51 +00005319 // -- it is implicitly considered to have the same exception-specification
5320 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00005321 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
Stephen Hines176edba2014-12-01 14:53:08 -08005322 EPI.ExceptionSpec.Type = EST_Unevaluated;
5323 EPI.ExceptionSpec.SourceDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00005324 MD->setType(Context.getFunctionType(ReturnType,
Stephen Hines176edba2014-12-01 14:53:08 -08005325 llvm::makeArrayRef(&ArgType,
Jordan Rosebea522f2013-03-08 21:51:21 +00005326 ExpectedParams),
5327 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00005328 }
5329
Richard Smith3003e1d2012-05-15 04:39:51 +00005330 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00005331 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00005332 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00005333 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00005334 // C++11 [dcl.fct.def.default]p4:
5335 // [For a] user-provided explicitly-defaulted function [...] if such a
5336 // function is implicitly defined as deleted, the program is ill-formed.
5337 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Stephen Hines651f13c2014-04-23 16:59:28 -07005338 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
Richard Smith3003e1d2012-05-15 04:39:51 +00005339 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00005340 }
5341 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00005342
Richard Smith3003e1d2012-05-15 04:39:51 +00005343 if (HadError)
5344 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00005345}
5346
Richard Smith1d28caf2012-12-11 01:14:52 +00005347/// Check whether the exception specification provided for an
5348/// explicitly-defaulted special member matches the exception specification
5349/// that would have been generated for an implicit special member, per
5350/// C++11 [dcl.fct.def.default]p2.
5351void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5352 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
Stephen Hines176edba2014-12-01 14:53:08 -08005353 // If the exception specification was explicitly specified but hadn't been
5354 // parsed when the method was defaulted, grab it now.
5355 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
5356 SpecifiedType =
5357 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
5358
Richard Smith1d28caf2012-12-11 01:14:52 +00005359 // Compute the implicit exception specification.
Reid Kleckneref072032013-08-27 23:08:25 +00005360 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5361 /*IsCXXMethod=*/true);
5362 FunctionProtoType::ExtProtoInfo EPI(CC);
Stephen Hines176edba2014-12-01 14:53:08 -08005363 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5364 .getExceptionSpec();
Richard Smith1d28caf2012-12-11 01:14:52 +00005365 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko55431692013-05-05 00:41:58 +00005366 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00005367
5368 // Ensure that it matches.
5369 CheckEquivalentExceptionSpec(
5370 PDiag(diag::err_incorrect_defaulted_exception_spec)
5371 << getSpecialMember(MD), PDiag(),
5372 ImplicitType, SourceLocation(),
5373 SpecifiedType, MD->getLocation());
5374}
5375
Alp Toker08235662013-10-18 05:54:19 +00005376void Sema::CheckDelayedMemberExceptionSpecs() {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005377 decltype(DelayedExceptionSpecChecks) Checks;
5378 decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
Richard Smith1d28caf2012-12-11 01:14:52 +00005379
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005380 std::swap(Checks, DelayedExceptionSpecChecks);
Alp Toker08235662013-10-18 05:54:19 +00005381 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5382
5383 // Perform any deferred checking of exception specifications for virtual
5384 // destructors.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005385 for (auto &Check : Checks)
5386 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
Alp Toker08235662013-10-18 05:54:19 +00005387
5388 // Check that any explicitly-defaulted methods have exception specifications
5389 // compatible with their implicit exception specifications.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07005390 for (auto &Spec : Specs)
5391 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
Richard Smith1d28caf2012-12-11 01:14:52 +00005392}
5393
Richard Smith7d5088a2012-02-18 02:02:13 +00005394namespace {
5395struct SpecialMemberDeletionInfo {
5396 Sema &S;
5397 CXXMethodDecl *MD;
5398 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005399 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00005400
5401 // Properties of the special member, computed for convenience.
Stephen Hines651f13c2014-04-23 16:59:28 -07005402 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smith7d5088a2012-02-18 02:02:13 +00005403 SourceLocation Loc;
5404
5405 bool AllFieldsAreConst;
5406
5407 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00005408 Sema::CXXSpecialMember CSM, bool Diagnose)
5409 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00005410 IsConstructor(false), IsAssignment(false), IsMove(false),
Stephen Hines651f13c2014-04-23 16:59:28 -07005411 ConstArg(false), Loc(MD->getLocation()),
Richard Smith7d5088a2012-02-18 02:02:13 +00005412 AllFieldsAreConst(true) {
5413 switch (CSM) {
5414 case Sema::CXXDefaultConstructor:
5415 case Sema::CXXCopyConstructor:
5416 IsConstructor = true;
5417 break;
5418 case Sema::CXXMoveConstructor:
5419 IsConstructor = true;
5420 IsMove = true;
5421 break;
5422 case Sema::CXXCopyAssignment:
5423 IsAssignment = true;
5424 break;
5425 case Sema::CXXMoveAssignment:
5426 IsAssignment = true;
5427 IsMove = true;
5428 break;
5429 case Sema::CXXDestructor:
5430 break;
5431 case Sema::CXXInvalid:
5432 llvm_unreachable("invalid special member kind");
5433 }
5434
5435 if (MD->getNumParams()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005436 if (const ReferenceType *RT =
5437 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5438 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smith7d5088a2012-02-18 02:02:13 +00005439 }
5440 }
5441
5442 bool inUnion() const { return MD->getParent()->isUnion(); }
5443
5444 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00005445 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Stephen Hines651f13c2014-04-23 16:59:28 -07005446 unsigned Quals, bool IsMutable) {
5447 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5448 ConstArg && !IsMutable);
Richard Smith7d5088a2012-02-18 02:02:13 +00005449 }
5450
Richard Smith6c4c36c2012-03-30 20:53:28 +00005451 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00005452
Richard Smith6c4c36c2012-03-30 20:53:28 +00005453 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00005454 bool shouldDeleteForField(FieldDecl *FD);
5455 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00005456
Richard Smith517bb842012-07-18 03:51:16 +00005457 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5458 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005459 bool shouldDeleteForSubobjectCall(Subobject Subobj,
5460 Sema::SpecialMemberOverloadResult *SMOR,
5461 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00005462
5463 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00005464};
5465}
5466
John McCall12d8d802012-04-09 20:53:23 +00005467/// Is the given special member inaccessible when used on the given
5468/// sub-object.
5469bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5470 CXXMethodDecl *target) {
5471 /// If we're operating on a base class, the object type is the
5472 /// type of this special member.
5473 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00005474 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00005475 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5476 objectTy = S.Context.getTypeDeclType(MD->getParent());
5477 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5478
5479 // If we're operating on a field, the object type is the type of the field.
5480 } else {
5481 objectTy = S.Context.getTypeDeclType(target->getParent());
5482 }
5483
5484 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5485}
5486
Richard Smith6c4c36c2012-03-30 20:53:28 +00005487/// Check whether we should delete a special member due to the implicit
5488/// definition containing a call to a special member of a subobject.
5489bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5490 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5491 bool IsDtorCallInCtor) {
5492 CXXMethodDecl *Decl = SMOR->getMethod();
5493 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5494
5495 int DiagKind = -1;
5496
5497 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5498 DiagKind = !Decl ? 0 : 1;
5499 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5500 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00005501 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00005502 DiagKind = 3;
5503 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5504 !Decl->isTrivial()) {
5505 // A member of a union must have a trivial corresponding special member.
5506 // As a weird special case, a destructor call from a union's constructor
5507 // must be accessible and non-deleted, but need not be trivial. Such a
5508 // destructor is never actually called, but is semantically checked as
5509 // if it were.
5510 DiagKind = 4;
5511 }
5512
5513 if (DiagKind == -1)
5514 return false;
5515
5516 if (Diagnose) {
5517 if (Field) {
5518 S.Diag(Field->getLocation(),
5519 diag::note_deleted_special_member_class_subobject)
5520 << CSM << MD->getParent() << /*IsField*/true
5521 << Field << DiagKind << IsDtorCallInCtor;
5522 } else {
5523 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5524 S.Diag(Base->getLocStart(),
5525 diag::note_deleted_special_member_class_subobject)
5526 << CSM << MD->getParent() << /*IsField*/false
5527 << Base->getType() << DiagKind << IsDtorCallInCtor;
5528 }
5529
5530 if (DiagKind == 1)
5531 S.NoteDeletedFunction(Decl);
5532 // FIXME: Explain inaccessibility if DiagKind == 3.
5533 }
5534
5535 return true;
5536}
5537
Richard Smith9a561d52012-02-26 09:11:52 +00005538/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00005539/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00005540bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00005541 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005542 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Stephen Hines651f13c2014-04-23 16:59:28 -07005543 bool IsMutable = Field && Field->isMutable();
Richard Smith7d5088a2012-02-18 02:02:13 +00005544
5545 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00005546 // -- any direct or virtual base class, or non-static data member with no
5547 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00005548 // either M has no default constructor or overload resolution as applied
5549 // to M's default constructor results in an ambiguity or in a function
5550 // that is deleted or inaccessible
5551 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5552 // -- a direct or virtual base class B that cannot be copied/moved because
5553 // overload resolution, as applied to B's corresponding special member,
5554 // results in an ambiguity or a function that is deleted or inaccessible
5555 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00005556 // C++11 [class.dtor]p5:
5557 // -- any direct or virtual base class [...] has a type with a destructor
5558 // that is deleted or inaccessible
5559 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00005560 Field && Field->hasInClassInitializer()) &&
Stephen Hines651f13c2014-04-23 16:59:28 -07005561 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5562 false))
Richard Smith1c931be2012-04-02 18:40:40 +00005563 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00005564
Richard Smith6c4c36c2012-03-30 20:53:28 +00005565 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5566 // -- any direct or virtual base class or non-static data member has a
5567 // type with a destructor that is deleted or inaccessible
5568 if (IsConstructor) {
5569 Sema::SpecialMemberOverloadResult *SMOR =
5570 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5571 false, false, false, false, false);
5572 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5573 return true;
5574 }
5575
Richard Smith9a561d52012-02-26 09:11:52 +00005576 return false;
5577}
5578
5579/// Check whether we should delete a special member function due to the class
5580/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005581bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00005582 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00005583 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00005584}
5585
5586/// Check whether we should delete a special member function due to the class
5587/// having a particular non-static data member.
5588bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5589 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5590 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5591
5592 if (CSM == Sema::CXXDefaultConstructor) {
5593 // For a default constructor, all references must be initialized in-class
5594 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005595 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5596 if (Diagnose)
5597 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5598 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00005599 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005600 }
Richard Smith79363f52012-02-27 06:07:25 +00005601 // C++11 [class.ctor]p5: any non-variant non-static data member of
5602 // const-qualified type (or array thereof) with no
5603 // brace-or-equal-initializer does not have a user-provided default
5604 // constructor.
5605 if (!inUnion() && FieldType.isConstQualified() &&
5606 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005607 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5608 if (Diagnose)
5609 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00005610 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00005611 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005612 }
5613
5614 if (inUnion() && !FieldType.isConstQualified())
5615 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00005616 } else if (CSM == Sema::CXXCopyConstructor) {
5617 // For a copy constructor, data members must not be of rvalue reference
5618 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005619 if (FieldType->isRValueReferenceType()) {
5620 if (Diagnose)
5621 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5622 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00005623 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005624 }
Richard Smith7d5088a2012-02-18 02:02:13 +00005625 } else if (IsAssignment) {
5626 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005627 if (FieldType->isReferenceType()) {
5628 if (Diagnose)
5629 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5630 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00005631 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005632 }
5633 if (!FieldRecord && FieldType.isConstQualified()) {
5634 // C++11 [class.copy]p23:
5635 // -- a non-static data member of const non-class type (or array thereof)
5636 if (Diagnose)
5637 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00005638 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005639 return true;
5640 }
Richard Smith7d5088a2012-02-18 02:02:13 +00005641 }
5642
5643 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00005644 // Some additional restrictions exist on the variant members.
5645 if (!inUnion() && FieldRecord->isUnion() &&
5646 FieldRecord->isAnonymousStructOrUnion()) {
5647 bool AllVariantFieldsAreConst = true;
5648
Richard Smithdf8dc862012-03-29 19:00:10 +00005649 // FIXME: Handle anonymous unions declared within anonymous unions.
Stephen Hines651f13c2014-04-23 16:59:28 -07005650 for (auto *UI : FieldRecord->fields()) {
Richard Smith7d5088a2012-02-18 02:02:13 +00005651 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00005652
5653 if (!UnionFieldType.isConstQualified())
5654 AllVariantFieldsAreConst = false;
5655
Richard Smith9a561d52012-02-26 09:11:52 +00005656 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5657 if (UnionFieldRecord &&
Stephen Hines651f13c2014-04-23 16:59:28 -07005658 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smith517bb842012-07-18 03:51:16 +00005659 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00005660 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00005661 }
5662
5663 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00005664 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Stephen Hines651f13c2014-04-23 16:59:28 -07005665 !FieldRecord->field_empty()) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005666 if (Diagnose)
5667 S.Diag(FieldRecord->getLocation(),
5668 diag::note_deleted_default_ctor_all_const)
5669 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00005670 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005671 }
Richard Smith7d5088a2012-02-18 02:02:13 +00005672
Richard Smithdf8dc862012-03-29 19:00:10 +00005673 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00005674 // This is technically non-conformant, but sanity demands it.
5675 return false;
5676 }
5677
Richard Smith517bb842012-07-18 03:51:16 +00005678 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5679 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00005680 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00005681 }
5682
5683 return false;
5684}
5685
5686/// C++11 [class.ctor] p5:
5687/// A defaulted default constructor for a class X is defined as deleted if
5688/// X is a union and all of its variant members are of const-qualified type.
5689bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00005690 // This is a silly definition, because it gives an empty union a deleted
5691 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005692 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
Stephen Hines651f13c2014-04-23 16:59:28 -07005693 !MD->getParent()->field_empty()) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005694 if (Diagnose)
5695 S.Diag(MD->getParent()->getLocation(),
5696 diag::note_deleted_default_ctor_all_const)
5697 << MD->getParent() << /*not anonymous union*/0;
5698 return true;
5699 }
5700 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00005701}
5702
5703/// Determine whether a defaulted special member function should be defined as
5704/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5705/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005706bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5707 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00005708 if (MD->isInvalidDecl())
5709 return false;
Sean Hunte16da072011-10-10 06:18:57 +00005710 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00005711 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00005712 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005713 return false;
5714
Richard Smith7d5088a2012-02-18 02:02:13 +00005715 // C++11 [expr.lambda.prim]p19:
5716 // The closure type associated with a lambda-expression has a
5717 // deleted (8.4.3) default constructor and a deleted copy
5718 // assignment operator.
5719 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005720 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5721 if (Diagnose)
5722 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00005723 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005724 }
5725
Richard Smith5bdaac52012-04-02 20:59:25 +00005726 // For an anonymous struct or union, the copy and assignment special members
5727 // will never be used, so skip the check. For an anonymous union declared at
5728 // namespace scope, the constructor and destructor are used.
5729 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5730 RD->isAnonymousStructOrUnion())
5731 return false;
5732
Richard Smith6c4c36c2012-03-30 20:53:28 +00005733 // C++11 [class.copy]p7, p18:
5734 // If the class definition declares a move constructor or move assignment
5735 // operator, an implicitly declared copy constructor or copy assignment
5736 // operator is defined as deleted.
5737 if (MD->isImplicit() &&
5738 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005739 CXXMethodDecl *UserDeclaredMove = nullptr;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005740
5741 // In Microsoft mode, a user-declared move only causes the deletion of the
5742 // corresponding copy operation, not both copy operations.
5743 if (RD->hasUserDeclaredMoveConstructor() &&
Stephen Hines651f13c2014-04-23 16:59:28 -07005744 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005745 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005746
5747 // Find any user-declared move constructor.
Stephen Hines651f13c2014-04-23 16:59:28 -07005748 for (auto *I : RD->ctors()) {
Richard Smith55798652012-12-08 04:10:18 +00005749 if (I->isMoveConstructor()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005750 UserDeclaredMove = I;
Richard Smith55798652012-12-08 04:10:18 +00005751 break;
5752 }
5753 }
Richard Smith1c931be2012-04-02 18:40:40 +00005754 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005755 } else if (RD->hasUserDeclaredMoveAssignment() &&
Stephen Hines651f13c2014-04-23 16:59:28 -07005756 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005757 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005758
5759 // Find any user-declared move assignment operator.
Stephen Hines651f13c2014-04-23 16:59:28 -07005760 for (auto *I : RD->methods()) {
Richard Smith55798652012-12-08 04:10:18 +00005761 if (I->isMoveAssignmentOperator()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005762 UserDeclaredMove = I;
Richard Smith55798652012-12-08 04:10:18 +00005763 break;
5764 }
5765 }
Richard Smith1c931be2012-04-02 18:40:40 +00005766 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005767 }
5768
5769 if (UserDeclaredMove) {
5770 Diag(UserDeclaredMove->getLocation(),
5771 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00005772 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00005773 << UserDeclaredMove->isMoveAssignmentOperator();
5774 return true;
5775 }
5776 }
Sean Hunte16da072011-10-10 06:18:57 +00005777
Richard Smith5bdaac52012-04-02 20:59:25 +00005778 // Do access control from the special member function
5779 ContextRAII MethodContext(*this, MD);
5780
Richard Smith9a561d52012-02-26 09:11:52 +00005781 // C++11 [class.dtor]p5:
5782 // -- for a virtual destructor, lookup of the non-array deallocation function
5783 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00005784 if (CSM == CXXDestructor && MD->isVirtual()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005785 FunctionDecl *OperatorDelete = nullptr;
Richard Smith9a561d52012-02-26 09:11:52 +00005786 DeclarationName Name =
5787 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5788 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00005789 OperatorDelete, false)) {
5790 if (Diagnose)
5791 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00005792 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005793 }
Richard Smith9a561d52012-02-26 09:11:52 +00005794 }
5795
Richard Smith6c4c36c2012-03-30 20:53:28 +00005796 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00005797
Stephen Hines651f13c2014-04-23 16:59:28 -07005798 for (auto &BI : RD->bases())
5799 if (!BI.isVirtual() &&
5800 SMI.shouldDeleteForBase(&BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005801 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005802
Richard Smithe0883602013-07-22 18:06:23 +00005803 // Per DR1611, do not consider virtual bases of constructors of abstract
5804 // classes, since we are not going to construct them.
Richard Smithcbc820a2013-07-22 02:56:56 +00005805 if (!RD->isAbstract() || !SMI.IsConstructor) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005806 for (auto &BI : RD->vbases())
5807 if (SMI.shouldDeleteForBase(&BI))
Richard Smithcbc820a2013-07-22 02:56:56 +00005808 return true;
5809 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00005810
Stephen Hines651f13c2014-04-23 16:59:28 -07005811 for (auto *FI : RD->fields())
Richard Smith7d5088a2012-02-18 02:02:13 +00005812 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Stephen Hines651f13c2014-04-23 16:59:28 -07005813 SMI.shouldDeleteForField(FI))
Sean Hunte3406822011-05-20 21:43:47 +00005814 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005815
Richard Smith7d5088a2012-02-18 02:02:13 +00005816 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005817 return true;
5818
Stephen Hines176edba2014-12-01 14:53:08 -08005819 if (getLangOpts().CUDA) {
5820 // We should delete the special member in CUDA mode if target inference
5821 // failed.
5822 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
5823 Diagnose);
5824 }
5825
Sean Huntcdee3fe2011-05-11 22:34:38 +00005826 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005827}
5828
Richard Smithac713512012-12-08 02:53:02 +00005829/// Perform lookup for a special member of the specified kind, and determine
5830/// whether it is trivial. If the triviality can be determined without the
5831/// lookup, skip it. This is intended for use when determining whether a
5832/// special member of a containing object is trivial, and thus does not ever
5833/// perform overload resolution for default constructors.
5834///
5835/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5836/// member that was most likely to be intended to be trivial, if any.
5837static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5838 Sema::CXXSpecialMember CSM, unsigned Quals,
Stephen Hines651f13c2014-04-23 16:59:28 -07005839 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smithac713512012-12-08 02:53:02 +00005840 if (Selected)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005841 *Selected = nullptr;
Richard Smithac713512012-12-08 02:53:02 +00005842
5843 switch (CSM) {
5844 case Sema::CXXInvalid:
5845 llvm_unreachable("not a special member");
5846
5847 case Sema::CXXDefaultConstructor:
5848 // C++11 [class.ctor]p5:
5849 // A default constructor is trivial if:
5850 // - all the [direct subobjects] have trivial default constructors
5851 //
5852 // Note, no overload resolution is performed in this case.
5853 if (RD->hasTrivialDefaultConstructor())
5854 return true;
5855
5856 if (Selected) {
5857 // If there's a default constructor which could have been trivial, dig it
5858 // out. Otherwise, if there's any user-provided default constructor, point
5859 // to that as an example of why there's not a trivial one.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005860 CXXConstructorDecl *DefCtor = nullptr;
Richard Smithac713512012-12-08 02:53:02 +00005861 if (RD->needsImplicitDefaultConstructor())
5862 S.DeclareImplicitDefaultConstructor(RD);
Stephen Hines651f13c2014-04-23 16:59:28 -07005863 for (auto *CI : RD->ctors()) {
Richard Smithac713512012-12-08 02:53:02 +00005864 if (!CI->isDefaultConstructor())
5865 continue;
Stephen Hines651f13c2014-04-23 16:59:28 -07005866 DefCtor = CI;
Richard Smithac713512012-12-08 02:53:02 +00005867 if (!DefCtor->isUserProvided())
5868 break;
5869 }
5870
5871 *Selected = DefCtor;
5872 }
5873
5874 return false;
5875
5876 case Sema::CXXDestructor:
5877 // C++11 [class.dtor]p5:
5878 // A destructor is trivial if:
5879 // - all the direct [subobjects] have trivial destructors
5880 if (RD->hasTrivialDestructor())
5881 return true;
5882
5883 if (Selected) {
5884 if (RD->needsImplicitDestructor())
5885 S.DeclareImplicitDestructor(RD);
5886 *Selected = RD->getDestructor();
5887 }
5888
5889 return false;
5890
5891 case Sema::CXXCopyConstructor:
5892 // C++11 [class.copy]p12:
5893 // A copy constructor is trivial if:
5894 // - the constructor selected to copy each direct [subobject] is trivial
5895 if (RD->hasTrivialCopyConstructor()) {
5896 if (Quals == Qualifiers::Const)
5897 // We must either select the trivial copy constructor or reach an
5898 // ambiguity; no need to actually perform overload resolution.
5899 return true;
5900 } else if (!Selected) {
5901 return false;
5902 }
5903 // In C++98, we are not supposed to perform overload resolution here, but we
5904 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5905 // cases like B as having a non-trivial copy constructor:
5906 // struct A { template<typename T> A(T&); };
5907 // struct B { mutable A a; };
5908 goto NeedOverloadResolution;
5909
5910 case Sema::CXXCopyAssignment:
5911 // C++11 [class.copy]p25:
5912 // A copy assignment operator is trivial if:
5913 // - the assignment operator selected to copy each direct [subobject] is
5914 // trivial
5915 if (RD->hasTrivialCopyAssignment()) {
5916 if (Quals == Qualifiers::Const)
5917 return true;
5918 } else if (!Selected) {
5919 return false;
5920 }
5921 // In C++98, we are not supposed to perform overload resolution here, but we
5922 // treat that as a language defect.
5923 goto NeedOverloadResolution;
5924
5925 case Sema::CXXMoveConstructor:
5926 case Sema::CXXMoveAssignment:
5927 NeedOverloadResolution:
5928 Sema::SpecialMemberOverloadResult *SMOR =
Stephen Hines651f13c2014-04-23 16:59:28 -07005929 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smithac713512012-12-08 02:53:02 +00005930
5931 // The standard doesn't describe how to behave if the lookup is ambiguous.
5932 // We treat it as not making the member non-trivial, just like the standard
5933 // mandates for the default constructor. This should rarely matter, because
5934 // the member will also be deleted.
5935 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5936 return true;
5937
5938 if (!SMOR->getMethod()) {
5939 assert(SMOR->getKind() ==
5940 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5941 return false;
5942 }
5943
5944 // We deliberately don't check if we found a deleted special member. We're
5945 // not supposed to!
5946 if (Selected)
5947 *Selected = SMOR->getMethod();
5948 return SMOR->getMethod()->isTrivial();
5949 }
5950
5951 llvm_unreachable("unknown special method kind");
5952}
5953
Benjamin Kramera574c892013-02-15 12:30:38 +00005954static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005955 for (auto *CI : RD->ctors())
Richard Smithac713512012-12-08 02:53:02 +00005956 if (!CI->isImplicit())
Stephen Hines651f13c2014-04-23 16:59:28 -07005957 return CI;
Richard Smithac713512012-12-08 02:53:02 +00005958
5959 // Look for constructor templates.
5960 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5961 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5962 if (CXXConstructorDecl *CD =
5963 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5964 return CD;
5965 }
5966
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005967 return nullptr;
Richard Smithac713512012-12-08 02:53:02 +00005968}
5969
5970/// The kind of subobject we are checking for triviality. The values of this
5971/// enumeration are used in diagnostics.
5972enum TrivialSubobjectKind {
5973 /// The subobject is a base class.
5974 TSK_BaseClass,
5975 /// The subobject is a non-static data member.
5976 TSK_Field,
5977 /// The object is actually the complete object.
5978 TSK_CompleteObject
5979};
5980
5981/// Check whether the special member selected for a given type would be trivial.
5982static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Stephen Hines651f13c2014-04-23 16:59:28 -07005983 QualType SubType, bool ConstRHS,
Richard Smithac713512012-12-08 02:53:02 +00005984 Sema::CXXSpecialMember CSM,
5985 TrivialSubobjectKind Kind,
5986 bool Diagnose) {
5987 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5988 if (!SubRD)
5989 return true;
5990
5991 CXXMethodDecl *Selected;
5992 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005993 ConstRHS, Diagnose ? &Selected : nullptr))
Richard Smithac713512012-12-08 02:53:02 +00005994 return true;
5995
5996 if (Diagnose) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005997 if (ConstRHS)
5998 SubType.addConst();
5999
Richard Smithac713512012-12-08 02:53:02 +00006000 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
6001 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
6002 << Kind << SubType.getUnqualifiedType();
6003 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
6004 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
6005 } else if (!Selected)
6006 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
6007 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
6008 else if (Selected->isUserProvided()) {
6009 if (Kind == TSK_CompleteObject)
6010 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
6011 << Kind << SubType.getUnqualifiedType() << CSM;
6012 else {
6013 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
6014 << Kind << SubType.getUnqualifiedType() << CSM;
6015 S.Diag(Selected->getLocation(), diag::note_declared_at);
6016 }
6017 } else {
6018 if (Kind != TSK_CompleteObject)
6019 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
6020 << Kind << SubType.getUnqualifiedType() << CSM;
6021
6022 // Explain why the defaulted or deleted special member isn't trivial.
6023 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
6024 }
6025 }
6026
6027 return false;
6028}
6029
6030/// Check whether the members of a class type allow a special member to be
6031/// trivial.
6032static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
6033 Sema::CXXSpecialMember CSM,
6034 bool ConstArg, bool Diagnose) {
Stephen Hines651f13c2014-04-23 16:59:28 -07006035 for (const auto *FI : RD->fields()) {
Richard Smithac713512012-12-08 02:53:02 +00006036 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
6037 continue;
6038
6039 QualType FieldType = S.Context.getBaseElementType(FI->getType());
6040
6041 // Pretend anonymous struct or union members are members of this class.
6042 if (FI->isAnonymousStructOrUnion()) {
6043 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
6044 CSM, ConstArg, Diagnose))
6045 return false;
6046 continue;
6047 }
6048
6049 // C++11 [class.ctor]p5:
6050 // A default constructor is trivial if [...]
6051 // -- no non-static data member of its class has a
6052 // brace-or-equal-initializer
6053 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
6054 if (Diagnose)
Stephen Hines651f13c2014-04-23 16:59:28 -07006055 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smithac713512012-12-08 02:53:02 +00006056 return false;
6057 }
6058
6059 // Objective C ARC 4.3.5:
6060 // [...] nontrivally ownership-qualified types are [...] not trivially
6061 // default constructible, copy constructible, move constructible, copy
6062 // assignable, move assignable, or destructible [...]
6063 if (S.getLangOpts().ObjCAutoRefCount &&
6064 FieldType.hasNonTrivialObjCLifetime()) {
6065 if (Diagnose)
6066 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
6067 << RD << FieldType.getObjCLifetime();
6068 return false;
6069 }
6070
Stephen Hines651f13c2014-04-23 16:59:28 -07006071 bool ConstRHS = ConstArg && !FI->isMutable();
6072 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
6073 CSM, TSK_Field, Diagnose))
Richard Smithac713512012-12-08 02:53:02 +00006074 return false;
6075 }
6076
6077 return true;
6078}
6079
6080/// Diagnose why the specified class does not have a trivial special member of
6081/// the given kind.
6082void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
6083 QualType Ty = Context.getRecordType(RD);
Richard Smithac713512012-12-08 02:53:02 +00006084
Stephen Hines651f13c2014-04-23 16:59:28 -07006085 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
6086 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smithac713512012-12-08 02:53:02 +00006087 TSK_CompleteObject, /*Diagnose*/true);
6088}
6089
6090/// Determine whether a defaulted or deleted special member function is trivial,
6091/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6092/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6093bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
6094 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00006095 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
6096
6097 CXXRecordDecl *RD = MD->getParent();
6098
6099 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00006100
Richard Smitha8d478e2013-11-04 02:02:27 +00006101 // C++11 [class.copy]p12, p25: [DR1593]
6102 // A [special member] is trivial if [...] its parameter-type-list is
6103 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smithac713512012-12-08 02:53:02 +00006104 switch (CSM) {
6105 case CXXDefaultConstructor:
6106 case CXXDestructor:
6107 // Trivial default constructors and destructors cannot have parameters.
6108 break;
6109
6110 case CXXCopyConstructor:
6111 case CXXCopyAssignment: {
6112 // Trivial copy operations always have const, non-volatile parameter types.
6113 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00006114 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00006115 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
6116 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
6117 if (Diagnose)
6118 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6119 << Param0->getSourceRange() << Param0->getType()
6120 << Context.getLValueReferenceType(
6121 Context.getRecordType(RD).withConst());
6122 return false;
6123 }
6124 break;
6125 }
6126
6127 case CXXMoveConstructor:
6128 case CXXMoveAssignment: {
6129 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00006130 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00006131 const RValueReferenceType *RT =
6132 Param0->getType()->getAs<RValueReferenceType>();
6133 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
6134 if (Diagnose)
6135 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6136 << Param0->getSourceRange() << Param0->getType()
6137 << Context.getRValueReferenceType(Context.getRecordType(RD));
6138 return false;
6139 }
6140 break;
6141 }
6142
6143 case CXXInvalid:
6144 llvm_unreachable("not a special member");
6145 }
6146
Richard Smithac713512012-12-08 02:53:02 +00006147 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
6148 if (Diagnose)
6149 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
6150 diag::note_nontrivial_default_arg)
6151 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
6152 return false;
6153 }
6154 if (MD->isVariadic()) {
6155 if (Diagnose)
6156 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
6157 return false;
6158 }
6159
6160 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6161 // A copy/move [constructor or assignment operator] is trivial if
6162 // -- the [member] selected to copy/move each direct base class subobject
6163 // is trivial
6164 //
6165 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6166 // A [default constructor or destructor] is trivial if
6167 // -- all the direct base classes have trivial [default constructors or
6168 // destructors]
Stephen Hines651f13c2014-04-23 16:59:28 -07006169 for (const auto &BI : RD->bases())
6170 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
6171 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smithac713512012-12-08 02:53:02 +00006172 return false;
6173
6174 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6175 // A copy/move [constructor or assignment operator] for a class X is
6176 // trivial if
6177 // -- for each non-static data member of X that is of class type (or array
6178 // thereof), the constructor selected to copy/move that member is
6179 // trivial
6180 //
6181 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6182 // A [default constructor or destructor] is trivial if
6183 // -- for all of the non-static data members of its class that are of class
6184 // type (or array thereof), each such class has a trivial [default
6185 // constructor or destructor]
6186 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
6187 return false;
6188
6189 // C++11 [class.dtor]p5:
6190 // A destructor is trivial if [...]
6191 // -- the destructor is not virtual
6192 if (CSM == CXXDestructor && MD->isVirtual()) {
6193 if (Diagnose)
6194 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
6195 return false;
6196 }
6197
6198 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
6199 // A [special member] for class X is trivial if [...]
6200 // -- class X has no virtual functions and no virtual base classes
6201 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
6202 if (!Diagnose)
6203 return false;
6204
6205 if (RD->getNumVBases()) {
6206 // Check for virtual bases. We already know that the corresponding
6207 // member in all bases is trivial, so vbases must all be direct.
6208 CXXBaseSpecifier &BS = *RD->vbases_begin();
6209 assert(BS.isVirtual());
6210 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
6211 return false;
6212 }
6213
6214 // Must have a virtual method.
Stephen Hines651f13c2014-04-23 16:59:28 -07006215 for (const auto *MI : RD->methods()) {
Richard Smithac713512012-12-08 02:53:02 +00006216 if (MI->isVirtual()) {
6217 SourceLocation MLoc = MI->getLocStart();
6218 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
6219 return false;
6220 }
6221 }
6222
6223 llvm_unreachable("dynamic class with no vbases and no virtual functions");
6224 }
6225
6226 // Looks like it's trivial!
6227 return true;
6228}
6229
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00006230/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00006231namespace {
6232 struct FindHiddenVirtualMethodData {
6233 Sema *S;
6234 CXXMethodDecl *Method;
6235 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006236 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00006237 };
6238}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00006239
David Blaikie5f750682012-10-19 00:53:08 +00006240/// \brief Check whether any most overriden method from MD in Methods
6241static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
Stephen Hines176edba2014-12-01 14:53:08 -08006242 const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie5f750682012-10-19 00:53:08 +00006243 if (MD->size_overridden_methods() == 0)
6244 return Methods.count(MD->getCanonicalDecl());
6245 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6246 E = MD->end_overridden_methods();
6247 I != E; ++I)
6248 if (CheckMostOverridenMethods(*I, Methods))
6249 return true;
6250 return false;
6251}
6252
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00006253/// \brief Member lookup function that determines whether a given C++
6254/// method overloads virtual methods in a base class without overriding any,
6255/// to be used with CXXRecordDecl::lookupInBases().
6256static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
6257 CXXBasePath &Path,
6258 void *UserData) {
6259 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
6260
6261 FindHiddenVirtualMethodData &Data
6262 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
6263
6264 DeclarationName Name = Data.Method->getDeclName();
6265 assert(Name.getNameKind() == DeclarationName::Identifier);
6266
6267 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006268 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00006269 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00006270 !Path.Decls.empty();
6271 Path.Decls = Path.Decls.slice(1)) {
6272 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00006273 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00006274 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00006275 foundSameNameMethod = true;
6276 // Interested only in hidden virtual methods.
6277 if (!MD->isVirtual())
6278 continue;
6279 // If the method we are checking overrides a method from its base
Stephen Hines176edba2014-12-01 14:53:08 -08006280 // don't warn about the other overloaded methods. Clang deviates from GCC
6281 // by only diagnosing overloads of inherited virtual functions that do not
6282 // override any other virtual functions in the base. GCC's
6283 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6284 // function from a base class. These cases may be better served by a
6285 // warning (not specific to virtual functions) on call sites when the call
6286 // would select a different function from the base class, were it visible.
6287 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00006288 if (!Data.S->IsOverload(Data.Method, MD, false))
6289 return true;
6290 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00006291 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00006292 overloadedMethods.push_back(MD);
6293 }
6294 }
6295
6296 if (foundSameNameMethod)
6297 Data.OverloadedMethods.append(overloadedMethods.begin(),
6298 overloadedMethods.end());
6299 return foundSameNameMethod;
6300}
6301
David Blaikie5f750682012-10-19 00:53:08 +00006302/// \brief Add the most overriden methods from MD to Methods
6303static void AddMostOverridenMethods(const CXXMethodDecl *MD,
Stephen Hines176edba2014-12-01 14:53:08 -08006304 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie5f750682012-10-19 00:53:08 +00006305 if (MD->size_overridden_methods() == 0)
6306 Methods.insert(MD->getCanonicalDecl());
6307 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6308 E = MD->end_overridden_methods();
6309 I != E; ++I)
6310 AddMostOverridenMethods(*I, Methods);
6311}
6312
Eli Friedmandae92712013-09-05 23:51:03 +00006313/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00006314/// overriding any.
Eli Friedmandae92712013-09-05 23:51:03 +00006315void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6316 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramerc4704422012-05-19 16:03:58 +00006317 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00006318 return;
6319
6320 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6321 /*bool RecordPaths=*/false,
6322 /*bool DetectVirtual=*/false);
6323 FindHiddenVirtualMethodData Data;
6324 Data.Method = MD;
6325 Data.S = this;
6326
6327 // Keep the base methods that were overriden or introduced in the subclass
6328 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmandae92712013-09-05 23:51:03 +00006329 CXXRecordDecl *DC = MD->getParent();
David Blaikie3bc93e32012-12-19 00:45:41 +00006330 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6331 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6332 NamedDecl *ND = *I;
6333 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00006334 ND = shad->getTargetDecl();
6335 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6336 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00006337 }
6338
Eli Friedmandae92712013-09-05 23:51:03 +00006339 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
6340 OverloadedMethods = Data.OverloadedMethods;
6341}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00006342
Eli Friedmandae92712013-09-05 23:51:03 +00006343void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6344 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6345 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6346 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6347 PartialDiagnostic PD = PDiag(
6348 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6349 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6350 Diag(overloadedMD->getLocation(), PD);
6351 }
6352}
6353
6354/// \brief Diagnose methods which overload virtual methods in a base class
6355/// without overriding any.
6356void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6357 if (MD->isInvalidDecl())
6358 return;
6359
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006360 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
Eli Friedmandae92712013-09-05 23:51:03 +00006361 return;
6362
6363 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6364 FindHiddenVirtualMethods(MD, OverloadedMethods);
6365 if (!OverloadedMethods.empty()) {
6366 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6367 << MD << (OverloadedMethods.size() > 1);
6368
6369 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00006370 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00006371}
6372
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00006373void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00006374 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00006375 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00006376 SourceLocation RBrac,
6377 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00006378 if (!TagDecl)
6379 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006380
Douglas Gregor42af25f2009-05-11 19:58:34 +00006381 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00006382
Rafael Espindolaf729ce02012-07-12 04:32:30 +00006383 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6384 if (l->getKind() != AttributeList::AT_Visibility)
6385 continue;
6386 l->setInvalid();
6387 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6388 l->getName();
6389 }
6390
David Blaikie77b6de02011-09-22 02:58:26 +00006391 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00006392 // strict aliasing violation!
6393 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00006394 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00006395
Douglas Gregor23c94db2010-07-02 17:43:08 +00006396 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00006397 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00006398}
6399
Douglas Gregor396b7cd2008-11-03 17:51:48 +00006400/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6401/// special functions, such as the default constructor, copy
6402/// constructor, or destructor, to the given C++ class (C++
6403/// [special]p1). This routine can only be executed just before the
6404/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00006405void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00006406 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00006407 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00006408
Richard Smithbc2a35d2012-12-08 08:32:28 +00006409 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00006410 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00006411
Richard Smithbc2a35d2012-12-08 08:32:28 +00006412 // If the properties or semantics of the copy constructor couldn't be
6413 // determined while the class was being declared, force a declaration
6414 // of it now.
6415 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6416 DeclareImplicitCopyConstructor(ClassDecl);
6417 }
6418
Richard Smith80ad52f2013-01-02 11:42:31 +00006419 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00006420 ++ASTContext::NumImplicitMoveConstructors;
6421
Richard Smithbc2a35d2012-12-08 08:32:28 +00006422 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6423 DeclareImplicitMoveConstructor(ClassDecl);
6424 }
6425
Douglas Gregora376d102010-07-02 21:50:04 +00006426 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6427 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00006428
6429 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00006430 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00006431 // it shows up in the right place in the vtable and that we diagnose
6432 // problems with the implicit exception specification.
6433 if (ClassDecl->isDynamicClass() ||
6434 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00006435 DeclareImplicitCopyAssignment(ClassDecl);
6436 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00006437
Richard Smith80ad52f2013-01-02 11:42:31 +00006438 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00006439 ++ASTContext::NumImplicitMoveAssignmentOperators;
6440
6441 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00006442 if (ClassDecl->isDynamicClass() ||
6443 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00006444 DeclareImplicitMoveAssignment(ClassDecl);
6445 }
6446
Douglas Gregor4923aa22010-07-02 20:37:36 +00006447 if (!ClassDecl->hasUserDeclaredDestructor()) {
6448 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00006449
6450 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00006451 // have to declare the destructor immediately. This ensures that, e.g., it
6452 // shows up in the right place in the vtable and that we diagnose problems
6453 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00006454 if (ClassDecl->isDynamicClass() ||
6455 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00006456 DeclareImplicitDestructor(ClassDecl);
6457 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00006458}
6459
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006460unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00006461 if (!D)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006462 return 0;
Francois Pichet8387e2a2011-04-22 22:18:13 +00006463
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006464 // The order of template parameters is not important here. All names
6465 // get added to the same scope.
6466 SmallVector<TemplateParameterList *, 4> ParameterLists;
6467
6468 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6469 D = TD->getTemplatedDecl();
6470
6471 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6472 ParameterLists.push_back(PSD->getTemplateParameters());
6473
6474 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6475 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6476 ParameterLists.push_back(DD->getTemplateParameterList(i));
6477
6478 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6479 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6480 ParameterLists.push_back(FTD->getTemplateParameters());
6481 }
6482 }
6483
6484 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6485 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6486 ParameterLists.push_back(TD->getTemplateParameterList(i));
6487
6488 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6489 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6490 ParameterLists.push_back(CTD->getTemplateParameters());
6491 }
6492 }
6493
6494 unsigned Count = 0;
6495 for (TemplateParameterList *Params : ParameterLists) {
6496 if (Params->size() > 0)
6497 // Ignore explicit specializations; they don't contribute to the template
6498 // depth.
6499 ++Count;
6500 for (NamedDecl *Param : *Params) {
6501 if (Param->getDeclName()) {
6502 S->AddDecl(Param);
6503 IdResolver.AddDecl(Param);
Francois Pichet8387e2a2011-04-22 22:18:13 +00006504 }
6505 }
6506 }
Francois Pichet8387e2a2011-04-22 22:18:13 +00006507
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006508 return Count;
Douglas Gregor6569d682009-05-27 23:11:45 +00006509}
6510
John McCalld226f652010-08-21 09:40:31 +00006511void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00006512 if (!RecordD) return;
6513 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00006514 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00006515 PushDeclContext(S, Record);
6516}
6517
John McCalld226f652010-08-21 09:40:31 +00006518void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00006519 if (!RecordD) return;
6520 PopDeclContext();
6521}
6522
Stephen Hines651f13c2014-04-23 16:59:28 -07006523/// This is used to implement the constant expression evaluation part of the
6524/// attribute enable_if extension. There is nothing in standard C++ which would
6525/// require reentering parameters.
6526void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6527 if (!Param)
6528 return;
6529
6530 S->AddDecl(Param);
6531 if (Param->getDeclName())
6532 IdResolver.AddDecl(Param);
6533}
6534
Douglas Gregor72b505b2008-12-16 21:30:33 +00006535/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6536/// parsing a top-level (non-nested) C++ class, and we are now
6537/// parsing those parts of the given Method declaration that could
6538/// not be parsed earlier (C++ [class.mem]p2), such as default
6539/// arguments. This action should enter the scope of the given
6540/// Method declaration as if we had just parsed the qualified method
6541/// name. However, it should not bring the parameters into scope;
6542/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00006543void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00006544}
6545
6546/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6547/// C++ method declaration. We're (re-)introducing the given
6548/// function parameter into scope for use in parsing later parts of
6549/// the method declaration. For example, we could see an
6550/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00006551void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00006552 if (!ParamD)
6553 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006554
John McCalld226f652010-08-21 09:40:31 +00006555 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00006556
6557 // If this parameter has an unparsed default argument, clear it out
6558 // to make way for the parsed default argument.
6559 if (Param->hasUnparsedDefaultArg())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006560 Param->setDefaultArg(nullptr);
Douglas Gregor61366e92008-12-24 00:01:03 +00006561
John McCalld226f652010-08-21 09:40:31 +00006562 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00006563 if (Param->getDeclName())
6564 IdResolver.AddDecl(Param);
6565}
6566
6567/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6568/// processing the delayed method declaration for Method. The method
6569/// declaration is now considered finished. There may be a separate
6570/// ActOnStartOfFunctionDef action later (not necessarily
6571/// immediately!) for this method, if it was also defined inside the
6572/// class body.
John McCalld226f652010-08-21 09:40:31 +00006573void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00006574 if (!MethodD)
6575 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006576
Douglas Gregorefd5bda2009-08-24 11:57:43 +00006577 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00006578
John McCalld226f652010-08-21 09:40:31 +00006579 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00006580
6581 // Now that we have our default arguments, check the constructor
6582 // again. It could produce additional diagnostics or affect whether
6583 // the class has implicitly-declared destructors, among other
6584 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00006585 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6586 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00006587
6588 // Check the default arguments, which we may have added.
6589 if (!Method->isInvalidDecl())
6590 CheckCXXDefaultArguments(Method);
6591}
6592
Douglas Gregor42a552f2008-11-05 20:51:48 +00006593/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00006594/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00006595/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00006596/// emit diagnostics and set the invalid bit to true. In any case, the type
6597/// will be updated to reflect a well-formed type for the constructor and
6598/// returned.
6599QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00006600 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006601 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006602
6603 // C++ [class.ctor]p3:
6604 // A constructor shall not be virtual (10.3) or static (9.4). A
6605 // constructor can be invoked for a const, volatile or const
6606 // volatile object. A constructor shall not be declared const,
6607 // volatile, or const volatile (9.3.2).
6608 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00006609 if (!D.isInvalidType())
6610 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6611 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6612 << SourceRange(D.getIdentifierLoc());
6613 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006614 }
John McCalld931b082010-08-26 03:08:43 +00006615 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00006616 if (!D.isInvalidType())
6617 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6618 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6619 << SourceRange(D.getIdentifierLoc());
6620 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006621 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006622 }
Mike Stump1eb44332009-09-09 15:08:12 +00006623
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006624 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6625 diagnoseIgnoredQualifiers(
6626 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6627 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6628 D.getDeclSpec().getRestrictSpecLoc(),
6629 D.getDeclSpec().getAtomicSpecLoc());
6630 D.setInvalidType();
6631 }
6632
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006633 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00006634 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00006635 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006636 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6637 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006638 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006639 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6640 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006641 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006642 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6643 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00006644 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006645 }
Mike Stump1eb44332009-09-09 15:08:12 +00006646
Douglas Gregorc938c162011-01-26 05:01:58 +00006647 // C++0x [class.ctor]p4:
6648 // A constructor shall not be declared with a ref-qualifier.
6649 if (FTI.hasRefQualifier()) {
6650 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6651 << FTI.RefQualifierIsLValueRef
6652 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6653 D.setInvalidType();
6654 }
6655
Douglas Gregor42a552f2008-11-05 20:51:48 +00006656 // Rebuild the function type "R" without any type qualifiers (in
6657 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00006658 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00006659 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07006660 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalle23cf432010-12-14 08:05:40 +00006661 return R;
6662
6663 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6664 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006665 EPI.RefQualifier = RQ_None;
Stephen Hines651f13c2014-04-23 16:59:28 -07006666
6667 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006668}
6669
Douglas Gregor72b505b2008-12-16 21:30:33 +00006670/// CheckConstructor - Checks a fully-formed constructor for
6671/// well-formedness, issuing any diagnostics required. Returns true if
6672/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00006673void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00006674 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00006675 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6676 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00006677 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00006678
6679 // C++ [class.copy]p3:
6680 // A declaration of a constructor for a class X is ill-formed if
6681 // its first parameter is of type (optionally cv-qualified) X and
6682 // either there are no other parameters or else all other
6683 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00006684 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00006685 ((Constructor->getNumParams() == 1) ||
6686 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00006687 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6688 Constructor->getTemplateSpecializationKind()
6689 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00006690 QualType ParamType = Constructor->getParamDecl(0)->getType();
6691 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6692 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00006693 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00006694 const char *ConstRef
6695 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6696 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00006697 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00006698 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00006699
6700 // FIXME: Rather that making the constructor invalid, we should endeavor
6701 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00006702 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00006703 }
6704 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00006705}
6706
John McCall15442822010-08-04 01:04:25 +00006707/// CheckDestructor - Checks a fully-formed destructor definition for
6708/// well-formedness, issuing any diagnostics required. Returns true
6709/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006710bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00006711 CXXRecordDecl *RD = Destructor->getParent();
6712
Peter Collingbournef51cfb82013-05-20 14:12:25 +00006713 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson6d701392009-11-15 22:49:34 +00006714 SourceLocation Loc;
6715
6716 if (!Destructor->isImplicit())
6717 Loc = Destructor->getLocation();
6718 else
6719 Loc = RD->getLocation();
6720
6721 // If we have a virtual destructor, look up the deallocation function
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006722 FunctionDecl *OperatorDelete = nullptr;
Anders Carlsson6d701392009-11-15 22:49:34 +00006723 DeclarationName Name =
6724 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006725 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00006726 return true;
Bill Wendlingc12b43a2013-12-07 23:53:50 +00006727 // If there's no class-specific operator delete, look up the global
6728 // non-array delete.
6729 if (!OperatorDelete)
6730 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall5efd91a2010-07-03 18:33:00 +00006731
Eli Friedman5f2987c2012-02-02 03:46:19 +00006732 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00006733
6734 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00006735 }
Anders Carlsson37909802009-11-30 21:24:50 +00006736
6737 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00006738}
6739
Douglas Gregor42a552f2008-11-05 20:51:48 +00006740/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6741/// the well-formednes of the destructor declarator @p D with type @p
6742/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00006743/// emit diagnostics and set the declarator to invalid. Even if this happens,
6744/// will be updated to reflect a well-formed type for the destructor and
6745/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00006746QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00006747 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006748 // C++ [class.dtor]p1:
6749 // [...] A typedef-name that names a class is a class-name
6750 // (7.1.3); however, a typedef-name that names a class shall not
6751 // be used as the identifier in the declarator for a destructor
6752 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006753 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00006754 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00006755 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00006756 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00006757 else if (const TemplateSpecializationType *TST =
6758 DeclaratorType->getAs<TemplateSpecializationType>())
6759 if (TST->isTypeAlias())
6760 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6761 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006762
6763 // C++ [class.dtor]p2:
6764 // A destructor is used to destroy objects of its class type. A
6765 // destructor takes no parameters, and no return type can be
6766 // specified for it (not even void). The address of a destructor
6767 // shall not be taken. A destructor shall not be static. A
6768 // destructor can be invoked for a const, volatile or const
6769 // volatile object. A destructor shall not be declared const,
6770 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00006771 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00006772 if (!D.isInvalidType())
6773 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6774 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00006775 << SourceRange(D.getIdentifierLoc())
6776 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6777
John McCalld931b082010-08-26 03:08:43 +00006778 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006779 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006780 if (!D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006781 // Destructors don't have return types, but the parser will
6782 // happily parse something like:
6783 //
6784 // class X {
6785 // float ~X();
6786 // };
6787 //
6788 // The return type will be eliminated later.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006789 if (D.getDeclSpec().hasTypeSpecifier())
6790 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6791 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6792 << SourceRange(D.getIdentifierLoc());
6793 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6794 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6795 SourceLocation(),
6796 D.getDeclSpec().getConstSpecLoc(),
6797 D.getDeclSpec().getVolatileSpecLoc(),
6798 D.getDeclSpec().getRestrictSpecLoc(),
6799 D.getDeclSpec().getAtomicSpecLoc());
6800 D.setInvalidType();
6801 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00006802 }
Mike Stump1eb44332009-09-09 15:08:12 +00006803
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006804 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00006805 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00006806 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006807 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6808 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006809 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006810 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6811 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006812 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006813 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6814 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00006815 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006816 }
6817
Douglas Gregorc938c162011-01-26 05:01:58 +00006818 // C++0x [class.dtor]p2:
6819 // A destructor shall not be declared with a ref-qualifier.
6820 if (FTI.hasRefQualifier()) {
6821 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6822 << FTI.RefQualifierIsLValueRef
6823 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6824 D.setInvalidType();
6825 }
6826
Douglas Gregor42a552f2008-11-05 20:51:48 +00006827 // Make sure we don't have any parameters.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006828 if (FTIHasNonVoidParameters(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006829 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6830
6831 // Delete the parameters.
Stephen Hines651f13c2014-04-23 16:59:28 -07006832 FTI.freeParams();
Chris Lattner65401802009-04-25 08:28:21 +00006833 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006834 }
6835
Mike Stump1eb44332009-09-09 15:08:12 +00006836 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00006837 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006838 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00006839 D.setInvalidType();
6840 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00006841
6842 // Rebuild the function type "R" without any type qualifiers or
6843 // parameters (in case any of the errors above fired) and with
6844 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00006845 // types.
John McCalle23cf432010-12-14 08:05:40 +00006846 if (!D.isInvalidType())
6847 return R;
6848
Douglas Gregord92ec472010-07-01 05:10:53 +00006849 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006850 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6851 EPI.Variadic = false;
6852 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006853 EPI.RefQualifier = RQ_None;
Dmitri Gribenko55431692013-05-05 00:41:58 +00006854 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006855}
6856
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006857static void extendLeft(SourceRange &R, const SourceRange &Before) {
6858 if (Before.isInvalid())
6859 return;
6860 R.setBegin(Before.getBegin());
6861 if (R.getEnd().isInvalid())
6862 R.setEnd(Before.getEnd());
6863}
6864
6865static void extendRight(SourceRange &R, const SourceRange &After) {
6866 if (After.isInvalid())
6867 return;
6868 if (R.getBegin().isInvalid())
6869 R.setBegin(After.getBegin());
6870 R.setEnd(After.getEnd());
6871}
6872
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006873/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6874/// well-formednes of the conversion function declarator @p D with
6875/// type @p R. If there are any errors in the declarator, this routine
6876/// will emit diagnostics and return true. Otherwise, it will return
6877/// false. Either way, the type @p R will be updated to reflect a
6878/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00006879void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00006880 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006881 // C++ [class.conv.fct]p1:
6882 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00006883 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00006884 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00006885 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00006886 if (!D.isInvalidType())
6887 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman4cde94a2013-06-20 20:58:02 +00006888 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6889 << D.getName().getSourceRange();
Chris Lattner6e475012009-04-25 08:35:12 +00006890 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006891 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006892 }
John McCalla3f81372010-04-13 00:04:31 +00006893
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006894 TypeSourceInfo *ConvTSI = nullptr;
6895 QualType ConvType =
6896 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
John McCalla3f81372010-04-13 00:04:31 +00006897
Chris Lattner6e475012009-04-25 08:35:12 +00006898 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006899 // Conversion functions don't have return types, but the parser will
6900 // happily parse something like:
6901 //
6902 // class X {
6903 // float operator bool();
6904 // };
6905 //
6906 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006907 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6908 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6909 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00006910 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006911 }
6912
John McCalla3f81372010-04-13 00:04:31 +00006913 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6914
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006915 // Make sure we don't have any parameters.
Stephen Hines651f13c2014-04-23 16:59:28 -07006916 if (Proto->getNumParams() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006917 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6918
6919 // Delete the parameters.
Stephen Hines651f13c2014-04-23 16:59:28 -07006920 D.getFunctionTypeInfo().freeParams();
Chris Lattner6e475012009-04-25 08:35:12 +00006921 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00006922 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006923 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00006924 D.setInvalidType();
6925 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006926
John McCalla3f81372010-04-13 00:04:31 +00006927 // Diagnose "&operator bool()" and other such nonsense. This
6928 // is actually a gcc extension which we don't support.
Stephen Hines651f13c2014-04-23 16:59:28 -07006929 if (Proto->getReturnType() != ConvType) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07006930 bool NeedsTypedef = false;
6931 SourceRange Before, After;
6932
6933 // Walk the chunks and extract information on them for our diagnostic.
6934 bool PastFunctionChunk = false;
6935 for (auto &Chunk : D.type_objects()) {
6936 switch (Chunk.Kind) {
6937 case DeclaratorChunk::Function:
6938 if (!PastFunctionChunk) {
6939 if (Chunk.Fun.HasTrailingReturnType) {
6940 TypeSourceInfo *TRT = nullptr;
6941 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
6942 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
6943 }
6944 PastFunctionChunk = true;
6945 break;
6946 }
6947 // Fall through.
6948 case DeclaratorChunk::Array:
6949 NeedsTypedef = true;
6950 extendRight(After, Chunk.getSourceRange());
6951 break;
6952
6953 case DeclaratorChunk::Pointer:
6954 case DeclaratorChunk::BlockPointer:
6955 case DeclaratorChunk::Reference:
6956 case DeclaratorChunk::MemberPointer:
6957 extendLeft(Before, Chunk.getSourceRange());
6958 break;
6959
6960 case DeclaratorChunk::Paren:
6961 extendLeft(Before, Chunk.Loc);
6962 extendRight(After, Chunk.EndLoc);
6963 break;
6964 }
6965 }
6966
6967 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
6968 After.isValid() ? After.getBegin() :
6969 D.getIdentifierLoc();
6970 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
6971 DB << Before << After;
6972
6973 if (!NeedsTypedef) {
6974 DB << /*don't need a typedef*/0;
6975
6976 // If we can provide a correct fix-it hint, do so.
6977 if (After.isInvalid() && ConvTSI) {
6978 SourceLocation InsertLoc =
6979 PP.getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
6980 DB << FixItHint::CreateInsertion(InsertLoc, " ")
6981 << FixItHint::CreateInsertionFromRange(
6982 InsertLoc, CharSourceRange::getTokenRange(Before))
6983 << FixItHint::CreateRemoval(Before);
6984 }
6985 } else if (!Proto->getReturnType()->isDependentType()) {
6986 DB << /*typedef*/1 << Proto->getReturnType();
6987 } else if (getLangOpts().CPlusPlus11) {
6988 DB << /*alias template*/2 << Proto->getReturnType();
6989 } else {
6990 DB << /*might not be fixable*/3;
6991 }
6992
6993 // Recover by incorporating the other type chunks into the result type.
6994 // Note, this does *not* change the name of the function. This is compatible
6995 // with the GCC extension:
6996 // struct S { &operator int(); } s;
6997 // int &r = s.operator int(); // ok in GCC
6998 // S::operator int&() {} // error in GCC, function name is 'operator int'.
Stephen Hines651f13c2014-04-23 16:59:28 -07006999 ConvType = Proto->getReturnType();
John McCalla3f81372010-04-13 00:04:31 +00007000 }
7001
Douglas Gregor2f1bc522008-11-07 20:08:42 +00007002 // C++ [class.conv.fct]p4:
7003 // The conversion-type-id shall not represent a function type nor
7004 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00007005 if (ConvType->isArrayType()) {
7006 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
7007 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00007008 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00007009 } else if (ConvType->isFunctionType()) {
7010 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
7011 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00007012 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00007013 }
7014
7015 // Rebuild the function type "R" without any parameters (in case any
7016 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00007017 // return type.
John McCalle23cf432010-12-14 08:05:40 +00007018 if (D.isInvalidType())
Dmitri Gribenko55431692013-05-05 00:41:58 +00007019 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00007020
Douglas Gregor09f41cf2009-01-14 15:45:31 +00007021 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00007022 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00007023 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00007024 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00007025 diag::warn_cxx98_compat_explicit_conversion_functions :
7026 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00007027 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00007028}
7029
Douglas Gregor2f1bc522008-11-07 20:08:42 +00007030/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
7031/// the declaration of the given C++ conversion function. This routine
7032/// is responsible for recording the conversion function in the C++
7033/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00007034Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00007035 assert(Conversion && "Expected to receive a conversion function declaration");
7036
Douglas Gregor9d350972008-12-12 08:25:50 +00007037 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00007038
7039 // Make sure we aren't redeclaring the conversion function.
7040 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00007041
7042 // C++ [class.conv.fct]p1:
7043 // [...] A conversion function is never used to convert a
7044 // (possibly cv-qualified) object to the (possibly cv-qualified)
7045 // same object type (or a reference to it), to a (possibly
7046 // cv-qualified) base class of that type (or a reference to it),
7047 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00007048 // FIXME: Suppress this warning if the conversion function ends up being a
7049 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00007050 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00007051 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00007052 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00007053 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00007054 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
7055 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00007056 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00007057 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00007058 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
7059 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00007060 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00007061 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00007062 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00007063 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00007064 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00007065 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00007066 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00007067 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00007068 }
7069
Douglas Gregore80622f2010-09-29 04:25:11 +00007070 if (FunctionTemplateDecl *ConversionTemplate
7071 = Conversion->getDescribedFunctionTemplate())
7072 return ConversionTemplate;
7073
John McCalld226f652010-08-21 09:40:31 +00007074 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00007075}
7076
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00007077//===----------------------------------------------------------------------===//
7078// Namespace Handling
7079//===----------------------------------------------------------------------===//
7080
Richard Smithd1a55a62012-10-04 22:13:39 +00007081/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
7082/// reopened.
7083static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
7084 SourceLocation Loc,
7085 IdentifierInfo *II, bool *IsInline,
7086 NamespaceDecl *PrevNS) {
7087 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00007088
Richard Smithc969e6a2012-10-05 01:46:25 +00007089 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
7090 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
7091 // inline namespaces, with the intention of bringing names into namespace std.
7092 //
7093 // We support this just well enough to get that case working; this is not
7094 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00007095 if (*IsInline && II && II->getName().startswith("__atomic") &&
7096 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00007097 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00007098 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
7099 NS = NS->getPreviousDecl())
7100 NS->setInline(*IsInline);
7101 // Patch up the lookup table for the containing namespace. This isn't really
7102 // correct, but it's good enough for this particular case.
Stephen Hines651f13c2014-04-23 16:59:28 -07007103 for (auto *I : PrevNS->decls())
7104 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smithd1a55a62012-10-04 22:13:39 +00007105 PrevNS->getParent()->makeDeclVisibleInContext(ND);
7106 return;
7107 }
7108
7109 if (PrevNS->isInline())
7110 // The user probably just forgot the 'inline', so suggest that it
7111 // be added back.
7112 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
7113 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
7114 else
Stephen Hines651f13c2014-04-23 16:59:28 -07007115 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
Richard Smithd1a55a62012-10-04 22:13:39 +00007116
7117 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
7118 *IsInline = PrevNS->isInline();
7119}
John McCallea318642010-08-26 09:15:37 +00007120
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00007121/// ActOnStartNamespaceDef - This is called at the start of a namespace
7122/// definition.
John McCalld226f652010-08-21 09:40:31 +00007123Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00007124 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00007125 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00007126 SourceLocation IdentLoc,
7127 IdentifierInfo *II,
7128 SourceLocation LBrace,
7129 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00007130 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
7131 // For anonymous namespace, take the location of the left brace.
7132 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00007133 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00007134 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00007135 bool IsStd = false;
7136 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00007137 Scope *DeclRegionScope = NamespcScope->getParent();
7138
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007139 NamespaceDecl *PrevNS = nullptr;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00007140 if (II) {
7141 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00007142 // The identifier in an original-namespace-definition shall not
7143 // have been previously defined in the declarative region in
7144 // which the original-namespace-definition appears. The
7145 // identifier in an original-namespace-definition is the name of
7146 // the namespace. Subsequently in that declarative region, it is
7147 // treated as an original-namespace-name.
7148 //
7149 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00007150 // look through using directives, just look for any ordinary names.
7151
7152 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00007153 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
7154 Decl::IDNS_Namespace;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007155 NamedDecl *PrevDecl = nullptr;
David Blaikie3bc93e32012-12-19 00:45:41 +00007156 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
7157 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
7158 ++I) {
7159 if ((*I)->getIdentifierNamespace() & IDNS) {
7160 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00007161 break;
7162 }
7163 }
7164
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00007165 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
7166
7167 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00007168 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00007169 if (IsInline != PrevNS->isInline())
7170 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
7171 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00007172 } else if (PrevDecl) {
7173 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00007174 Diag(Loc, diag::err_redefinition_different_kind)
7175 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00007176 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00007177 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00007178 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00007179 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00007180 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00007181 // This is the first "real" definition of the namespace "std", so update
7182 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00007183 PrevNS = getStdNamespace();
7184 IsStd = true;
7185 AddToKnown = !IsInline;
7186 } else {
7187 // We've seen this namespace for the first time.
7188 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00007189 }
Douglas Gregor44b43212008-12-11 16:49:14 +00007190 } else {
John McCall9aeed322009-10-01 00:25:31 +00007191 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00007192
7193 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00007194 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00007195 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00007196 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00007197 } else {
7198 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00007199 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00007200 }
7201
Richard Smithd1a55a62012-10-04 22:13:39 +00007202 if (PrevNS && IsInline != PrevNS->isInline())
7203 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
7204 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00007205 }
7206
7207 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
7208 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00007209 if (IsInvalid)
7210 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00007211
7212 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00007213
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00007214 // FIXME: Should we be merging attributes?
7215 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00007216 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00007217
7218 if (IsStd)
7219 StdNamespace = Namespc;
7220 if (AddToKnown)
7221 KnownNamespaces[Namespc] = false;
7222
7223 if (II) {
7224 PushOnScopeChains(Namespc, DeclRegionScope);
7225 } else {
7226 // Link the anonymous namespace into its parent.
7227 DeclContext *Parent = CurContext->getRedeclContext();
7228 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7229 TU->setAnonymousNamespace(Namespc);
7230 } else {
7231 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00007232 }
John McCall9aeed322009-10-01 00:25:31 +00007233
Douglas Gregora4181472010-03-24 00:46:35 +00007234 CurContext->addDecl(Namespc);
7235
John McCall9aeed322009-10-01 00:25:31 +00007236 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
7237 // behaves as if it were replaced by
7238 // namespace unique { /* empty body */ }
7239 // using namespace unique;
7240 // namespace unique { namespace-body }
7241 // where all occurrences of 'unique' in a translation unit are
7242 // replaced by the same identifier and this identifier differs
7243 // from all other identifiers in the entire program.
7244
7245 // We just create the namespace with an empty name and then add an
7246 // implicit using declaration, just like the standard suggests.
7247 //
7248 // CodeGen enforces the "universally unique" aspect by giving all
7249 // declarations semantically contained within an anonymous
7250 // namespace internal linkage.
7251
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00007252 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00007253 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00007254 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00007255 /* 'using' */ LBrace,
7256 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00007257 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00007258 /* identifier */ SourceLocation(),
7259 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00007260 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00007261 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00007262 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00007263 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00007264 }
7265
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00007266 ActOnDocumentableDecl(Namespc);
7267
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00007268 // Although we could have an invalid decl (i.e. the namespace name is a
7269 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00007270 // FIXME: We should be able to push Namespc here, so that the each DeclContext
7271 // for the namespace has the declarations that showed up in that particular
7272 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00007273 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00007274 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00007275}
7276
Sebastian Redleb0d8c92009-11-23 15:34:23 +00007277/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
7278/// is a namespace alias, returns the namespace it points to.
7279static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
7280 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
7281 return AD->getNamespace();
7282 return dyn_cast_or_null<NamespaceDecl>(D);
7283}
7284
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00007285/// ActOnFinishNamespaceDef - This callback is called after a namespace is
7286/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00007287void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00007288 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
7289 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00007290 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00007291 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00007292 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00007293 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00007294}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007295
John McCall384aff82010-08-25 07:42:41 +00007296CXXRecordDecl *Sema::getStdBadAlloc() const {
7297 return cast_or_null<CXXRecordDecl>(
7298 StdBadAlloc.get(Context.getExternalSource()));
7299}
7300
7301NamespaceDecl *Sema::getStdNamespace() const {
7302 return cast_or_null<NamespaceDecl>(
7303 StdNamespace.get(Context.getExternalSource()));
7304}
7305
Douglas Gregor66992202010-06-29 17:53:46 +00007306/// \brief Retrieve the special "std" namespace, which may require us to
7307/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00007308NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00007309 if (!StdNamespace) {
7310 // The "std" namespace has not yet been defined, so build one implicitly.
7311 StdNamespace = NamespaceDecl::Create(Context,
7312 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00007313 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00007314 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00007315 &PP.getIdentifierTable().get("std"),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007316 /*PrevDecl=*/nullptr);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00007317 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00007318 }
Stephen Hines176edba2014-12-01 14:53:08 -08007319
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00007320 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00007321}
7322
Sebastian Redl395e04d2012-01-17 22:49:33 +00007323bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00007324 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00007325 "Looking for std::initializer_list outside of C++.");
7326
7327 // We're looking for implicit instantiations of
7328 // template <typename E> class std::initializer_list.
7329
7330 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
7331 return false;
7332
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007333 ClassTemplateDecl *Template = nullptr;
7334 const TemplateArgument *Arguments = nullptr;
Sebastian Redl395e04d2012-01-17 22:49:33 +00007335
Sebastian Redl84760e32012-01-17 22:49:58 +00007336 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00007337
Sebastian Redl84760e32012-01-17 22:49:58 +00007338 ClassTemplateSpecializationDecl *Specialization =
7339 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
7340 if (!Specialization)
7341 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00007342
Sebastian Redl84760e32012-01-17 22:49:58 +00007343 Template = Specialization->getSpecializedTemplate();
7344 Arguments = Specialization->getTemplateArgs().data();
7345 } else if (const TemplateSpecializationType *TST =
7346 Ty->getAs<TemplateSpecializationType>()) {
7347 Template = dyn_cast_or_null<ClassTemplateDecl>(
7348 TST->getTemplateName().getAsTemplateDecl());
7349 Arguments = TST->getArgs();
7350 }
7351 if (!Template)
7352 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00007353
7354 if (!StdInitializerList) {
7355 // Haven't recognized std::initializer_list yet, maybe this is it.
7356 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
7357 if (TemplateClass->getIdentifier() !=
7358 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00007359 !getStdNamespace()->InEnclosingNamespaceSetOf(
7360 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00007361 return false;
7362 // This is a template called std::initializer_list, but is it the right
7363 // template?
7364 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00007365 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00007366 return false;
7367 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
7368 return false;
7369
7370 // It's the right template.
7371 StdInitializerList = Template;
7372 }
7373
Stephen Hines0e2c34f2015-03-23 12:09:02 -07007374 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
Sebastian Redl395e04d2012-01-17 22:49:33 +00007375 return false;
7376
7377 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00007378 if (Element)
7379 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00007380 return true;
7381}
7382
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00007383static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7384 NamespaceDecl *Std = S.getStdNamespace();
7385 if (!Std) {
7386 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007387 return nullptr;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00007388 }
7389
7390 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7391 Loc, Sema::LookupOrdinaryName);
7392 if (!S.LookupQualifiedName(Result, Std)) {
7393 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007394 return nullptr;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00007395 }
7396 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7397 if (!Template) {
7398 Result.suppressDiagnostics();
7399 // We found something weird. Complain about the first thing we found.
7400 NamedDecl *Found = *Result.begin();
7401 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007402 return nullptr;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00007403 }
7404
7405 // We found some template called std::initializer_list. Now verify that it's
7406 // correct.
7407 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00007408 if (Params->getMinRequiredArguments() != 1 ||
7409 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00007410 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007411 return nullptr;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00007412 }
7413
7414 return Template;
7415}
7416
7417QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7418 if (!StdInitializerList) {
7419 StdInitializerList = LookupStdInitializerList(*this, Loc);
7420 if (!StdInitializerList)
7421 return QualType();
7422 }
7423
7424 TemplateArgumentListInfo Args(Loc, Loc);
7425 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7426 Context.getTrivialTypeSourceInfo(Element,
7427 Loc)));
7428 return Context.getCanonicalType(
7429 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7430}
7431
Sebastian Redl98d36062012-01-17 22:50:14 +00007432bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7433 // C++ [dcl.init.list]p2:
7434 // A constructor is an initializer-list constructor if its first parameter
7435 // is of type std::initializer_list<E> or reference to possibly cv-qualified
7436 // std::initializer_list<E> for some type E, and either there are no other
7437 // parameters or else all other parameters have default arguments.
7438 if (Ctor->getNumParams() < 1 ||
7439 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7440 return false;
7441
7442 QualType ArgType = Ctor->getParamDecl(0)->getType();
7443 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7444 ArgType = RT->getPointeeType().getUnqualifiedType();
7445
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007446 return isStdInitializerList(ArgType, nullptr);
Sebastian Redl98d36062012-01-17 22:50:14 +00007447}
7448
Douglas Gregor9172aa62011-03-26 22:25:30 +00007449/// \brief Determine whether a using statement is in a context where it will be
7450/// apply in all contexts.
7451static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7452 switch (CurContext->getDeclKind()) {
7453 case Decl::TranslationUnit:
7454 return true;
7455 case Decl::LinkageSpec:
7456 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7457 default:
7458 return false;
7459 }
7460}
7461
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00007462namespace {
7463
7464// Callback to only accept typo corrections that are namespaces.
7465class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007466public:
Stephen Hines651f13c2014-04-23 16:59:28 -07007467 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007468 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00007469 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00007470 return false;
7471 }
7472};
7473
7474}
7475
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007476static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7477 CXXScopeSpec &SS,
7478 SourceLocation IdentLoc,
7479 IdentifierInfo *Ident) {
7480 R.clear();
Stephen Hines176edba2014-12-01 14:53:08 -08007481 if (TypoCorrection Corrected =
7482 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
7483 llvm::make_unique<NamespaceValidatorCCC>(),
7484 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00007485 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smith2d670972013-08-17 00:46:16 +00007486 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7487 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00007488 Ident->getName().equals(CorrectedStr);
Richard Smith2d670972013-08-17 00:46:16 +00007489 S.diagnoseTypo(Corrected,
7490 S.PDiag(diag::err_using_directive_member_suggest)
7491 << Ident << DC << DroppedSpecifier << SS.getRange(),
7492 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00007493 } else {
Richard Smith2d670972013-08-17 00:46:16 +00007494 S.diagnoseTypo(Corrected,
7495 S.PDiag(diag::err_using_directive_suggest) << Ident,
7496 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00007497 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00007498 R.addDecl(Corrected.getCorrectionDecl());
7499 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007500 }
7501 return false;
7502}
7503
John McCalld226f652010-08-21 09:40:31 +00007504Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007505 SourceLocation UsingLoc,
7506 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007507 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007508 SourceLocation IdentLoc,
7509 IdentifierInfo *NamespcName,
7510 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00007511 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7512 assert(NamespcName && "Invalid NamespcName.");
7513 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00007514
7515 // This can only happen along a recovery path.
7516 while (S->getFlags() & Scope::TemplateParamScope)
7517 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00007518 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00007519
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007520 UsingDirectiveDecl *UDir = nullptr;
7521 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregor66992202010-06-29 17:53:46 +00007522 if (SS.isSet())
Stephen Hines651f13c2014-04-23 16:59:28 -07007523 Qualifier = SS.getScopeRep();
Douglas Gregor66992202010-06-29 17:53:46 +00007524
Douglas Gregoreb11cd02009-01-14 22:20:51 +00007525 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007526 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7527 LookupParsedName(R, S, &SS);
7528 if (R.isAmbiguous())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007529 return nullptr;
John McCalla24dc2e2009-11-17 02:14:36 +00007530
Douglas Gregor66992202010-06-29 17:53:46 +00007531 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007532 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00007533 // Allow "using namespace std;" or "using namespace ::std;" even if
7534 // "std" hasn't been defined yet, for GCC compatibility.
7535 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7536 NamespcName->isStr("std")) {
7537 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00007538 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00007539 R.resolveKind();
7540 }
7541 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007542 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00007543 }
7544
John McCallf36e02d2009-10-09 21:13:30 +00007545 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00007546 NamedDecl *Named = R.getFoundDecl();
7547 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7548 && "expected namespace decl");
Stephen Hines176edba2014-12-01 14:53:08 -08007549
Stephen Hines0e2c34f2015-03-23 12:09:02 -07007550 // The use of a nested name specifier may trigger deprecation warnings.
7551 DiagnoseUseOfDecl(Named, IdentLoc);
Stephen Hines176edba2014-12-01 14:53:08 -08007552
Douglas Gregor2a3009a2009-02-03 19:21:40 +00007553 // C++ [namespace.udir]p1:
7554 // A using-directive specifies that the names in the nominated
7555 // namespace can be used in the scope in which the
7556 // using-directive appears after the using-directive. During
7557 // unqualified name lookup (3.4.1), the names appear as if they
7558 // were declared in the nearest enclosing namespace which
7559 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00007560 // namespace. [Note: in this context, "contains" means "contains
7561 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00007562
7563 // Find enclosing context containing both using-directive and
7564 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00007565 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00007566 DeclContext *CommonAncestor = cast<DeclContext>(NS);
7567 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7568 CommonAncestor = CommonAncestor->getParent();
7569
Sebastian Redleb0d8c92009-11-23 15:34:23 +00007570 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00007571 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00007572 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00007573
Douglas Gregor9172aa62011-03-26 22:25:30 +00007574 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman24146972013-08-22 00:27:10 +00007575 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00007576 Diag(IdentLoc, diag::warn_using_directive_in_header);
7577 }
7578
Douglas Gregor2a3009a2009-02-03 19:21:40 +00007579 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00007580 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00007581 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00007582 }
7583
Richard Smith6b3d3e52013-02-20 19:22:51 +00007584 if (UDir)
7585 ProcessDeclAttributeList(S, UDir, AttrList);
7586
John McCalld226f652010-08-21 09:40:31 +00007587 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00007588}
7589
7590void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00007591 // If the scope has an associated entity and the using directive is at
7592 // namespace or translation unit scope, add the UsingDirectiveDecl into
7593 // its lookup structure so qualified name lookup can find it.
Ted Kremenekf0d58612013-10-08 17:08:03 +00007594 DeclContext *Ctx = S->getEntity();
Richard Smith1b7f9cb2012-03-13 03:12:56 +00007595 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00007596 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00007597 else
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007598 // Otherwise, it is at block scope. The using-directives will affect lookup
Richard Smith1b7f9cb2012-03-13 03:12:56 +00007599 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00007600 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00007601}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007602
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007603
John McCalld226f652010-08-21 09:40:31 +00007604Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00007605 AccessSpecifier AS,
7606 bool HasUsingKeyword,
7607 SourceLocation UsingLoc,
7608 CXXScopeSpec &SS,
7609 UnqualifiedId &Name,
7610 AttributeList *AttrList,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007611 bool HasTypenameKeyword,
John McCall78b81052010-11-10 02:40:36 +00007612 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007613 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00007614
Douglas Gregor12c118a2009-11-04 16:30:06 +00007615 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00007616 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00007617 case UnqualifiedId::IK_Identifier:
7618 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00007619 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00007620 case UnqualifiedId::IK_ConversionFunctionId:
7621 break;
7622
7623 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00007624 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00007625 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00007626 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00007627 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00007628 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00007629 diag::err_using_decl_constructor)
7630 << SS.getRange();
7631
Richard Smith80ad52f2013-01-02 11:42:31 +00007632 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00007633
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007634 return nullptr;
7635
Douglas Gregor12c118a2009-11-04 16:30:06 +00007636 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00007637 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00007638 << SS.getRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007639 return nullptr;
7640
Douglas Gregor12c118a2009-11-04 16:30:06 +00007641 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00007642 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00007643 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007644 return nullptr;
Douglas Gregor12c118a2009-11-04 16:30:06 +00007645 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007646
7647 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7648 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00007649 if (!TargetName)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007650 return nullptr;
John McCall604e7f12009-12-08 07:46:18 +00007651
Richard Smith07b0fdc2013-03-18 21:12:30 +00007652 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00007653 if (!HasUsingKeyword) {
Enea Zaffanellad4de59d2013-07-17 17:28:56 +00007654 Diag(Name.getLocStart(),
Richard Smith1b2209f2013-06-13 02:12:17 +00007655 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7656 : diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00007657 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00007658 }
7659
Douglas Gregor56c04582010-12-16 00:46:58 +00007660 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7661 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007662 return nullptr;
Douglas Gregor56c04582010-12-16 00:46:58 +00007663
John McCall9488ea12009-11-17 05:59:44 +00007664 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007665 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007666 /* IsInstantiation */ false,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007667 HasTypenameKeyword, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00007668 if (UD)
7669 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00007670
John McCalld226f652010-08-21 09:40:31 +00007671 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00007672}
7673
Douglas Gregor09acc982010-07-07 23:08:52 +00007674/// \brief Determine whether a using declaration considers the given
7675/// declarations as "equivalent", e.g., if they are redeclarations of
7676/// the same entity or are both typedefs of the same type.
Richard Smithf06a28932013-10-23 02:17:46 +00007677static bool
7678IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7679 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor09acc982010-07-07 23:08:52 +00007680 return true;
Douglas Gregor09acc982010-07-07 23:08:52 +00007681
Richard Smith162e1c12011-04-15 14:24:37 +00007682 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithf06a28932013-10-23 02:17:46 +00007683 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor09acc982010-07-07 23:08:52 +00007684 return Context.hasSameType(TD1->getUnderlyingType(),
7685 TD2->getUnderlyingType());
Douglas Gregor09acc982010-07-07 23:08:52 +00007686
7687 return false;
7688}
7689
7690
John McCall9f54ad42009-12-10 09:41:52 +00007691/// Determines whether to create a using shadow decl for a particular
7692/// decl, given the set of decls existing prior to this using lookup.
7693bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithf06a28932013-10-23 02:17:46 +00007694 const LookupResult &Previous,
7695 UsingShadowDecl *&PrevShadow) {
John McCall9f54ad42009-12-10 09:41:52 +00007696 // Diagnose finding a decl which is not from a base class of the
7697 // current class. We do this now because there are cases where this
7698 // function will silently decide not to build a shadow decl, which
7699 // will pre-empt further diagnostics.
7700 //
7701 // We don't need to do this in C++0x because we do the check once on
7702 // the qualifier.
7703 //
7704 // FIXME: diagnose the following if we care enough:
7705 // struct A { int foo; };
7706 // struct B : A { using A::foo; };
7707 // template <class T> struct C : A {};
7708 // template <class T> struct D : C<T> { using B::foo; } // <---
7709 // This is invalid (during instantiation) in C++03 because B::foo
7710 // resolves to the using decl in B, which is not a base class of D<T>.
7711 // We can't diagnose it immediately because C<T> is an unknown
7712 // specialization. The UsingShadowDecl in D<T> then points directly
7713 // to A::foo, which will look well-formed when we instantiate.
7714 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00007715 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00007716 DeclContext *OrigDC = Orig->getDeclContext();
7717
7718 // Handle enums and anonymous structs.
7719 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7720 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7721 while (OrigRec->isAnonymousStructOrUnion())
7722 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7723
7724 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7725 if (OrigDC == CurContext) {
7726 Diag(Using->getLocation(),
7727 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00007728 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00007729 Diag(Orig->getLocation(), diag::note_using_decl_target);
7730 return true;
7731 }
7732
Douglas Gregordc355712011-02-25 00:36:19 +00007733 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00007734 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00007735 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00007736 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00007737 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00007738 Diag(Orig->getLocation(), diag::note_using_decl_target);
7739 return true;
7740 }
7741 }
7742
7743 if (Previous.empty()) return false;
7744
7745 NamedDecl *Target = Orig;
7746 if (isa<UsingShadowDecl>(Target))
7747 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7748
John McCalld7533ec2009-12-11 02:33:26 +00007749 // If the target happens to be one of the previous declarations, we
7750 // don't have a conflict.
7751 //
7752 // FIXME: but we might be increasing its access, in which case we
7753 // should redeclare it.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007754 NamedDecl *NonTag = nullptr, *Tag = nullptr;
Richard Smithf06a28932013-10-23 02:17:46 +00007755 bool FoundEquivalentDecl = false;
John McCalld7533ec2009-12-11 02:33:26 +00007756 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7757 I != E; ++I) {
7758 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithf06a28932013-10-23 02:17:46 +00007759 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7760 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7761 PrevShadow = Shadow;
7762 FoundEquivalentDecl = true;
7763 }
John McCalld7533ec2009-12-11 02:33:26 +00007764
7765 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7766 }
7767
Richard Smithf06a28932013-10-23 02:17:46 +00007768 if (FoundEquivalentDecl)
7769 return false;
7770
Stephen Hines651f13c2014-04-23 16:59:28 -07007771 if (FunctionDecl *FD = Target->getAsFunction()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007772 NamedDecl *OldDecl = nullptr;
7773 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7774 /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00007775 case Ovl_Overload:
7776 return false;
7777
7778 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00007779 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007780 break;
Stephen Hines651f13c2014-04-23 16:59:28 -07007781
John McCall9f54ad42009-12-10 09:41:52 +00007782 // We found a decl with the exact signature.
7783 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00007784 // If we're in a record, we want to hide the target, so we
7785 // return true (without a diagnostic) to tell the caller not to
7786 // build a shadow decl.
7787 if (CurContext->isRecord())
7788 return true;
7789
7790 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00007791 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007792 break;
7793 }
7794
7795 Diag(Target->getLocation(), diag::note_using_decl_target);
7796 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7797 return true;
7798 }
7799
7800 // Target is not a function.
7801
John McCall9f54ad42009-12-10 09:41:52 +00007802 if (isa<TagDecl>(Target)) {
7803 // No conflict between a tag and a non-tag.
7804 if (!Tag) return false;
7805
John McCall41ce66f2009-12-10 19:51:03 +00007806 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007807 Diag(Target->getLocation(), diag::note_using_decl_target);
7808 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7809 return true;
7810 }
7811
7812 // No conflict between a tag and a non-tag.
7813 if (!NonTag) return false;
7814
John McCall41ce66f2009-12-10 19:51:03 +00007815 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007816 Diag(Target->getLocation(), diag::note_using_decl_target);
7817 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7818 return true;
7819}
7820
John McCall9488ea12009-11-17 05:59:44 +00007821/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00007822UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00007823 UsingDecl *UD,
Richard Smithf06a28932013-10-23 02:17:46 +00007824 NamedDecl *Orig,
7825 UsingShadowDecl *PrevDecl) {
John McCall9488ea12009-11-17 05:59:44 +00007826
7827 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00007828 NamedDecl *Target = Orig;
7829 if (isa<UsingShadowDecl>(Target)) {
7830 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7831 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00007832 }
Richard Smithf06a28932013-10-23 02:17:46 +00007833
John McCall9488ea12009-11-17 05:59:44 +00007834 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00007835 = UsingShadowDecl::Create(Context, CurContext,
7836 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00007837 UD->addShadowDecl(Shadow);
Richard Smithf06a28932013-10-23 02:17:46 +00007838
Douglas Gregore80622f2010-09-29 04:25:11 +00007839 Shadow->setAccess(UD->getAccess());
7840 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7841 Shadow->setInvalidDecl();
Richard Smithf06a28932013-10-23 02:17:46 +00007842
7843 Shadow->setPreviousDecl(PrevDecl);
7844
John McCall9488ea12009-11-17 05:59:44 +00007845 if (S)
John McCall604e7f12009-12-08 07:46:18 +00007846 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00007847 else
John McCall604e7f12009-12-08 07:46:18 +00007848 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00007849
John McCall604e7f12009-12-08 07:46:18 +00007850
John McCall9f54ad42009-12-10 09:41:52 +00007851 return Shadow;
7852}
John McCall604e7f12009-12-08 07:46:18 +00007853
John McCall9f54ad42009-12-10 09:41:52 +00007854/// Hides a using shadow declaration. This is required by the current
7855/// using-decl implementation when a resolvable using declaration in a
7856/// class is followed by a declaration which would hide or override
7857/// one or more of the using decl's targets; for example:
7858///
7859/// struct Base { void foo(int); };
7860/// struct Derived : Base {
7861/// using Base::foo;
7862/// void foo(int);
7863/// };
7864///
7865/// The governing language is C++03 [namespace.udecl]p12:
7866///
7867/// When a using-declaration brings names from a base class into a
7868/// derived class scope, member functions in the derived class
7869/// override and/or hide member functions with the same name and
7870/// parameter types in a base class (rather than conflicting).
7871///
7872/// There are two ways to implement this:
7873/// (1) optimistically create shadow decls when they're not hidden
7874/// by existing declarations, or
7875/// (2) don't create any shadow decls (or at least don't make them
7876/// visible) until we've fully parsed/instantiated the class.
7877/// The problem with (1) is that we might have to retroactively remove
7878/// a shadow decl, which requires several O(n) operations because the
7879/// decl structures are (very reasonably) not designed for removal.
7880/// (2) avoids this but is very fiddly and phase-dependent.
7881void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00007882 if (Shadow->getDeclName().getNameKind() ==
7883 DeclarationName::CXXConversionFunctionName)
7884 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7885
John McCall9f54ad42009-12-10 09:41:52 +00007886 // Remove it from the DeclContext...
7887 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007888
John McCall9f54ad42009-12-10 09:41:52 +00007889 // ...and the scope, if applicable...
7890 if (S) {
John McCalld226f652010-08-21 09:40:31 +00007891 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00007892 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007893 }
7894
John McCall9f54ad42009-12-10 09:41:52 +00007895 // ...and the using decl.
7896 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7897
7898 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00007899 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00007900}
7901
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007902/// Find the base specifier for a base class with the given type.
7903static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7904 QualType DesiredBase,
7905 bool &AnyDependentBases) {
7906 // Check whether the named type is a direct base class.
7907 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7908 for (auto &Base : Derived->bases()) {
7909 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7910 if (CanonicalDesiredBase == BaseType)
7911 return &Base;
7912 if (BaseType->isDependentType())
7913 AnyDependentBases = true;
7914 }
7915 return nullptr;
7916}
7917
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007918namespace {
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007919class UsingValidatorCCC : public CorrectionCandidateCallback {
7920public:
Kaelyn Uhrainb5c77682013-10-19 00:05:00 +00007921 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007922 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007923 : HasTypenameKeyword(HasTypenameKeyword),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007924 IsInstantiation(IsInstantiation), OldNNS(NNS),
7925 RequireMemberOf(RequireMemberOf) {}
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007926
Stephen Hines651f13c2014-04-23 16:59:28 -07007927 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007928 NamedDecl *ND = Candidate.getCorrectionDecl();
7929
7930 // Keywords are not valid here.
7931 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007932 return false;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007933
7934 // Completely unqualified names are invalid for a 'using' declaration.
7935 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7936 return false;
7937
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007938 if (RequireMemberOf) {
7939 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7940 if (FoundRecord && FoundRecord->isInjectedClassName()) {
7941 // No-one ever wants a using-declaration to name an injected-class-name
7942 // of a base class, unless they're declaring an inheriting constructor.
7943 ASTContext &Ctx = ND->getASTContext();
7944 if (!Ctx.getLangOpts().CPlusPlus11)
7945 return false;
7946 QualType FoundType = Ctx.getRecordType(FoundRecord);
7947
7948 // Check that the injected-class-name is named as a member of its own
7949 // type; we don't want to suggest 'using Derived::Base;', since that
7950 // means something else.
7951 NestedNameSpecifier *Specifier =
7952 Candidate.WillReplaceSpecifier()
7953 ? Candidate.getCorrectionSpecifier()
7954 : OldNNS;
7955 if (!Specifier->getAsType() ||
7956 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
7957 return false;
7958
7959 // Check that this inheriting constructor declaration actually names a
7960 // direct base class of the current class.
7961 bool AnyDependentBases = false;
7962 if (!findDirectBaseWithType(RequireMemberOf,
7963 Ctx.getRecordType(FoundRecord),
7964 AnyDependentBases) &&
7965 !AnyDependentBases)
7966 return false;
7967 } else {
7968 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
7969 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
7970 return false;
7971
7972 // FIXME: Check that the base class member is accessible?
7973 }
7974 }
7975
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007976 if (isa<TypeDecl>(ND))
7977 return HasTypenameKeyword || !IsInstantiation;
7978
7979 return !HasTypenameKeyword;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007980 }
7981
7982private:
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007983 bool HasTypenameKeyword;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007984 bool IsInstantiation;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007985 NestedNameSpecifier *OldNNS;
7986 CXXRecordDecl *RequireMemberOf;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007987};
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007988} // end anonymous namespace
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007989
John McCall7ba107a2009-11-18 02:36:19 +00007990/// Builds a using declaration.
7991///
7992/// \param IsInstantiation - Whether this call arises from an
7993/// instantiation of an unresolved using declaration. We treat
7994/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00007995NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7996 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007997 CXXScopeSpec &SS,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007998 DeclarationNameInfo NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00007999 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00008000 bool IsInstantiation,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00008001 bool HasTypenameKeyword,
John McCall7ba107a2009-11-18 02:36:19 +00008002 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00008003 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00008004 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00008005 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00008006
Anders Carlsson550b14b2009-08-28 05:49:21 +00008007 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00008008
Anders Carlssoncf9f9212009-08-28 03:16:11 +00008009 if (SS.isEmpty()) {
8010 Diag(IdentLoc, diag::err_using_requires_qualname);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008011 return nullptr;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00008012 }
Mike Stump1eb44332009-09-09 15:08:12 +00008013
John McCall9f54ad42009-12-10 09:41:52 +00008014 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00008015 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00008016 ForRedeclaration);
8017 Previous.setHideTags(false);
8018 if (S) {
8019 LookupName(Previous, S);
8020
8021 // It is really dumb that we have to do this.
8022 LookupResult::Filter F = Previous.makeFilter();
8023 while (F.hasNext()) {
8024 NamedDecl *D = F.next();
8025 if (!isDeclInScope(D, CurContext, S))
8026 F.erase();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008027 // If we found a local extern declaration that's not ordinarily visible,
8028 // and this declaration is being added to a non-block scope, ignore it.
8029 // We're only checking for scope conflicts here, not also for violations
8030 // of the linkage rules.
8031 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
8032 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
8033 F.erase();
John McCall9f54ad42009-12-10 09:41:52 +00008034 }
8035 F.done();
8036 } else {
8037 assert(IsInstantiation && "no scope in non-instantiation");
8038 assert(CurContext->isRecord() && "scope not record in instantiation");
8039 LookupQualifiedName(Previous, CurContext);
8040 }
8041
John McCall9f54ad42009-12-10 09:41:52 +00008042 // Check for invalid redeclarations.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00008043 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
8044 SS, IdentLoc, Previous))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008045 return nullptr;
John McCall9f54ad42009-12-10 09:41:52 +00008046
8047 // Check for bad qualifiers.
Stephen Hines651f13c2014-04-23 16:59:28 -07008048 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008049 return nullptr;
John McCalled976492009-12-04 22:46:56 +00008050
John McCallaf8e6ed2009-11-12 03:15:40 +00008051 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00008052 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00008053 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00008054 if (!LookupContext) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00008055 if (HasTypenameKeyword) {
John McCalled976492009-12-04 22:46:56 +00008056 // FIXME: not all declaration name kinds are legal here
8057 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
8058 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00008059 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00008060 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00008061 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00008062 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
8063 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00008064 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008065 D->setAccess(AS);
8066 CurContext->addDecl(D);
8067 return D;
Anders Carlsson550b14b2009-08-28 05:49:21 +00008068 }
John McCalled976492009-12-04 22:46:56 +00008069
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008070 auto Build = [&](bool Invalid) {
8071 UsingDecl *UD =
8072 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
8073 HasTypenameKeyword);
8074 UD->setAccess(AS);
8075 CurContext->addDecl(UD);
8076 UD->setInvalidDecl(Invalid);
John McCall604e7f12009-12-08 07:46:18 +00008077 return UD;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008078 };
8079 auto BuildInvalid = [&]{ return Build(true); };
8080 auto BuildValid = [&]{ return Build(false); };
8081
8082 if (RequireCompleteDeclContext(SS, LookupContext))
8083 return BuildInvalid();
Anders Carlssoncf9f9212009-08-28 03:16:11 +00008084
Richard Smithc5a89a12012-04-02 01:30:27 +00008085 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00008086 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008087 UsingDecl *UD = BuildValid();
8088 CheckInheritingConstructorUsingDecl(UD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008089 return UD;
8090 }
8091
8092 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00008093
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00008094 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00008095
John McCall604e7f12009-12-08 07:46:18 +00008096 // Unlike most lookups, we don't always want to hide tag
8097 // declarations: tag names are visible through the using declaration
8098 // even if hidden by ordinary names, *except* in a dependent context
8099 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00008100 if (!IsInstantiation)
8101 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00008102
John McCallb9abd8722012-04-07 03:04:20 +00008103 // For the purposes of this lookup, we have a base object type
8104 // equal to that of the current context.
8105 if (CurContext->isRecord()) {
8106 R.setBaseObjectType(
8107 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
8108 }
8109
John McCalla24dc2e2009-11-17 02:14:36 +00008110 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00008111
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00008112 // Try to correct typos if possible.
John McCallf36e02d2009-10-09 21:13:30 +00008113 if (R.empty()) {
Stephen Hines176edba2014-12-01 14:53:08 -08008114 if (TypoCorrection Corrected = CorrectTypo(
8115 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
8116 llvm::make_unique<UsingValidatorCCC>(
8117 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
8118 dyn_cast<CXXRecordDecl>(CurContext)),
8119 CTK_ErrorRecovery)) {
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00008120 // We reject any correction for which ND would be NULL.
8121 NamedDecl *ND = Corrected.getCorrectionDecl();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008122
Richard Smith2d670972013-08-17 00:46:16 +00008123 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00008124 // literal '0' below.
Richard Smith2d670972013-08-17 00:46:16 +00008125 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
8126 << NameInfo.getName() << LookupContext << 0
8127 << SS.getRange());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008128
8129 // If we corrected to an inheriting constructor, handle it as one.
8130 auto *RD = dyn_cast<CXXRecordDecl>(ND);
8131 if (RD && RD->isInjectedClassName()) {
8132 // Fix up the information we'll use to build the using declaration.
8133 if (Corrected.WillReplaceSpecifier()) {
8134 NestedNameSpecifierLocBuilder Builder;
8135 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
8136 QualifierLoc.getSourceRange());
8137 QualifierLoc = Builder.getWithLocInContext(Context);
8138 }
8139
8140 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
8141 Context.getCanonicalType(Context.getRecordType(RD))));
8142 NameInfo.setNamedTypeInfo(nullptr);
8143
8144 // Build it and process it as an inheriting constructor.
8145 UsingDecl *UD = BuildValid();
8146 CheckInheritingConstructorUsingDecl(UD);
8147 return UD;
8148 }
8149
8150 // FIXME: Pick up all the declarations if we found an overloaded function.
8151 R.setLookupName(Corrected.getCorrection());
8152 R.addDecl(ND);
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00008153 } else {
Richard Smith2d670972013-08-17 00:46:16 +00008154 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00008155 << NameInfo.getName() << LookupContext << SS.getRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008156 return BuildInvalid();
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00008157 }
Douglas Gregor9cfbe482009-06-20 00:51:54 +00008158 }
8159
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008160 if (R.isAmbiguous())
8161 return BuildInvalid();
Mike Stump1eb44332009-09-09 15:08:12 +00008162
Enea Zaffanella8d030c72013-07-22 10:54:09 +00008163 if (HasTypenameKeyword) {
John McCall7ba107a2009-11-18 02:36:19 +00008164 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00008165 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00008166 Diag(IdentLoc, diag::err_using_typename_non_type);
8167 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8168 Diag((*I)->getUnderlyingDecl()->getLocation(),
8169 diag::note_using_decl_target);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008170 return BuildInvalid();
John McCall7ba107a2009-11-18 02:36:19 +00008171 }
8172 } else {
8173 // If we asked for a non-typename and we got a type, error out,
8174 // but only if this is an instantiation of an unresolved using
8175 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00008176 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00008177 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
8178 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008179 return BuildInvalid();
John McCall7ba107a2009-11-18 02:36:19 +00008180 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00008181 }
8182
Anders Carlsson73b39cf2009-08-28 03:35:18 +00008183 // C++0x N2914 [namespace.udecl]p6:
8184 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00008185 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00008186 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
8187 << SS.getRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008188 return BuildInvalid();
Anders Carlsson73b39cf2009-08-28 03:35:18 +00008189 }
Mike Stump1eb44332009-09-09 15:08:12 +00008190
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008191 UsingDecl *UD = BuildValid();
John McCall9f54ad42009-12-10 09:41:52 +00008192 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008193 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithf06a28932013-10-23 02:17:46 +00008194 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
8195 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall9f54ad42009-12-10 09:41:52 +00008196 }
John McCall9488ea12009-11-17 05:59:44 +00008197
8198 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00008199}
8200
Sebastian Redlf677ea32011-02-05 19:23:19 +00008201/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00008202bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00008203 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00008204
Douglas Gregordc355712011-02-25 00:36:19 +00008205 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008206 assert(SourceType &&
8207 "Using decl naming constructor doesn't have type in scope spec.");
8208 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
8209
8210 // Check whether the named type is a direct base class.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008211 bool AnyDependentBases = false;
8212 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
8213 AnyDependentBases);
8214 if (!Base && !AnyDependentBases) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00008215 Diag(UD->getUsingLoc(),
Sebastian Redlf677ea32011-02-05 19:23:19 +00008216 diag::err_using_decl_constructor_not_in_direct_base)
8217 << UD->getNameInfo().getSourceRange()
8218 << QualType(SourceType, 0) << TargetClass;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008219 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008220 return true;
8221 }
8222
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008223 if (Base)
8224 Base->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008225
8226 return false;
8227}
8228
John McCall9f54ad42009-12-10 09:41:52 +00008229/// Checks that the given using declaration is not an invalid
8230/// redeclaration. Note that this is checking only for the using decl
8231/// itself, not for any ill-formedness among the UsingShadowDecls.
8232bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00008233 bool HasTypenameKeyword,
John McCall9f54ad42009-12-10 09:41:52 +00008234 const CXXScopeSpec &SS,
8235 SourceLocation NameLoc,
8236 const LookupResult &Prev) {
8237 // C++03 [namespace.udecl]p8:
8238 // C++0x [namespace.udecl]p10:
8239 // A using-declaration is a declaration and can therefore be used
8240 // repeatedly where (and only where) multiple declarations are
8241 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00008242 //
John McCall8a726212010-11-29 18:01:58 +00008243 // That's in non-member contexts.
8244 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00008245 return false;
8246
Stephen Hines651f13c2014-04-23 16:59:28 -07008247 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall9f54ad42009-12-10 09:41:52 +00008248
8249 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
8250 NamedDecl *D = *I;
8251
8252 bool DTypename;
8253 NestedNameSpecifier *DQual;
8254 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00008255 DTypename = UD->hasTypename();
Douglas Gregordc355712011-02-25 00:36:19 +00008256 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00008257 } else if (UnresolvedUsingValueDecl *UD
8258 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
8259 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00008260 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00008261 } else if (UnresolvedUsingTypenameDecl *UD
8262 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
8263 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00008264 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00008265 } else continue;
8266
8267 // using decls differ if one says 'typename' and the other doesn't.
8268 // FIXME: non-dependent using decls?
Enea Zaffanella8d030c72013-07-22 10:54:09 +00008269 if (HasTypenameKeyword != DTypename) continue;
John McCall9f54ad42009-12-10 09:41:52 +00008270
8271 // using decls differ if they name different scopes (but note that
8272 // template instantiation can cause this check to trigger when it
8273 // didn't before instantiation).
8274 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
8275 Context.getCanonicalNestedNameSpecifier(DQual))
8276 continue;
8277
8278 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00008279 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00008280 return true;
8281 }
8282
8283 return false;
8284}
8285
John McCall604e7f12009-12-08 07:46:18 +00008286
John McCalled976492009-12-04 22:46:56 +00008287/// Checks that the given nested-name qualifier used in a using decl
8288/// in the current context is appropriately related to the current
8289/// scope. If an error is found, diagnoses it and returns true.
8290bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
8291 const CXXScopeSpec &SS,
Stephen Hines651f13c2014-04-23 16:59:28 -07008292 const DeclarationNameInfo &NameInfo,
John McCalled976492009-12-04 22:46:56 +00008293 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00008294 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00008295
John McCall604e7f12009-12-08 07:46:18 +00008296 if (!CurContext->isRecord()) {
8297 // C++03 [namespace.udecl]p3:
8298 // C++0x [namespace.udecl]p8:
8299 // A using-declaration for a class member shall be a member-declaration.
8300
8301 // If we weren't able to compute a valid scope, it must be a
8302 // dependent class scope.
8303 if (!NamedContext || NamedContext->isRecord()) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07008304 auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext);
Stephen Hines651f13c2014-04-23 16:59:28 -07008305 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008306 RD = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07008307
John McCall604e7f12009-12-08 07:46:18 +00008308 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
8309 << SS.getRange();
Stephen Hines651f13c2014-04-23 16:59:28 -07008310
8311 // If we have a complete, non-dependent source type, try to suggest a
8312 // way to get the same effect.
8313 if (!RD)
8314 return true;
8315
8316 // Find what this using-declaration was referring to.
8317 LookupResult R(*this, NameInfo, LookupOrdinaryName);
8318 R.setHideTags(false);
8319 R.suppressDiagnostics();
8320 LookupQualifiedName(R, RD);
8321
8322 if (R.getAsSingle<TypeDecl>()) {
8323 if (getLangOpts().CPlusPlus11) {
8324 // Convert 'using X::Y;' to 'using Y = X::Y;'.
8325 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
8326 << 0 // alias declaration
8327 << FixItHint::CreateInsertion(SS.getBeginLoc(),
8328 NameInfo.getName().getAsString() +
8329 " = ");
8330 } else {
8331 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
8332 SourceLocation InsertLoc =
8333 PP.getLocForEndOfToken(NameInfo.getLocEnd());
8334 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
8335 << 1 // typedef declaration
8336 << FixItHint::CreateReplacement(UsingLoc, "typedef")
8337 << FixItHint::CreateInsertion(
8338 InsertLoc, " " + NameInfo.getName().getAsString());
8339 }
8340 } else if (R.getAsSingle<VarDecl>()) {
8341 // Don't provide a fixit outside C++11 mode; we don't want to suggest
8342 // repeating the type of the static data member here.
8343 FixItHint FixIt;
8344 if (getLangOpts().CPlusPlus11) {
8345 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8346 FixIt = FixItHint::CreateReplacement(
8347 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
8348 }
8349
8350 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8351 << 2 // reference declaration
8352 << FixIt;
8353 }
John McCall604e7f12009-12-08 07:46:18 +00008354 return true;
8355 }
8356
8357 // Otherwise, everything is known to be fine.
8358 return false;
8359 }
8360
8361 // The current scope is a record.
8362
8363 // If the named context is dependent, we can't decide much.
8364 if (!NamedContext) {
8365 // FIXME: in C++0x, we can diagnose if we can prove that the
8366 // nested-name-specifier does not refer to a base class, which is
8367 // still possible in some cases.
8368
8369 // Otherwise we have to conservatively report that things might be
8370 // okay.
8371 return false;
8372 }
8373
8374 if (!NamedContext->isRecord()) {
8375 // Ideally this would point at the last name in the specifier,
8376 // but we don't have that level of source info.
8377 Diag(SS.getRange().getBegin(),
8378 diag::err_using_decl_nested_name_specifier_is_not_class)
Stephen Hines651f13c2014-04-23 16:59:28 -07008379 << SS.getScopeRep() << SS.getRange();
John McCall604e7f12009-12-08 07:46:18 +00008380 return true;
8381 }
8382
Douglas Gregor6fb07292010-12-21 07:41:49 +00008383 if (!NamedContext->isDependentContext() &&
8384 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8385 return true;
8386
Richard Smith80ad52f2013-01-02 11:42:31 +00008387 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00008388 // C++0x [namespace.udecl]p3:
8389 // In a using-declaration used as a member-declaration, the
8390 // nested-name-specifier shall name a base class of the class
8391 // being defined.
8392
8393 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8394 cast<CXXRecordDecl>(NamedContext))) {
8395 if (CurContext == NamedContext) {
8396 Diag(NameLoc,
8397 diag::err_using_decl_nested_name_specifier_is_current_class)
8398 << SS.getRange();
8399 return true;
8400 }
8401
8402 Diag(SS.getRange().getBegin(),
8403 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Stephen Hines651f13c2014-04-23 16:59:28 -07008404 << SS.getScopeRep()
John McCall604e7f12009-12-08 07:46:18 +00008405 << cast<CXXRecordDecl>(CurContext)
8406 << SS.getRange();
8407 return true;
8408 }
8409
8410 return false;
8411 }
8412
8413 // C++03 [namespace.udecl]p4:
8414 // A using-declaration used as a member-declaration shall refer
8415 // to a member of a base class of the class being defined [etc.].
8416
8417 // Salient point: SS doesn't have to name a base class as long as
8418 // lookup only finds members from base classes. Therefore we can
8419 // diagnose here only if we can prove that that can't happen,
8420 // i.e. if the class hierarchies provably don't intersect.
8421
8422 // TODO: it would be nice if "definitely valid" results were cached
8423 // in the UsingDecl and UsingShadowDecl so that these checks didn't
8424 // need to be repeated.
8425
8426 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00008427 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00008428
8429 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
8430 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8431 Data->Bases.insert(Base);
8432 return true;
8433 }
8434
8435 bool hasDependentBases(const CXXRecordDecl *Class) {
8436 return !Class->forallBases(collect, this);
8437 }
8438
8439 /// Returns true if the base is dependent or is one of the
8440 /// accumulated base classes.
8441 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
8442 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8443 return !Data->Bases.count(Base);
8444 }
8445
8446 bool mightShareBases(const CXXRecordDecl *Class) {
8447 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
8448 }
8449 };
8450
8451 UserData Data;
8452
8453 // Returns false if we find a dependent base.
8454 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
8455 return false;
8456
8457 // Returns false if the class has a dependent base or if it or one
8458 // of its bases is present in the base set of the current context.
8459 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
8460 return false;
8461
8462 Diag(SS.getRange().getBegin(),
8463 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Stephen Hines651f13c2014-04-23 16:59:28 -07008464 << SS.getScopeRep()
John McCall604e7f12009-12-08 07:46:18 +00008465 << cast<CXXRecordDecl>(CurContext)
8466 << SS.getRange();
8467
8468 return true;
John McCalled976492009-12-04 22:46:56 +00008469}
8470
Richard Smith162e1c12011-04-15 14:24:37 +00008471Decl *Sema::ActOnAliasDeclaration(Scope *S,
8472 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00008473 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00008474 SourceLocation UsingLoc,
8475 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00008476 AttributeList *AttrList,
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07008477 TypeResult Type,
8478 Decl *DeclFromDeclSpec) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00008479 // Skip up to the relevant declaration scope.
8480 while (S->getFlags() & Scope::TemplateParamScope)
8481 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00008482 assert((S->getFlags() & Scope::DeclScope) &&
8483 "got alias-declaration outside of declaration scope");
8484
8485 if (Type.isInvalid())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008486 return nullptr;
Richard Smith162e1c12011-04-15 14:24:37 +00008487
8488 bool Invalid = false;
8489 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008490 TypeSourceInfo *TInfo = nullptr;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00008491 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00008492
8493 if (DiagnoseClassNameShadow(CurContext, NameInfo))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008494 return nullptr;
Richard Smith162e1c12011-04-15 14:24:37 +00008495
8496 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00008497 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00008498 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00008499 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8500 TInfo->getTypeLoc().getBeginLoc());
8501 }
Richard Smith162e1c12011-04-15 14:24:37 +00008502
8503 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8504 LookupName(Previous, S);
8505
8506 // Warn about shadowing the name of a template parameter.
8507 if (Previous.isSingleResult() &&
8508 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00008509 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00008510 Previous.clear();
8511 }
8512
8513 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8514 "name in alias declaration must be an identifier");
8515 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8516 Name.StartLocation,
8517 Name.Identifier, TInfo);
8518
8519 NewTD->setAccess(AS);
8520
8521 if (Invalid)
8522 NewTD->setInvalidDecl();
8523
Richard Smith6b3d3e52013-02-20 19:22:51 +00008524 ProcessDeclAttributeList(S, NewTD, AttrList);
8525
Richard Smith3e4c6c42011-05-05 21:57:07 +00008526 CheckTypedefForVariablyModifiedType(S, NewTD);
8527 Invalid |= NewTD->isInvalidDecl();
8528
Richard Smith162e1c12011-04-15 14:24:37 +00008529 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00008530
8531 NamedDecl *NewND;
8532 if (TemplateParamLists.size()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008533 TypeAliasTemplateDecl *OldDecl = nullptr;
8534 TemplateParameterList *OldTemplateParams = nullptr;
Richard Smith3e4c6c42011-05-05 21:57:07 +00008535
8536 if (TemplateParamLists.size() != 1) {
8537 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008538 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8539 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00008540 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008541 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00008542
8543 // Only consider previous declarations in the same scope.
8544 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8545 /*ExplicitInstantiationOrSpecialization*/false);
8546 if (!Previous.empty()) {
8547 Redeclaration = true;
8548
8549 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8550 if (!OldDecl && !Invalid) {
8551 Diag(UsingLoc, diag::err_redefinition_different_kind)
8552 << Name.Identifier;
8553
8554 NamedDecl *OldD = Previous.getRepresentativeDecl();
8555 if (OldD->getLocation().isValid())
8556 Diag(OldD->getLocation(), diag::note_previous_definition);
8557
8558 Invalid = true;
8559 }
8560
8561 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8562 if (TemplateParameterListsAreEqual(TemplateParams,
8563 OldDecl->getTemplateParameters(),
8564 /*Complain=*/true,
8565 TPL_TemplateMatch))
8566 OldTemplateParams = OldDecl->getTemplateParameters();
8567 else
8568 Invalid = true;
8569
8570 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8571 if (!Invalid &&
8572 !Context.hasSameType(OldTD->getUnderlyingType(),
8573 NewTD->getUnderlyingType())) {
8574 // FIXME: The C++0x standard does not clearly say this is ill-formed,
8575 // but we can't reasonably accept it.
8576 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8577 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8578 if (OldTD->getLocation().isValid())
8579 Diag(OldTD->getLocation(), diag::note_previous_definition);
8580 Invalid = true;
8581 }
8582 }
8583 }
8584
8585 // Merge any previous default template arguments into our parameters,
8586 // and check the parameter list.
8587 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8588 TPC_TypeAliasTemplate))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008589 return nullptr;
Richard Smith3e4c6c42011-05-05 21:57:07 +00008590
8591 TypeAliasTemplateDecl *NewDecl =
8592 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8593 Name.Identifier, TemplateParams,
8594 NewTD);
Stephen Hines176edba2014-12-01 14:53:08 -08008595 NewTD->setDescribedAliasTemplate(NewDecl);
Richard Smith3e4c6c42011-05-05 21:57:07 +00008596
8597 NewDecl->setAccess(AS);
8598
8599 if (Invalid)
8600 NewDecl->setInvalidDecl();
8601 else if (OldDecl)
Rafael Espindolabc650912013-10-17 15:37:26 +00008602 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3e4c6c42011-05-05 21:57:07 +00008603
8604 NewND = NewDecl;
8605 } else {
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07008606 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
8607 setTagNameForLinkagePurposes(TD, NewTD);
8608 handleTagNumbering(TD, S);
8609 }
Richard Smith3e4c6c42011-05-05 21:57:07 +00008610 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8611 NewND = NewTD;
8612 }
Richard Smith162e1c12011-04-15 14:24:37 +00008613
8614 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00008615 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00008616
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00008617 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00008618 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00008619}
8620
Stephen Hines176edba2014-12-01 14:53:08 -08008621Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
8622 SourceLocation AliasLoc,
8623 IdentifierInfo *Alias, CXXScopeSpec &SS,
8624 SourceLocation IdentLoc,
8625 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00008626
Anders Carlsson81c85c42009-03-28 23:53:49 +00008627 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00008628 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8629 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00008630
John McCalla24dc2e2009-11-17 02:14:36 +00008631 if (R.isAmbiguous())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008632 return nullptr;
Mike Stump1eb44332009-09-09 15:08:12 +00008633
John McCallf36e02d2009-10-09 21:13:30 +00008634 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00008635 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00008636 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008637 return nullptr;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00008638 }
Anders Carlsson5721c682009-03-28 06:42:02 +00008639 }
Stephen Hines176edba2014-12-01 14:53:08 -08008640 assert(!R.isAmbiguous() && !R.empty());
8641
8642 // Check if we have a previous declaration with the same name.
8643 NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8644 ForRedeclaration);
8645 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
8646 PrevDecl = nullptr;
8647
8648 NamedDecl *ND = R.getFoundDecl();
8649
8650 if (PrevDecl) {
8651 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8652 // We already have an alias with the same name that points to the same
8653 // namespace; check that it matches.
8654 if (!AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
8655 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
8656 << Alias;
8657 Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias)
8658 << AD->getNamespace();
8659 return nullptr;
8660 }
8661 } else {
8662 unsigned DiagID = isa<NamespaceDecl>(PrevDecl)
8663 ? diag::err_redefinition
8664 : diag::err_redefinition_different_kind;
8665 Diag(AliasLoc, DiagID) << Alias;
8666 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8667 return nullptr;
8668 }
8669 }
8670
Stephen Hines0e2c34f2015-03-23 12:09:02 -07008671 // The use of a nested name specifier may trigger deprecation warnings.
Stephen Hines176edba2014-12-01 14:53:08 -08008672 DiagnoseUseOfDecl(ND, IdentLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00008673
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00008674 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00008675 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00008676 Alias, SS.getWithLocInContext(Context),
Stephen Hines176edba2014-12-01 14:53:08 -08008677 IdentLoc, ND);
8678 if (PrevDecl)
8679 AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl));
Mike Stump1eb44332009-09-09 15:08:12 +00008680
John McCall3dbd3d52010-02-16 06:53:13 +00008681 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00008682 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00008683}
8684
Sean Hunt001cad92011-05-10 00:49:42 +00008685Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008686Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8687 CXXMethodDecl *MD) {
8688 CXXRecordDecl *ClassDecl = MD->getParent();
8689
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008690 // C++ [except.spec]p14:
8691 // An implicitly declared special member function (Clause 12) shall have an
8692 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00008693 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008694 if (ClassDecl->isInvalidDecl())
8695 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008696
Sebastian Redl60618fa2011-03-12 11:50:43 +00008697 // Direct base-class constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07008698 for (const auto &B : ClassDecl->bases()) {
8699 if (B.isVirtual()) // Handled below.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008700 continue;
8701
Stephen Hines651f13c2014-04-23 16:59:28 -07008702 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor18274032010-07-03 00:47:00 +00008703 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00008704 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8705 // If this is a deleted function, add it anyway. This might be conformant
8706 // with the standard. This might not. I'm not sure. It might not matter.
8707 if (Constructor)
Stephen Hines651f13c2014-04-23 16:59:28 -07008708 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00008709 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008710 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008711
8712 // Virtual base-class constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07008713 for (const auto &B : ClassDecl->vbases()) {
8714 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor18274032010-07-03 00:47:00 +00008715 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00008716 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8717 // If this is a deleted function, add it anyway. This might be conformant
8718 // with the standard. This might not. I'm not sure. It might not matter.
8719 if (Constructor)
Stephen Hines651f13c2014-04-23 16:59:28 -07008720 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00008721 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008722 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008723
8724 // Field constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07008725 for (const auto *F : ClassDecl->fields()) {
Richard Smith7a614d82011-06-11 17:19:42 +00008726 if (F->hasInClassInitializer()) {
8727 if (Expr *E = F->getInClassInitializer())
8728 ExceptSpec.CalledExpr(E);
Richard Smith7a614d82011-06-11 17:19:42 +00008729 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00008730 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00008731 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8732 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8733 // If this is a deleted function, add it anyway. This might be conformant
8734 // with the standard. This might not. I'm not sure. It might not matter.
8735 // In particular, the problem is that this function never gets called. It
8736 // might just be ill-formed because this function attempts to refer to
8737 // a deleted function here.
8738 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00008739 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00008740 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008741 }
John McCalle23cf432010-12-14 08:05:40 +00008742
Sean Hunt001cad92011-05-10 00:49:42 +00008743 return ExceptSpec;
8744}
8745
Richard Smith07b0fdc2013-03-18 21:12:30 +00008746Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00008747Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8748 CXXRecordDecl *ClassDecl = CD->getParent();
8749
8750 // C++ [except.spec]p14:
8751 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00008752 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00008753 if (ClassDecl->isInvalidDecl())
8754 return ExceptSpec;
8755
8756 // Inherited constructor.
8757 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8758 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8759 // FIXME: Copying or moving the parameters could add extra exceptions to the
8760 // set, as could the default arguments for the inherited constructor. This
8761 // will be addressed when we implement the resolution of core issue 1351.
8762 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8763
8764 // Direct base-class constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07008765 for (const auto &B : ClassDecl->bases()) {
8766 if (B.isVirtual()) // Handled below.
Richard Smith0b0ca472013-04-10 06:11:48 +00008767 continue;
8768
Stephen Hines651f13c2014-04-23 16:59:28 -07008769 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smith0b0ca472013-04-10 06:11:48 +00008770 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8771 if (BaseClassDecl == InheritedDecl)
8772 continue;
8773 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8774 if (Constructor)
Stephen Hines651f13c2014-04-23 16:59:28 -07008775 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smith0b0ca472013-04-10 06:11:48 +00008776 }
8777 }
8778
8779 // Virtual base-class constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07008780 for (const auto &B : ClassDecl->vbases()) {
8781 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smith0b0ca472013-04-10 06:11:48 +00008782 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8783 if (BaseClassDecl == InheritedDecl)
8784 continue;
8785 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8786 if (Constructor)
Stephen Hines651f13c2014-04-23 16:59:28 -07008787 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smith0b0ca472013-04-10 06:11:48 +00008788 }
8789 }
8790
8791 // Field constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07008792 for (const auto *F : ClassDecl->fields()) {
Richard Smith0b0ca472013-04-10 06:11:48 +00008793 if (F->hasInClassInitializer()) {
8794 if (Expr *E = F->getInClassInitializer())
8795 ExceptSpec.CalledExpr(E);
Richard Smith0b0ca472013-04-10 06:11:48 +00008796 } else if (const RecordType *RecordTy
8797 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8798 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8799 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8800 if (Constructor)
8801 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8802 }
8803 }
8804
Richard Smith07b0fdc2013-03-18 21:12:30 +00008805 return ExceptSpec;
8806}
8807
Richard Smithafb49182012-11-29 01:34:07 +00008808namespace {
8809/// RAII object to register a special member as being currently declared.
8810struct DeclaringSpecialMember {
8811 Sema &S;
8812 Sema::SpecialMemberDecl D;
8813 bool WasAlreadyBeingDeclared;
8814
8815 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8816 : S(S), D(RD, CSM) {
Stephen Hines176edba2014-12-01 14:53:08 -08008817 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
Richard Smithafb49182012-11-29 01:34:07 +00008818 if (WasAlreadyBeingDeclared)
8819 // This almost never happens, but if it does, ensure that our cache
8820 // doesn't contain a stale result.
8821 S.SpecialMemberCache.clear();
8822
8823 // FIXME: Register a note to be produced if we encounter an error while
8824 // declaring the special member.
8825 }
8826 ~DeclaringSpecialMember() {
8827 if (!WasAlreadyBeingDeclared)
8828 S.SpecialMembersBeingDeclared.erase(D);
8829 }
8830
8831 /// \brief Are we already trying to declare this special member?
8832 bool isAlreadyBeingDeclared() const {
8833 return WasAlreadyBeingDeclared;
8834 }
8835};
8836}
8837
Sean Hunt001cad92011-05-10 00:49:42 +00008838CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8839 CXXRecordDecl *ClassDecl) {
8840 // C++ [class.ctor]p5:
8841 // A default constructor for a class X is a constructor of class X
8842 // that can be called without an argument. If there is no
8843 // user-declared constructor for class X, a default constructor is
8844 // implicitly declared. An implicitly-declared default constructor
8845 // is an inline public member of its class.
Stephen Hines176edba2014-12-01 14:53:08 -08008846 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00008847 "Should not build implicit default constructor!");
8848
Richard Smithafb49182012-11-29 01:34:07 +00008849 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8850 if (DSM.isAlreadyBeingDeclared())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008851 return nullptr;
Richard Smithafb49182012-11-29 01:34:07 +00008852
Richard Smith7756afa2012-06-10 05:43:50 +00008853 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8854 CXXDefaultConstructor,
8855 false);
8856
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008857 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00008858 CanQualType ClassType
8859 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008860 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00008861 DeclarationName Name
8862 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008863 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00008864 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008865 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8866 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8867 /*isImplicitlyDeclared=*/true, Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00008868 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00008869 DefaultCon->setDefaulted();
Stephen Hines176edba2014-12-01 14:53:08 -08008870
8871 if (getLangOpts().CUDA) {
8872 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
8873 DefaultCon,
8874 /* ConstRHS */ false,
8875 /* Diagnose */ false);
8876 }
Richard Smithb9d0b762012-07-27 04:22:15 +00008877
8878 // Build an exception specification pointing back at this constructor.
Reid Kleckneref072032013-08-27 23:08:25 +00008879 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko55431692013-05-05 00:41:58 +00008880 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008881
Richard Smithbc2a35d2012-12-08 08:32:28 +00008882 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8883 // constructors is easy to compute.
8884 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8885
8886 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008887 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008888
Douglas Gregor18274032010-07-03 00:47:00 +00008889 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00008890 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00008891
Douglas Gregor23c94db2010-07-02 17:43:08 +00008892 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00008893 PushOnScopeChains(DefaultCon, S, false);
8894 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00008895
Douglas Gregor32df23e2010-07-01 22:02:46 +00008896 return DefaultCon;
8897}
8898
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00008899void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8900 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00008901 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00008902 !Constructor->doesThisDeclarationHaveABody() &&
8903 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00008904 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008905
Anders Carlssonf6513ed2010-04-23 16:04:08 +00008906 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00008907 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00008908
Eli Friedman9a14db32012-10-18 20:14:08 +00008909 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008910 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00008911 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008912 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008913 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00008914 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00008915 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008916 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00008917 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008918
Stephen Hines176edba2014-12-01 14:53:08 -08008919 // The exception specification is needed because we are defining the
8920 // function.
8921 ResolveExceptionSpec(CurrentLocation,
8922 Constructor->getType()->castAs<FunctionProtoType>());
8923
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008924 SourceLocation Loc = Constructor->getLocEnd().isValid()
8925 ? Constructor->getLocEnd()
8926 : Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008927 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008928
Eli Friedman86164e82013-09-05 00:02:25 +00008929 Constructor->markUsed(Context);
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008930 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008931
8932 if (ASTMutationListener *L = getASTMutationListener()) {
8933 L->CompletedImplicitDefinition(Constructor);
8934 }
Richard Trieu858d2ba2013-10-25 00:56:00 +00008935
8936 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00008937}
8938
Richard Smith7a614d82011-06-11 17:19:42 +00008939void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Toker08235662013-10-18 05:54:19 +00008940 // Perform any delayed checks on exception specifications.
8941 CheckDelayedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00008942}
8943
Richard Smith4841ca52013-04-10 05:48:59 +00008944namespace {
8945/// Information on inheriting constructors to declare.
8946class InheritingConstructorInfo {
8947public:
8948 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8949 : SemaRef(SemaRef), Derived(Derived) {
8950 // Mark the constructors that we already have in the derived class.
8951 //
8952 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8953 // unless there is a user-declared constructor with the same signature in
8954 // the class where the using-declaration appears.
8955 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8956 }
8957
8958 void inheritAll(CXXRecordDecl *RD) {
8959 visitAll(RD, &InheritingConstructorInfo::inherit);
8960 }
8961
8962private:
8963 /// Information about an inheriting constructor.
8964 struct InheritingConstructor {
8965 InheritingConstructor()
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008966 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
Richard Smith4841ca52013-04-10 05:48:59 +00008967
8968 /// If \c true, a constructor with this signature is already declared
8969 /// in the derived class.
8970 bool DeclaredInDerived;
8971
8972 /// The constructor which is inherited.
8973 const CXXConstructorDecl *BaseCtor;
8974
8975 /// The derived constructor we declared.
8976 CXXConstructorDecl *DerivedCtor;
8977 };
8978
8979 /// Inheriting constructors with a given canonical type. There can be at
8980 /// most one such non-template constructor, and any number of templated
8981 /// constructors.
8982 struct InheritingConstructorsForType {
8983 InheritingConstructor NonTemplate;
Robert Wilhelme7205c02013-08-10 12:33:24 +00008984 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8985 Templates;
Richard Smith4841ca52013-04-10 05:48:59 +00008986
8987 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8988 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8989 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8990 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8991 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8992 false, S.TPL_TemplateMatch))
8993 return Templates[I].second;
8994 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8995 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008996 }
Richard Smith4841ca52013-04-10 05:48:59 +00008997
8998 return NonTemplate;
8999 }
9000 };
9001
9002 /// Get or create the inheriting constructor record for a constructor.
9003 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
9004 QualType CtorType) {
9005 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
9006 .getEntry(SemaRef, Ctor);
9007 }
9008
9009 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
9010
9011 /// Process all constructors for a class.
9012 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
Stephen Hines651f13c2014-04-23 16:59:28 -07009013 for (const auto *Ctor : RD->ctors())
9014 (this->*Callback)(Ctor);
Richard Smith4841ca52013-04-10 05:48:59 +00009015 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
9016 I(RD->decls_begin()), E(RD->decls_end());
9017 I != E; ++I) {
9018 const FunctionDecl *FD = (*I)->getTemplatedDecl();
9019 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
9020 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00009021 }
9022 }
Richard Smith4841ca52013-04-10 05:48:59 +00009023
9024 /// Note that a constructor (or constructor template) was declared in Derived.
9025 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
9026 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
9027 }
9028
9029 /// Inherit a single constructor.
9030 void inherit(const CXXConstructorDecl *Ctor) {
9031 const FunctionProtoType *CtorType =
9032 Ctor->getType()->castAs<FunctionProtoType>();
Stephen Hines176edba2014-12-01 14:53:08 -08009033 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
Richard Smith4841ca52013-04-10 05:48:59 +00009034 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
9035
9036 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
9037
9038 // Core issue (no number yet): the ellipsis is always discarded.
9039 if (EPI.Variadic) {
9040 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
9041 SemaRef.Diag(Ctor->getLocation(),
9042 diag::note_using_decl_constructor_ellipsis);
9043 EPI.Variadic = false;
9044 }
9045
9046 // Declare a constructor for each number of parameters.
9047 //
9048 // C++11 [class.inhctor]p1:
9049 // The candidate set of inherited constructors from the class X named in
9050 // the using-declaration consists of [... modulo defects ...] for each
9051 // constructor or constructor template of X, the set of constructors or
9052 // constructor templates that results from omitting any ellipsis parameter
9053 // specification and successively omitting parameters with a default
9054 // argument from the end of the parameter-type-list
Richard Smith987c0302013-04-17 19:00:52 +00009055 unsigned MinParams = minParamsToInherit(Ctor);
9056 unsigned Params = Ctor->getNumParams();
9057 if (Params >= MinParams) {
9058 do
9059 declareCtor(UsingLoc, Ctor,
9060 SemaRef.Context.getFunctionType(
Stephen Hines651f13c2014-04-23 16:59:28 -07009061 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
Richard Smith987c0302013-04-17 19:00:52 +00009062 while (Params > MinParams &&
9063 Ctor->getParamDecl(--Params)->hasDefaultArg());
9064 }
Richard Smith4841ca52013-04-10 05:48:59 +00009065 }
9066
9067 /// Find the using-declaration which specified that we should inherit the
9068 /// constructors of \p Base.
9069 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
9070 // No fancy lookup required; just look for the base constructor name
9071 // directly within the derived class.
9072 ASTContext &Context = SemaRef.Context;
9073 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9074 Context.getCanonicalType(Context.getRecordType(Base)));
Stephen Hines0e2c34f2015-03-23 12:09:02 -07009075 DeclContext::lookup_result Decls = Derived->lookup(Name);
Richard Smith4841ca52013-04-10 05:48:59 +00009076 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
9077 }
9078
9079 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
9080 // C++11 [class.inhctor]p3:
9081 // [F]or each constructor template in the candidate set of inherited
9082 // constructors, a constructor template is implicitly declared
9083 if (Ctor->getDescribedFunctionTemplate())
9084 return 0;
9085
9086 // For each non-template constructor in the candidate set of inherited
9087 // constructors other than a constructor having no parameters or a
9088 // copy/move constructor having a single parameter, a constructor is
9089 // implicitly declared [...]
9090 if (Ctor->getNumParams() == 0)
9091 return 1;
9092 if (Ctor->isCopyOrMoveConstructor())
9093 return 2;
9094
9095 // Per discussion on core reflector, never inherit a constructor which
9096 // would become a default, copy, or move constructor of Derived either.
9097 const ParmVarDecl *PD = Ctor->getParamDecl(0);
9098 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
9099 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
9100 }
9101
9102 /// Declare a single inheriting constructor, inheriting the specified
9103 /// constructor, with the given type.
9104 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
9105 QualType DerivedType) {
9106 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
9107
9108 // C++11 [class.inhctor]p3:
9109 // ... a constructor is implicitly declared with the same constructor
9110 // characteristics unless there is a user-declared constructor with
9111 // the same signature in the class where the using-declaration appears
9112 if (Entry.DeclaredInDerived)
9113 return;
9114
9115 // C++11 [class.inhctor]p7:
9116 // If two using-declarations declare inheriting constructors with the
9117 // same signature, the program is ill-formed
9118 if (Entry.DerivedCtor) {
9119 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
9120 // Only diagnose this once per constructor.
9121 if (Entry.DerivedCtor->isInvalidDecl())
9122 return;
9123 Entry.DerivedCtor->setInvalidDecl();
9124
9125 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
9126 SemaRef.Diag(BaseCtor->getLocation(),
9127 diag::note_using_decl_constructor_conflict_current_ctor);
9128 SemaRef.Diag(Entry.BaseCtor->getLocation(),
9129 diag::note_using_decl_constructor_conflict_previous_ctor);
9130 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
9131 diag::note_using_decl_constructor_conflict_previous_using);
9132 } else {
9133 // Core issue (no number): if the same inheriting constructor is
9134 // produced by multiple base class constructors from the same base
9135 // class, the inheriting constructor is defined as deleted.
9136 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
9137 }
9138
9139 return;
9140 }
9141
9142 ASTContext &Context = SemaRef.Context;
9143 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9144 Context.getCanonicalType(Context.getRecordType(Derived)));
9145 DeclarationNameInfo NameInfo(Name, UsingLoc);
9146
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009147 TemplateParameterList *TemplateParams = nullptr;
Richard Smith4841ca52013-04-10 05:48:59 +00009148 if (const FunctionTemplateDecl *FTD =
9149 BaseCtor->getDescribedFunctionTemplate()) {
9150 TemplateParams = FTD->getTemplateParameters();
9151 // We're reusing template parameters from a different DeclContext. This
9152 // is questionable at best, but works out because the template depth in
9153 // both places is guaranteed to be 0.
9154 // FIXME: Rebuild the template parameters in the new context, and
9155 // transform the function type to refer to them.
9156 }
9157
9158 // Build type source info pointing at the using-declaration. This is
9159 // required by template instantiation.
9160 TypeSourceInfo *TInfo =
9161 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
9162 FunctionProtoTypeLoc ProtoLoc =
9163 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
9164
9165 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
9166 Context, Derived, UsingLoc, NameInfo, DerivedType,
9167 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
9168 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
9169
9170 // Build an unevaluated exception specification for this constructor.
9171 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
9172 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Stephen Hines176edba2014-12-01 14:53:08 -08009173 EPI.ExceptionSpec.Type = EST_Unevaluated;
9174 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
Stephen Hines651f13c2014-04-23 16:59:28 -07009175 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
9176 FPT->getParamTypes(), EPI));
Richard Smith4841ca52013-04-10 05:48:59 +00009177
9178 // Build the parameter declarations.
9179 SmallVector<ParmVarDecl *, 16> ParamDecls;
Stephen Hines651f13c2014-04-23 16:59:28 -07009180 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith4841ca52013-04-10 05:48:59 +00009181 TypeSourceInfo *TInfo =
Stephen Hines651f13c2014-04-23 16:59:28 -07009182 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
Richard Smith4841ca52013-04-10 05:48:59 +00009183 ParmVarDecl *PD = ParmVarDecl::Create(
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009184 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
9185 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
Richard Smith4841ca52013-04-10 05:48:59 +00009186 PD->setScopeInfo(0, I);
9187 PD->setImplicit();
9188 ParamDecls.push_back(PD);
Stephen Hines651f13c2014-04-23 16:59:28 -07009189 ProtoLoc.setParam(I, PD);
Richard Smith4841ca52013-04-10 05:48:59 +00009190 }
9191
9192 // Set up the new constructor.
9193 DerivedCtor->setAccess(BaseCtor->getAccess());
9194 DerivedCtor->setParams(ParamDecls);
9195 DerivedCtor->setInheritedConstructor(BaseCtor);
9196 if (BaseCtor->isDeleted())
9197 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
9198
9199 // If this is a constructor template, build the template declaration.
9200 if (TemplateParams) {
9201 FunctionTemplateDecl *DerivedTemplate =
9202 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
9203 TemplateParams, DerivedCtor);
9204 DerivedTemplate->setAccess(BaseCtor->getAccess());
9205 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
9206 Derived->addDecl(DerivedTemplate);
9207 } else {
9208 Derived->addDecl(DerivedCtor);
9209 }
9210
9211 Entry.BaseCtor = BaseCtor;
9212 Entry.DerivedCtor = DerivedCtor;
9213 }
9214
9215 Sema &SemaRef;
9216 CXXRecordDecl *Derived;
9217 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
9218 MapType Map;
9219};
9220}
9221
9222void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
9223 // Defer declaring the inheriting constructors until the class is
9224 // instantiated.
9225 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00009226 return;
9227
Richard Smith4841ca52013-04-10 05:48:59 +00009228 // Find base classes from which we might inherit constructors.
9229 SmallVector<CXXRecordDecl*, 4> InheritedBases;
Stephen Hines651f13c2014-04-23 16:59:28 -07009230 for (const auto &BaseIt : ClassDecl->bases())
9231 if (BaseIt.getInheritConstructors())
9232 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00009233
Richard Smith4841ca52013-04-10 05:48:59 +00009234 // Go no further if we're not inheriting any constructors.
9235 if (InheritedBases.empty())
9236 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00009237
Richard Smith4841ca52013-04-10 05:48:59 +00009238 // Declare the inherited constructors.
9239 InheritingConstructorInfo ICI(*this, ClassDecl);
9240 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
9241 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00009242}
9243
Richard Smith07b0fdc2013-03-18 21:12:30 +00009244void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
9245 CXXConstructorDecl *Constructor) {
9246 CXXRecordDecl *ClassDecl = Constructor->getParent();
9247 assert(Constructor->getInheritedConstructor() &&
9248 !Constructor->doesThisDeclarationHaveABody() &&
9249 !Constructor->isDeleted());
9250
9251 SynthesizedFunctionScope Scope(*this, Constructor);
9252 DiagnosticErrorTrap Trap(Diags);
9253 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9254 Trap.hasErrorOccurred()) {
9255 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
9256 << Context.getTagDeclType(ClassDecl);
9257 Constructor->setInvalidDecl();
9258 return;
9259 }
9260
9261 SourceLocation Loc = Constructor->getLocation();
9262 Constructor->setBody(new (Context) CompoundStmt(Loc));
9263
Eli Friedman86164e82013-09-05 00:02:25 +00009264 Constructor->markUsed(Context);
Richard Smith07b0fdc2013-03-18 21:12:30 +00009265 MarkVTableUsed(CurrentLocation, ClassDecl);
9266
9267 if (ASTMutationListener *L = getASTMutationListener()) {
9268 L->CompletedImplicitDefinition(Constructor);
9269 }
9270}
9271
9272
Sean Huntcb45a0f2011-05-12 22:46:25 +00009273Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009274Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
9275 CXXRecordDecl *ClassDecl = MD->getParent();
9276
Douglas Gregorfabd43a2010-07-01 19:09:28 +00009277 // C++ [except.spec]p14:
9278 // An implicitly declared special member function (Clause 12) shall have
9279 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00009280 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00009281 if (ClassDecl->isInvalidDecl())
9282 return ExceptSpec;
9283
Douglas Gregorfabd43a2010-07-01 19:09:28 +00009284 // Direct base-class destructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07009285 for (const auto &B : ClassDecl->bases()) {
9286 if (B.isVirtual()) // Handled below.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00009287 continue;
9288
Stephen Hines651f13c2014-04-23 16:59:28 -07009289 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9290 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00009291 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00009292 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00009293
Douglas Gregorfabd43a2010-07-01 19:09:28 +00009294 // Virtual base-class destructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07009295 for (const auto &B : ClassDecl->vbases()) {
9296 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9297 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00009298 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00009299 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00009300
Douglas Gregorfabd43a2010-07-01 19:09:28 +00009301 // Field destructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07009302 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00009303 if (const RecordType *RecordTy
9304 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00009305 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00009306 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00009307 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009308
Sean Huntcb45a0f2011-05-12 22:46:25 +00009309 return ExceptSpec;
9310}
9311
9312CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
9313 // C++ [class.dtor]p2:
9314 // If a class has no user-declared destructor, a destructor is
9315 // declared implicitly. An implicitly-declared destructor is an
9316 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00009317 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00009318
Richard Smithafb49182012-11-29 01:34:07 +00009319 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
9320 if (DSM.isAlreadyBeingDeclared())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009321 return nullptr;
Richard Smithafb49182012-11-29 01:34:07 +00009322
Douglas Gregor4923aa22010-07-02 20:37:36 +00009323 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00009324 CanQualType ClassType
9325 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009326 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00009327 DeclarationName Name
9328 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009329 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00009330 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00009331 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009332 QualType(), nullptr, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00009333 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00009334 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00009335 Destructor->setDefaulted();
Stephen Hines176edba2014-12-01 14:53:08 -08009336
9337 if (getLangOpts().CUDA) {
9338 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
9339 Destructor,
9340 /* ConstRHS */ false,
9341 /* Diagnose */ false);
9342 }
Richard Smithb9d0b762012-07-27 04:22:15 +00009343
9344 // Build an exception specification pointing back at this destructor.
Reid Kleckneref072032013-08-27 23:08:25 +00009345 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko55431692013-05-05 00:41:58 +00009346 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009347
Richard Smithbc2a35d2012-12-08 08:32:28 +00009348 AddOverriddenMethods(ClassDecl, Destructor);
9349
9350 // We don't need to use SpecialMemberIsTrivial here; triviality for
9351 // destructors is easy to compute.
9352 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
9353
9354 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009355 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00009356
Douglas Gregor4923aa22010-07-02 20:37:36 +00009357 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00009358 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00009359
Douglas Gregor4923aa22010-07-02 20:37:36 +00009360 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00009361 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00009362 PushOnScopeChains(Destructor, S, false);
9363 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00009364
Douglas Gregorfabd43a2010-07-01 19:09:28 +00009365 return Destructor;
9366}
9367
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009368void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00009369 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00009370 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00009371 !Destructor->doesThisDeclarationHaveABody() &&
9372 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009373 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00009374 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009375 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009376
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009377 if (Destructor->isInvalidDecl())
9378 return;
9379
Eli Friedman9a14db32012-10-18 20:14:08 +00009380 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009381
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009382 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00009383 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9384 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00009385
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009386 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00009387 Diag(CurrentLocation, diag::note_member_synthesized_at)
9388 << CXXDestructor << Context.getTagDeclType(ClassDecl);
9389
9390 Destructor->setInvalidDecl();
9391 return;
9392 }
9393
Stephen Hines176edba2014-12-01 14:53:08 -08009394 // The exception specification is needed because we are defining the
9395 // function.
9396 ResolveExceptionSpec(CurrentLocation,
9397 Destructor->getType()->castAs<FunctionProtoType>());
9398
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009399 SourceLocation Loc = Destructor->getLocEnd().isValid()
9400 ? Destructor->getLocEnd()
9401 : Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00009402 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman86164e82013-09-05 00:02:25 +00009403 Destructor->markUsed(Context);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009404 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009405
9406 if (ASTMutationListener *L = getASTMutationListener()) {
9407 L->CompletedImplicitDefinition(Destructor);
9408 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009409}
9410
Richard Smitha4156b82012-04-21 18:42:51 +00009411/// \brief Perform any semantic analysis which needs to be delayed until all
9412/// pending class member declarations have been parsed.
9413void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00009414 // If the context is an invalid C++ class, just suppress these checks.
9415 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9416 if (Record->isInvalidDecl()) {
Alp Toker08235662013-10-18 05:54:19 +00009417 DelayedDefaultedMemberExceptionSpecs.clear();
Stephen Hines0e2c34f2015-03-23 12:09:02 -07009418 DelayedExceptionSpecChecks.clear();
Douglas Gregor10318842013-02-01 04:49:10 +00009419 return;
9420 }
9421 }
Richard Smitha4156b82012-04-21 18:42:51 +00009422}
9423
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07009424static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) {
9425 // Don't do anything for template patterns.
9426 if (Class->getDescribedClassTemplate())
9427 return;
9428
9429 for (Decl *Member : Class->decls()) {
9430 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
9431 if (!CD) {
9432 // Recurse on nested classes.
9433 if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member))
9434 getDefaultArgExprsForConstructors(S, NestedRD);
9435 continue;
9436 } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) {
9437 continue;
9438 }
9439
9440 for (unsigned I = 0, E = CD->getNumParams(); I != E; ++I) {
9441 // Skip any default arguments that we've already instantiated.
9442 if (S.Context.getDefaultArgExprForConstructor(CD, I))
9443 continue;
9444
9445 Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD,
9446 CD->getParamDecl(I)).get();
9447 S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
9448 }
9449 }
9450}
9451
9452void Sema::ActOnFinishCXXMemberDefaultArgs(Decl *D) {
9453 auto *RD = dyn_cast<CXXRecordDecl>(D);
9454
9455 // Default constructors that are annotated with __declspec(dllexport) which
9456 // have default arguments or don't use the standard calling convention are
9457 // wrapped with a thunk called the default constructor closure.
9458 if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft())
9459 getDefaultArgExprsForConstructors(*this, RD);
9460}
9461
Richard Smithb9d0b762012-07-27 04:22:15 +00009462void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9463 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00009464 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00009465 "adjusting dtor exception specs was introduced in c++11");
9466
Sebastian Redl0ee33912011-05-19 05:13:44 +00009467 // C++11 [class.dtor]p3:
9468 // A declaration of a destructor that does not have an exception-
9469 // specification is implicitly considered to have the same exception-
9470 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00009471 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00009472 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00009473 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00009474 return;
9475
Chandler Carruth3f224b22011-09-20 04:55:26 +00009476 // Replace the destructor's type, building off the existing one. Fortunately,
9477 // the only thing of interest in the destructor type is its extended info.
9478 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00009479 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
Stephen Hines176edba2014-12-01 14:53:08 -08009480 EPI.ExceptionSpec.Type = EST_Unevaluated;
9481 EPI.ExceptionSpec.SourceDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00009482 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00009483
Sebastian Redl0ee33912011-05-19 05:13:44 +00009484 // FIXME: If the destructor has a body that could throw, and the newly created
9485 // spec doesn't allow exceptions, we should emit a warning, because this
9486 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00009487 // However, we don't have a body or an exception specification yet, so it
9488 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00009489}
9490
Pavel Labath66ea35d2013-08-30 08:52:28 +00009491namespace {
9492/// \brief An abstract base class for all helper classes used in building the
9493// copy/move operators. These classes serve as factory functions and help us
9494// avoid using the same Expr* in the AST twice.
9495class ExprBuilder {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07009496 ExprBuilder(const ExprBuilder&) = delete;
9497 ExprBuilder &operator=(const ExprBuilder&) = delete;
Pavel Labath66ea35d2013-08-30 08:52:28 +00009498
9499protected:
9500 static Expr *assertNotNull(Expr *E) {
9501 assert(E && "Expression construction must not fail.");
9502 return E;
9503 }
9504
9505public:
9506 ExprBuilder() {}
9507 virtual ~ExprBuilder() {}
9508
9509 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9510};
9511
9512class RefBuilder: public ExprBuilder {
9513 VarDecl *Var;
9514 QualType VarType;
9515
9516public:
Stephen Hines176edba2014-12-01 14:53:08 -08009517 Expr *build(Sema &S, SourceLocation Loc) const override {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009518 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
Pavel Labath66ea35d2013-08-30 08:52:28 +00009519 }
9520
9521 RefBuilder(VarDecl *Var, QualType VarType)
9522 : Var(Var), VarType(VarType) {}
9523};
9524
9525class ThisBuilder: public ExprBuilder {
9526public:
Stephen Hines176edba2014-12-01 14:53:08 -08009527 Expr *build(Sema &S, SourceLocation Loc) const override {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009528 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
Pavel Labath66ea35d2013-08-30 08:52:28 +00009529 }
9530};
9531
9532class CastBuilder: public ExprBuilder {
9533 const ExprBuilder &Builder;
9534 QualType Type;
9535 ExprValueKind Kind;
9536 const CXXCastPath &Path;
9537
9538public:
Stephen Hines176edba2014-12-01 14:53:08 -08009539 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath66ea35d2013-08-30 08:52:28 +00009540 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9541 CK_UncheckedDerivedToBase, Kind,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009542 &Path).get());
Pavel Labath66ea35d2013-08-30 08:52:28 +00009543 }
9544
9545 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9546 const CXXCastPath &Path)
9547 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9548};
9549
9550class DerefBuilder: public ExprBuilder {
9551 const ExprBuilder &Builder;
9552
9553public:
Stephen Hines176edba2014-12-01 14:53:08 -08009554 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath66ea35d2013-08-30 08:52:28 +00009555 return assertNotNull(
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009556 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
Pavel Labath66ea35d2013-08-30 08:52:28 +00009557 }
9558
9559 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9560};
9561
9562class MemberBuilder: public ExprBuilder {
9563 const ExprBuilder &Builder;
9564 QualType Type;
9565 CXXScopeSpec SS;
9566 bool IsArrow;
9567 LookupResult &MemberLookup;
9568
9569public:
Stephen Hines176edba2014-12-01 14:53:08 -08009570 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath66ea35d2013-08-30 08:52:28 +00009571 return assertNotNull(S.BuildMemberReferenceExpr(
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009572 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009573 nullptr, MemberLookup, nullptr).get());
Pavel Labath66ea35d2013-08-30 08:52:28 +00009574 }
9575
9576 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9577 LookupResult &MemberLookup)
9578 : Builder(Builder), Type(Type), IsArrow(IsArrow),
9579 MemberLookup(MemberLookup) {}
9580};
9581
9582class MoveCastBuilder: public ExprBuilder {
9583 const ExprBuilder &Builder;
9584
9585public:
Stephen Hines176edba2014-12-01 14:53:08 -08009586 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath66ea35d2013-08-30 08:52:28 +00009587 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9588 }
9589
9590 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9591};
9592
9593class LvalueConvBuilder: public ExprBuilder {
9594 const ExprBuilder &Builder;
9595
9596public:
Stephen Hines176edba2014-12-01 14:53:08 -08009597 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath66ea35d2013-08-30 08:52:28 +00009598 return assertNotNull(
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009599 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
Pavel Labath66ea35d2013-08-30 08:52:28 +00009600 }
9601
9602 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9603};
9604
9605class SubscriptBuilder: public ExprBuilder {
9606 const ExprBuilder &Base;
9607 const ExprBuilder &Index;
9608
9609public:
Stephen Hines176edba2014-12-01 14:53:08 -08009610 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath66ea35d2013-08-30 08:52:28 +00009611 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009612 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
Pavel Labath66ea35d2013-08-30 08:52:28 +00009613 }
9614
9615 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9616 : Base(Base), Index(Index) {}
9617};
9618
9619} // end anonymous namespace
9620
Richard Smith8c889532012-11-14 00:50:40 +00009621/// When generating a defaulted copy or move assignment operator, if a field
9622/// should be copied with __builtin_memcpy rather than via explicit assignments,
9623/// do so. This optimization only applies for arrays of scalars, and for arrays
9624/// of class type where the selected copy/move-assignment operator is trivial.
9625static StmtResult
9626buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009627 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith8c889532012-11-14 00:50:40 +00009628 // Compute the size of the memory buffer to be copied.
9629 QualType SizeType = S.Context.getSizeType();
9630 llvm::APInt Size(S.Context.getTypeSize(SizeType),
9631 S.Context.getTypeSizeInChars(T).getQuantity());
9632
9633 // Take the address of the field references for "from" and "to". We
9634 // directly construct UnaryOperators here because semantic analysis
9635 // does not permit us to take the address of an xvalue.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009636 Expr *From = FromB.build(S, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00009637 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9638 S.Context.getPointerType(From->getType()),
9639 VK_RValue, OK_Ordinary, Loc);
Pavel Labath66ea35d2013-08-30 08:52:28 +00009640 Expr *To = ToB.build(S, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00009641 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9642 S.Context.getPointerType(To->getType()),
9643 VK_RValue, OK_Ordinary, Loc);
9644
9645 const Type *E = T->getBaseElementTypeUnsafe();
9646 bool NeedsCollectableMemCpy =
9647 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9648
9649 // Create a reference to the __builtin_objc_memmove_collectable function
9650 StringRef MemCpyName = NeedsCollectableMemCpy ?
9651 "__builtin_objc_memmove_collectable" :
9652 "__builtin_memcpy";
9653 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9654 Sema::LookupOrdinaryName);
9655 S.LookupName(R, S.TUScope, true);
9656
9657 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9658 if (!MemCpy)
9659 // Something went horribly wrong earlier, and we will have complained
9660 // about it.
9661 return StmtError();
9662
9663 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009664 VK_RValue, Loc, nullptr);
Richard Smith8c889532012-11-14 00:50:40 +00009665 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9666
9667 Expr *CallArgs[] = {
9668 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9669 };
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009670 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
Richard Smith8c889532012-11-14 00:50:40 +00009671 Loc, CallArgs, Loc);
9672
9673 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009674 return Call.getAs<Stmt>();
Richard Smith8c889532012-11-14 00:50:40 +00009675}
9676
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009677/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00009678/// \c To.
9679///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009680/// This routine is used to copy/move the members of a class with an
9681/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00009682/// copied are arrays, this routine builds for loops to copy them.
9683///
9684/// \param S The Sema object used for type-checking.
9685///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009686/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00009687///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009688/// \param T The type of the expressions being copied/moved. Both expressions
9689/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00009690///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009691/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00009692///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009693/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00009694///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009695/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00009696/// Otherwise, it's a non-static member subobject.
9697///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009698/// \param Copying Whether we're copying or moving.
9699///
Douglas Gregor06a9f362010-05-01 20:49:11 +00009700/// \param Depth Internal parameter recording the depth of the recursion.
9701///
Richard Smith8c889532012-11-14 00:50:40 +00009702/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9703/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00009704static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00009705buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009706 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith8c889532012-11-14 00:50:40 +00009707 bool CopyingBaseSubobject, bool Copying,
9708 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00009709 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00009710 // Each subobject is assigned in the manner appropriate to its type:
9711 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009712 // - if the subobject is of class type, as if by a call to operator= with
9713 // the subobject as the object expression and the corresponding
9714 // subobject of x as a single function argument (as if by explicit
9715 // qualification; that is, ignoring any possible virtual overriding
9716 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00009717 //
9718 // C++03 [class.copy]p13:
9719 // - if the subobject is of class type, the copy assignment operator for
9720 // the class is used (as if by explicit qualification; that is,
9721 // ignoring any possible virtual overriding functions in more derived
9722 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009723 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9724 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00009725
Douglas Gregor06a9f362010-05-01 20:49:11 +00009726 // Look for operator=.
9727 DeclarationName Name
9728 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9729 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9730 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009731
Richard Smith044c8aa2012-11-13 00:54:12 +00009732 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9733 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00009734 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00009735 LookupResult::Filter F = OpLookup.makeFilter();
9736 while (F.hasNext()) {
9737 NamedDecl *D = F.next();
9738 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9739 if (Method->isCopyAssignmentOperator() ||
9740 (!Copying && Method->isMoveAssignmentOperator()))
9741 continue;
9742
9743 F.erase();
9744 }
9745 F.done();
John McCallb0207482010-03-16 06:11:48 +00009746 }
Richard Smith044c8aa2012-11-13 00:54:12 +00009747
Douglas Gregor6cdc1612010-05-04 15:20:55 +00009748 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00009749 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00009750 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00009751 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00009752 // ambiguities), we need to cast "this" to that subobject type; to
9753 // ensure that we don't go through the virtual call mechanism, we need
9754 // to qualify the operator= name with the base class (see below). However,
9755 // this means that if the base class has a protected copy assignment
9756 // operator, the protected member access check will fail. So, we
9757 // rewrite "protected" access to "public" access in this case, since we
9758 // know by construction that we're calling from a derived class.
9759 if (CopyingBaseSubobject) {
9760 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9761 L != LEnd; ++L) {
9762 if (L.getAccess() == AS_protected)
9763 L.setAccess(AS_public);
9764 }
9765 }
Richard Smith044c8aa2012-11-13 00:54:12 +00009766
Douglas Gregor06a9f362010-05-01 20:49:11 +00009767 // Create the nested-name-specifier that will be used to qualify the
9768 // reference to operator=; this is required to suppress the virtual
9769 // call mechanism.
9770 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00009771 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00009772 SS.MakeTrivial(S.Context,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009773 NestedNameSpecifier::Create(S.Context, nullptr, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00009774 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00009775 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00009776
Douglas Gregor06a9f362010-05-01 20:49:11 +00009777 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00009778 ExprResult OpEqualRef
Pavel Labath66ea35d2013-08-30 08:52:28 +00009779 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9780 SS, /*TemplateKWLoc=*/SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009781 /*FirstQualifierInScope=*/nullptr,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009782 OpLookup,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009783 /*TemplateArgs=*/nullptr,
Douglas Gregor06a9f362010-05-01 20:49:11 +00009784 /*SuppressQualifierCheck=*/true);
9785 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009786 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00009787
Douglas Gregor06a9f362010-05-01 20:49:11 +00009788 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00009789
Pavel Labath66ea35d2013-08-30 08:52:28 +00009790 Expr *FromInst = From.build(S, Loc);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009791 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009792 OpEqualRef.getAs<Expr>(),
Pavel Labath66ea35d2013-08-30 08:52:28 +00009793 Loc, FromInst, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009794 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009795 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00009796
Richard Smith8c889532012-11-14 00:50:40 +00009797 // If we built a call to a trivial 'operator=' while copying an array,
9798 // bail out. We'll replace the whole shebang with a memcpy.
9799 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9800 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009801 return StmtResult((Stmt*)nullptr);
Richard Smith8c889532012-11-14 00:50:40 +00009802
Richard Smith044c8aa2012-11-13 00:54:12 +00009803 // Convert to an expression-statement, and clean up any produced
9804 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00009805 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009806 }
John McCallb0207482010-03-16 06:11:48 +00009807
Richard Smith044c8aa2012-11-13 00:54:12 +00009808 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00009809 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00009810 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009811 if (!ArrayTy) {
Pavel Labath66ea35d2013-08-30 08:52:28 +00009812 ExprResult Assignment = S.CreateBuiltinBinOp(
9813 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00009814 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009815 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00009816 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009817 }
Richard Smith044c8aa2012-11-13 00:54:12 +00009818
9819 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00009820 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00009821
Douglas Gregor06a9f362010-05-01 20:49:11 +00009822 // Construct a loop over the array bounds, e.g.,
9823 //
9824 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9825 //
9826 // that will copy each of the array elements.
9827 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00009828
Douglas Gregor06a9f362010-05-01 20:49:11 +00009829 // Create the iteration variable.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009830 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009831 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00009832 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009833 llvm::raw_svector_ostream OS(Str);
9834 OS << "__i" << Depth;
9835 IterationVarName = &S.Context.Idents.get(OS.str());
9836 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009837 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00009838 IterationVarName, SizeType,
9839 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009840 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00009841
Douglas Gregor06a9f362010-05-01 20:49:11 +00009842 // Initialize the iteration variable to zero.
9843 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00009844 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00009845
Pavel Labath66ea35d2013-08-30 08:52:28 +00009846 // Creates a reference to the iteration variable.
9847 RefBuilder IterationVarRef(IterationVar, SizeType);
9848 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman8c382062012-01-23 02:35:22 +00009849
Douglas Gregor06a9f362010-05-01 20:49:11 +00009850 // Create the DeclStmt that holds the iteration variable.
9851 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00009852
Douglas Gregor06a9f362010-05-01 20:49:11 +00009853 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009854 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9855 MoveCastBuilder FromIndexMove(FromIndexCopy);
9856 const ExprBuilder *FromIndex;
9857 if (Copying)
9858 FromIndex = &FromIndexCopy;
9859 else
9860 FromIndex = &FromIndexMove;
9861
9862 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009863
9864 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00009865 StmtResult Copy =
9866 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath66ea35d2013-08-30 08:52:28 +00009867 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith8c889532012-11-14 00:50:40 +00009868 Copying, Depth + 1);
9869 // Bail out if copying fails or if we determined that we should use memcpy.
9870 if (Copy.isInvalid() || !Copy.get())
9871 return Copy;
9872
9873 // Create the comparison against the array bound.
9874 llvm::APInt Upper
9875 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9876 Expr *Comparison
Pavel Labath66ea35d2013-08-30 08:52:28 +00009877 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith8c889532012-11-14 00:50:40 +00009878 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9879 BO_NE, S.Context.BoolTy,
9880 VK_RValue, OK_Ordinary, Loc, false);
9881
9882 // Create the pre-increment of the iteration variable.
9883 Expr *Increment
Pavel Labath66ea35d2013-08-30 08:52:28 +00009884 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9885 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00009886
Douglas Gregor06a9f362010-05-01 20:49:11 +00009887 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00009888 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00009889 S.MakeFullExpr(Comparison),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009890 nullptr, S.MakeFullDiscardedValueExpr(Increment),
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009891 Loc, Copy.get());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009892}
9893
Richard Smith8c889532012-11-14 00:50:40 +00009894static StmtResult
9895buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009896 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith8c889532012-11-14 00:50:40 +00009897 bool CopyingBaseSubobject, bool Copying) {
9898 // Maybe we should use a memcpy?
9899 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9900 T.isTriviallyCopyableType(S.Context))
9901 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9902
9903 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9904 CopyingBaseSubobject,
9905 Copying, 0));
9906
9907 // If we ended up picking a trivial assignment operator for an array of a
9908 // non-trivially-copyable class type, just emit a memcpy.
9909 if (!Result.isInvalid() && !Result.get())
9910 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9911
9912 return Result;
9913}
9914
Richard Smithb9d0b762012-07-27 04:22:15 +00009915Sema::ImplicitExceptionSpecification
9916Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9917 CXXRecordDecl *ClassDecl = MD->getParent();
9918
9919 ImplicitExceptionSpecification ExceptSpec(*this);
9920 if (ClassDecl->isInvalidDecl())
9921 return ExceptSpec;
9922
9923 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07009924 assert(T->getNumParams() == 1 && "not a copy assignment op");
9925 unsigned ArgQuals =
9926 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithb9d0b762012-07-27 04:22:15 +00009927
Douglas Gregorb87786f2010-07-01 17:48:08 +00009928 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00009929 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00009930 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00009931
9932 // It is unspecified whether or not an implicit copy assignment operator
9933 // attempts to deduplicate calls to assignment operators of virtual bases are
9934 // made. As such, this exception specification is effectively unspecified.
9935 // Based on a similar decision made for constness in C++0x, we're erring on
9936 // the side of assuming such calls to be made regardless of whether they
9937 // actually happen.
Stephen Hines651f13c2014-04-23 16:59:28 -07009938 for (const auto &Base : ClassDecl->bases()) {
9939 if (Base.isVirtual())
Sean Hunt661c67a2011-06-21 23:42:56 +00009940 continue;
9941
Douglas Gregora376d102010-07-02 21:50:04 +00009942 CXXRecordDecl *BaseClassDecl
Stephen Hines651f13c2014-04-23 16:59:28 -07009943 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00009944 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9945 ArgQuals, false, 0))
Stephen Hines651f13c2014-04-23 16:59:28 -07009946 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00009947 }
Sean Hunt661c67a2011-06-21 23:42:56 +00009948
Stephen Hines651f13c2014-04-23 16:59:28 -07009949 for (const auto &Base : ClassDecl->vbases()) {
Sean Hunt661c67a2011-06-21 23:42:56 +00009950 CXXRecordDecl *BaseClassDecl
Stephen Hines651f13c2014-04-23 16:59:28 -07009951 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00009952 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9953 ArgQuals, false, 0))
Stephen Hines651f13c2014-04-23 16:59:28 -07009954 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00009955 }
9956
Stephen Hines651f13c2014-04-23 16:59:28 -07009957 for (const auto *Field : ClassDecl->fields()) {
David Blaikie262bc182012-04-30 02:36:29 +00009958 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00009959 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9960 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009961 LookupCopyingAssignment(FieldClassDecl,
9962 ArgQuals | FieldType.getCVRQualifiers(),
9963 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009964 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00009965 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00009966 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009967
Richard Smithb9d0b762012-07-27 04:22:15 +00009968 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00009969}
9970
9971CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9972 // Note: The following rules are largely analoguous to the copy
9973 // constructor rules. Note that virtual bases are not taken into account
9974 // for determining the argument type of the operator. Note also that
9975 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00009976 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00009977
Richard Smithafb49182012-11-29 01:34:07 +00009978 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9979 if (DSM.isAlreadyBeingDeclared())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009980 return nullptr;
Richard Smithafb49182012-11-29 01:34:07 +00009981
Sean Hunt30de05c2011-05-14 05:23:20 +00009982 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9983 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smitha8942d72013-05-07 03:19:20 +00009984 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9985 if (Const)
Sean Hunt30de05c2011-05-14 05:23:20 +00009986 ArgType = ArgType.withConst();
9987 ArgType = Context.getLValueReferenceType(ArgType);
9988
Richard Smitha8942d72013-05-07 03:19:20 +00009989 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9990 CXXCopyAssignment,
9991 Const);
9992
Douglas Gregord3c35902010-07-01 16:36:15 +00009993 // An implicitly-declared copy assignment operator is an inline public
9994 // member of its class.
9995 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009996 SourceLocation ClassLoc = ClassDecl->getLocation();
9997 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009998 CXXMethodDecl *CopyAssignment =
9999 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010000 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10001 /*isInline=*/true, Constexpr, SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +000010002 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +000010003 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +000010004 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +000010005
Stephen Hines176edba2014-12-01 14:53:08 -080010006 if (getLangOpts().CUDA) {
10007 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
10008 CopyAssignment,
10009 /* ConstRHS */ Const,
10010 /* Diagnose */ false);
10011 }
10012
Richard Smithb9d0b762012-07-27 04:22:15 +000010013 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +000010014 FunctionProtoType::ExtProtoInfo EPI =
10015 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rosebea522f2013-03-08 21:51:21 +000010016 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +000010017
Douglas Gregord3c35902010-07-01 16:36:15 +000010018 // Add the parameter to the operator.
10019 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010020 ClassLoc, ClassLoc,
10021 /*Id=*/nullptr, ArgType,
10022 /*TInfo=*/nullptr, SC_None,
10023 nullptr);
David Blaikie4278c652011-09-21 18:16:56 +000010024 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +000010025
Richard Smithbc2a35d2012-12-08 08:32:28 +000010026 AddOverriddenMethods(ClassDecl, CopyAssignment);
10027
10028 CopyAssignment->setTrivial(
10029 ClassDecl->needsOverloadResolutionForCopyAssignment()
10030 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
10031 : ClassDecl->hasTrivialCopyAssignment());
10032
Richard Smith6c4c36c2012-03-30 20:53:28 +000010033 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +000010034 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +000010035
Richard Smithbc2a35d2012-12-08 08:32:28 +000010036 // Note that we have added this copy-assignment operator.
10037 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
10038
10039 if (Scope *S = getScopeForContext(ClassDecl))
10040 PushOnScopeChains(CopyAssignment, S, false);
10041 ClassDecl->addDecl(CopyAssignment);
10042
Douglas Gregord3c35902010-07-01 16:36:15 +000010043 return CopyAssignment;
10044}
10045
Richard Smith36155c12013-06-13 03:23:42 +000010046/// Diagnose an implicit copy operation for a class which is odr-used, but
10047/// which is deprecated because the class has a user-declared copy constructor,
10048/// copy assignment operator, or destructor.
10049static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
10050 SourceLocation UseLoc) {
10051 assert(CopyOp->isImplicit());
10052
10053 CXXRecordDecl *RD = CopyOp->getParent();
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010054 CXXMethodDecl *UserDeclaredOperation = nullptr;
Richard Smith36155c12013-06-13 03:23:42 +000010055
10056 // In Microsoft mode, assignment operations don't affect constructors and
10057 // vice versa.
10058 if (RD->hasUserDeclaredDestructor()) {
10059 UserDeclaredOperation = RD->getDestructor();
10060 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
10061 RD->hasUserDeclaredCopyConstructor() &&
Stephen Hines651f13c2014-04-23 16:59:28 -070010062 !S.getLangOpts().MSVCCompat) {
Richard Smith36155c12013-06-13 03:23:42 +000010063 // Find any user-declared copy constructor.
Stephen Hines651f13c2014-04-23 16:59:28 -070010064 for (auto *I : RD->ctors()) {
Richard Smith36155c12013-06-13 03:23:42 +000010065 if (I->isCopyConstructor()) {
Stephen Hines651f13c2014-04-23 16:59:28 -070010066 UserDeclaredOperation = I;
Richard Smith36155c12013-06-13 03:23:42 +000010067 break;
10068 }
10069 }
10070 assert(UserDeclaredOperation);
10071 } else if (isa<CXXConstructorDecl>(CopyOp) &&
10072 RD->hasUserDeclaredCopyAssignment() &&
Stephen Hines651f13c2014-04-23 16:59:28 -070010073 !S.getLangOpts().MSVCCompat) {
Richard Smith36155c12013-06-13 03:23:42 +000010074 // Find any user-declared move assignment operator.
Stephen Hines651f13c2014-04-23 16:59:28 -070010075 for (auto *I : RD->methods()) {
Richard Smith36155c12013-06-13 03:23:42 +000010076 if (I->isCopyAssignmentOperator()) {
Stephen Hines651f13c2014-04-23 16:59:28 -070010077 UserDeclaredOperation = I;
Richard Smith36155c12013-06-13 03:23:42 +000010078 break;
10079 }
10080 }
10081 assert(UserDeclaredOperation);
10082 }
10083
10084 if (UserDeclaredOperation) {
10085 S.Diag(UserDeclaredOperation->getLocation(),
10086 diag::warn_deprecated_copy_operation)
10087 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
10088 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
10089 S.Diag(UseLoc, diag::note_member_synthesized_at)
10090 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
10091 : Sema::CXXCopyAssignment)
10092 << RD;
10093 }
10094}
10095
Douglas Gregor06a9f362010-05-01 20:49:11 +000010096void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
10097 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +000010098 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +000010099 CopyAssignOperator->isOverloadedOperator() &&
10100 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +000010101 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
10102 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +000010103 "DefineImplicitCopyAssignment called for wrong function");
10104
10105 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
10106
10107 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
10108 CopyAssignOperator->setInvalidDecl();
10109 return;
10110 }
Richard Smith36155c12013-06-13 03:23:42 +000010111
10112 // C++11 [class.copy]p18:
10113 // The [definition of an implicitly declared copy assignment operator] is
10114 // deprecated if the class has a user-declared copy constructor or a
10115 // user-declared destructor.
10116 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
10117 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
10118
Eli Friedman86164e82013-09-05 00:02:25 +000010119 CopyAssignOperator->markUsed(Context);
Douglas Gregor06a9f362010-05-01 20:49:11 +000010120
Eli Friedman9a14db32012-10-18 20:14:08 +000010121 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +000010122 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +000010123
10124 // C++0x [class.copy]p30:
10125 // The implicitly-defined or explicitly-defaulted copy assignment operator
10126 // for a non-union class X performs memberwise copy assignment of its
10127 // subobjects. The direct base classes of X are assigned first, in the
10128 // order of their declaration in the base-specifier-list, and then the
10129 // immediate non-static data members of X are assigned, in the order in
10130 // which they were declared in the class definition.
10131
10132 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +000010133 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +000010134
10135 // The parameter for the "other" object, which we are copying from.
10136 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
10137 Qualifiers OtherQuals = Other->getType().getQualifiers();
10138 QualType OtherRefType = Other->getType();
10139 if (const LValueReferenceType *OtherRef
10140 = OtherRefType->getAs<LValueReferenceType>()) {
10141 OtherRefType = OtherRef->getPointeeType();
10142 OtherQuals = OtherRefType.getQualifiers();
10143 }
10144
10145 // Our location for everything implicitly-generated.
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010146 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
10147 ? CopyAssignOperator->getLocEnd()
10148 : CopyAssignOperator->getLocation();
10149
Pavel Labath66ea35d2013-08-30 08:52:28 +000010150 // Builds a DeclRefExpr for the "other" object.
10151 RefBuilder OtherRef(Other, OtherRefType);
10152
10153 // Builds the "this" pointer.
10154 ThisBuilder This;
Douglas Gregor06a9f362010-05-01 20:49:11 +000010155
10156 // Assign base classes.
10157 bool Invalid = false;
Stephen Hines651f13c2014-04-23 16:59:28 -070010158 for (auto &Base : ClassDecl->bases()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +000010159 // Form the assignment:
10160 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Stephen Hines651f13c2014-04-23 16:59:28 -070010161 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +000010162 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +000010163 Invalid = true;
10164 continue;
10165 }
10166
John McCallf871d0c2010-08-07 06:22:56 +000010167 CXXCastPath BasePath;
Stephen Hines651f13c2014-04-23 16:59:28 -070010168 BasePath.push_back(&Base);
John McCallf871d0c2010-08-07 06:22:56 +000010169
Douglas Gregor06a9f362010-05-01 20:49:11 +000010170 // Construct the "from" expression, which is an implicit cast to the
10171 // appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +000010172 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
10173 VK_LValue, BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +000010174
10175 // Dereference "this".
Pavel Labath66ea35d2013-08-30 08:52:28 +000010176 DerefBuilder DerefThis(This);
10177 CastBuilder To(DerefThis,
10178 Context.getCVRQualifiedType(
10179 BaseType, CopyAssignOperator->getTypeQualifiers()),
10180 VK_LValue, BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +000010181
10182 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +000010183 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath66ea35d2013-08-30 08:52:28 +000010184 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010185 /*CopyingBaseSubobject=*/true,
10186 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +000010187 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +000010188 Diag(CurrentLocation, diag::note_member_synthesized_at)
10189 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10190 CopyAssignOperator->setInvalidDecl();
10191 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +000010192 }
10193
10194 // Success! Record the copy.
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010195 Statements.push_back(Copy.getAs<Expr>());
Douglas Gregor06a9f362010-05-01 20:49:11 +000010196 }
10197
Douglas Gregor06a9f362010-05-01 20:49:11 +000010198 // Assign non-static members.
Stephen Hines651f13c2014-04-23 16:59:28 -070010199 for (auto *Field : ClassDecl->fields()) {
Douglas Gregord61db332011-10-10 17:22:13 +000010200 if (Field->isUnnamedBitfield())
10201 continue;
Eli Friedman8150da32013-06-07 01:48:56 +000010202
10203 if (Field->isInvalidDecl()) {
10204 Invalid = true;
10205 continue;
10206 }
10207
Douglas Gregor06a9f362010-05-01 20:49:11 +000010208 // Check for members of reference type; we can't copy those.
10209 if (Field->getType()->isReferenceType()) {
10210 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10211 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10212 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +000010213 Diag(CurrentLocation, diag::note_member_synthesized_at)
10214 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +000010215 Invalid = true;
10216 continue;
10217 }
10218
10219 // Check for members of const-qualified, non-class type.
10220 QualType BaseType = Context.getBaseElementType(Field->getType());
10221 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10222 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10223 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10224 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +000010225 Diag(CurrentLocation, diag::note_member_synthesized_at)
10226 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +000010227 Invalid = true;
10228 continue;
10229 }
John McCallb77115d2011-06-17 00:18:42 +000010230
10231 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +000010232 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10233 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +000010234
10235 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +000010236 if (FieldType->isIncompleteArrayType()) {
10237 assert(ClassDecl->hasFlexibleArrayMember() &&
10238 "Incomplete array type is not valid");
10239 continue;
10240 }
Douglas Gregor06a9f362010-05-01 20:49:11 +000010241
10242 // Build references to the field in the object we're copying from and to.
10243 CXXScopeSpec SS; // Intentionally empty
10244 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10245 LookupMemberName);
Stephen Hines651f13c2014-04-23 16:59:28 -070010246 MemberLookup.addDecl(Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +000010247 MemberLookup.resolveKind();
Pavel Labath66ea35d2013-08-30 08:52:28 +000010248
10249 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
10250
10251 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregor06a9f362010-05-01 20:49:11 +000010252
Douglas Gregor06a9f362010-05-01 20:49:11 +000010253 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +000010254 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath66ea35d2013-08-30 08:52:28 +000010255 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010256 /*CopyingBaseSubobject=*/false,
10257 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +000010258 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +000010259 Diag(CurrentLocation, diag::note_member_synthesized_at)
10260 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10261 CopyAssignOperator->setInvalidDecl();
10262 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +000010263 }
10264
10265 // Success! Record the copy.
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010266 Statements.push_back(Copy.getAs<Stmt>());
Douglas Gregor06a9f362010-05-01 20:49:11 +000010267 }
10268
10269 if (!Invalid) {
10270 // Add a "return *this;"
Pavel Labath66ea35d2013-08-30 08:52:28 +000010271 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +000010272
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010273 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +000010274 if (Return.isInvalid())
10275 Invalid = true;
10276 else {
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010277 Statements.push_back(Return.getAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +000010278
10279 if (Trap.hasErrorOccurred()) {
10280 Diag(CurrentLocation, diag::note_member_synthesized_at)
10281 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10282 Invalid = true;
10283 }
Douglas Gregor06a9f362010-05-01 20:49:11 +000010284 }
10285 }
10286
Stephen Hines176edba2014-12-01 14:53:08 -080010287 // The exception specification is needed because we are defining the
10288 // function.
10289 ResolveExceptionSpec(CurrentLocation,
10290 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
10291
Douglas Gregor06a9f362010-05-01 20:49:11 +000010292 if (Invalid) {
10293 CopyAssignOperator->setInvalidDecl();
10294 return;
10295 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010296
10297 StmtResult Body;
10298 {
10299 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010300 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010301 /*isStmtExpr=*/false);
10302 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10303 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010304 CopyAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +000010305
10306 if (ASTMutationListener *L = getASTMutationListener()) {
10307 L->CompletedImplicitDefinition(CopyAssignOperator);
10308 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010309}
10310
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010311Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +000010312Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
10313 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010314
Richard Smithb9d0b762012-07-27 04:22:15 +000010315 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010316 if (ClassDecl->isInvalidDecl())
10317 return ExceptSpec;
10318
10319 // C++0x [except.spec]p14:
10320 // An implicitly declared special member function (Clause 12) shall have an
10321 // exception-specification. [...]
10322
10323 // It is unspecified whether or not an implicit move assignment operator
10324 // attempts to deduplicate calls to assignment operators of virtual bases are
10325 // made. As such, this exception specification is effectively unspecified.
10326 // Based on a similar decision made for constness in C++0x, we're erring on
10327 // the side of assuming such calls to be made regardless of whether they
10328 // actually happen.
10329 // Note that a move constructor is not implicitly declared when there are
10330 // virtual bases, but it can still be user-declared and explicitly defaulted.
Stephen Hines651f13c2014-04-23 16:59:28 -070010331 for (const auto &Base : ClassDecl->bases()) {
10332 if (Base.isVirtual())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010333 continue;
10334
10335 CXXRecordDecl *BaseClassDecl
Stephen Hines651f13c2014-04-23 16:59:28 -070010336 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010337 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +000010338 0, false, 0))
Stephen Hines651f13c2014-04-23 16:59:28 -070010339 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010340 }
10341
Stephen Hines651f13c2014-04-23 16:59:28 -070010342 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010343 CXXRecordDecl *BaseClassDecl
Stephen Hines651f13c2014-04-23 16:59:28 -070010344 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010345 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +000010346 0, false, 0))
Stephen Hines651f13c2014-04-23 16:59:28 -070010347 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010348 }
10349
Stephen Hines651f13c2014-04-23 16:59:28 -070010350 for (const auto *Field : ClassDecl->fields()) {
David Blaikie262bc182012-04-30 02:36:29 +000010351 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010352 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +000010353 if (CXXMethodDecl *MoveAssign =
10354 LookupMovingAssignment(FieldClassDecl,
10355 FieldType.getCVRQualifiers(),
10356 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +000010357 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010358 }
10359 }
10360
10361 return ExceptSpec;
10362}
10363
10364CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +000010365 assert(ClassDecl->needsImplicitMoveAssignment());
10366
Richard Smithafb49182012-11-29 01:34:07 +000010367 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
10368 if (DSM.isAlreadyBeingDeclared())
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010369 return nullptr;
Richard Smithafb49182012-11-29 01:34:07 +000010370
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010371 // Note: The following rules are largely analoguous to the move
10372 // constructor rules.
10373
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010374 QualType ArgType = Context.getTypeDeclType(ClassDecl);
10375 QualType RetType = Context.getLValueReferenceType(ArgType);
10376 ArgType = Context.getRValueReferenceType(ArgType);
10377
Richard Smitha8942d72013-05-07 03:19:20 +000010378 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10379 CXXMoveAssignment,
10380 false);
10381
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010382 // An implicitly-declared move assignment operator is an inline public
10383 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010384 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10385 SourceLocation ClassLoc = ClassDecl->getLocation();
10386 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +000010387 CXXMethodDecl *MoveAssignment =
10388 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010389 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
Richard Smitha8942d72013-05-07 03:19:20 +000010390 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010391 MoveAssignment->setAccess(AS_public);
10392 MoveAssignment->setDefaulted();
10393 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010394
Stephen Hines176edba2014-12-01 14:53:08 -080010395 if (getLangOpts().CUDA) {
10396 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
10397 MoveAssignment,
10398 /* ConstRHS */ false,
10399 /* Diagnose */ false);
10400 }
10401
Richard Smithb9d0b762012-07-27 04:22:15 +000010402 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +000010403 FunctionProtoType::ExtProtoInfo EPI =
10404 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rosebea522f2013-03-08 21:51:21 +000010405 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +000010406
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010407 // Add the parameter to the operator.
10408 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010409 ClassLoc, ClassLoc,
10410 /*Id=*/nullptr, ArgType,
10411 /*TInfo=*/nullptr, SC_None,
10412 nullptr);
David Blaikie4278c652011-09-21 18:16:56 +000010413 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010414
Richard Smithbc2a35d2012-12-08 08:32:28 +000010415 AddOverriddenMethods(ClassDecl, MoveAssignment);
10416
10417 MoveAssignment->setTrivial(
10418 ClassDecl->needsOverloadResolutionForMoveAssignment()
10419 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
10420 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010421
Richard Smith7d5088a2012-02-18 02:02:13 +000010422 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith743cbb92013-11-04 01:48:18 +000010423 ClassDecl->setImplicitMoveAssignmentIsDeleted();
10424 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010425 }
10426
Richard Smithbc2a35d2012-12-08 08:32:28 +000010427 // Note that we have added this copy-assignment operator.
10428 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
10429
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010430 if (Scope *S = getScopeForContext(ClassDecl))
10431 PushOnScopeChains(MoveAssignment, S, false);
10432 ClassDecl->addDecl(MoveAssignment);
10433
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010434 return MoveAssignment;
10435}
10436
Richard Smith33b1f632013-11-04 04:26:14 +000010437/// Check if we're implicitly defining a move assignment operator for a class
10438/// with virtual bases. Such a move assignment might move-assign the virtual
10439/// base multiple times.
10440static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
10441 SourceLocation CurrentLocation) {
10442 assert(!Class->isDependentContext() && "should not define dependent move");
10443
10444 // Only a virtual base could get implicitly move-assigned multiple times.
10445 // Only a non-trivial move assignment can observe this. We only want to
10446 // diagnose if we implicitly define an assignment operator that assigns
10447 // two base classes, both of which move-assign the same virtual base.
10448 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10449 Class->getNumBases() < 2)
10450 return;
10451
10452 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10453 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10454 VBaseMap VBases;
10455
Stephen Hines651f13c2014-04-23 16:59:28 -070010456 for (auto &BI : Class->bases()) {
10457 Worklist.push_back(&BI);
Richard Smith33b1f632013-11-04 04:26:14 +000010458 while (!Worklist.empty()) {
10459 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10460 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10461
10462 // If the base has no non-trivial move assignment operators,
10463 // we don't care about moves from it.
10464 if (!Base->hasNonTrivialMoveAssignment())
10465 continue;
10466
10467 // If there's nothing virtual here, skip it.
10468 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10469 continue;
10470
10471 // If we're not actually going to call a move assignment for this base,
10472 // or the selected move assignment is trivial, skip it.
10473 Sema::SpecialMemberOverloadResult *SMOR =
10474 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10475 /*ConstArg*/false, /*VolatileArg*/false,
10476 /*RValueThis*/true, /*ConstThis*/false,
10477 /*VolatileThis*/false);
10478 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10479 !SMOR->getMethod()->isMoveAssignmentOperator())
10480 continue;
10481
10482 if (BaseSpec->isVirtual()) {
10483 // We're going to move-assign this virtual base, and its move
10484 // assignment operator is not trivial. If this can happen for
10485 // multiple distinct direct bases of Class, diagnose it. (If it
10486 // only happens in one base, we'll diagnose it when synthesizing
10487 // that base class's move assignment operator.)
10488 CXXBaseSpecifier *&Existing =
Stephen Hines651f13c2014-04-23 16:59:28 -070010489 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smith33b1f632013-11-04 04:26:14 +000010490 .first->second;
Stephen Hines651f13c2014-04-23 16:59:28 -070010491 if (Existing && Existing != &BI) {
Richard Smith33b1f632013-11-04 04:26:14 +000010492 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10493 << Class << Base;
10494 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10495 << (Base->getCanonicalDecl() ==
10496 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10497 << Base << Existing->getType() << Existing->getSourceRange();
Stephen Hines651f13c2014-04-23 16:59:28 -070010498 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smith33b1f632013-11-04 04:26:14 +000010499 << (Base->getCanonicalDecl() ==
Stephen Hines651f13c2014-04-23 16:59:28 -070010500 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10501 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smith33b1f632013-11-04 04:26:14 +000010502
10503 // Only diagnose each vbase once.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010504 Existing = nullptr;
Richard Smith33b1f632013-11-04 04:26:14 +000010505 }
10506 } else {
10507 // Only walk over bases that have defaulted move assignment operators.
10508 // We assume that any user-provided move assignment operator handles
10509 // the multiple-moves-of-vbase case itself somehow.
10510 if (!SMOR->getMethod()->isDefaulted())
10511 continue;
10512
10513 // We're going to move the base classes of Base. Add them to the list.
Stephen Hines651f13c2014-04-23 16:59:28 -070010514 for (auto &BI : Base->bases())
10515 Worklist.push_back(&BI);
Richard Smith33b1f632013-11-04 04:26:14 +000010516 }
10517 }
10518 }
10519}
10520
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010521void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10522 CXXMethodDecl *MoveAssignOperator) {
10523 assert((MoveAssignOperator->isDefaulted() &&
10524 MoveAssignOperator->isOverloadedOperator() &&
10525 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +000010526 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10527 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010528 "DefineImplicitMoveAssignment called for wrong function");
10529
10530 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10531
10532 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10533 MoveAssignOperator->setInvalidDecl();
10534 return;
10535 }
10536
Eli Friedman86164e82013-09-05 00:02:25 +000010537 MoveAssignOperator->markUsed(Context);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010538
Eli Friedman9a14db32012-10-18 20:14:08 +000010539 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010540 DiagnosticErrorTrap Trap(Diags);
10541
10542 // C++0x [class.copy]p28:
10543 // The implicitly-defined or move assignment operator for a non-union class
10544 // X performs memberwise move assignment of its subobjects. The direct base
10545 // classes of X are assigned first, in the order of their declaration in the
10546 // base-specifier-list, and then the immediate non-static data members of X
10547 // are assigned, in the order in which they were declared in the class
10548 // definition.
10549
Richard Smith33b1f632013-11-04 04:26:14 +000010550 // Issue a warning if our implicit move assignment operator will move
10551 // from a virtual base more than once.
10552 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith743cbb92013-11-04 01:48:18 +000010553
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010554 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +000010555 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010556
10557 // The parameter for the "other" object, which we are move from.
10558 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10559 QualType OtherRefType = Other->getType()->
10560 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7247c882013-05-15 07:37:26 +000010561 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010562 "Bad argument type of defaulted move assignment");
10563
10564 // Our location for everything implicitly-generated.
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010565 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10566 ? MoveAssignOperator->getLocEnd()
10567 : MoveAssignOperator->getLocation();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010568
Pavel Labath66ea35d2013-08-30 08:52:28 +000010569 // Builds a reference to the "other" object.
10570 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010571 // Cast to rvalue.
Pavel Labath66ea35d2013-08-30 08:52:28 +000010572 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010573
Pavel Labath66ea35d2013-08-30 08:52:28 +000010574 // Builds the "this" pointer.
10575 ThisBuilder This;
Richard Smith1c931be2012-04-02 18:40:40 +000010576
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010577 // Assign base classes.
10578 bool Invalid = false;
Stephen Hines651f13c2014-04-23 16:59:28 -070010579 for (auto &Base : ClassDecl->bases()) {
Richard Smith33b1f632013-11-04 04:26:14 +000010580 // C++11 [class.copy]p28:
10581 // It is unspecified whether subobjects representing virtual base classes
10582 // are assigned more than once by the implicitly-defined copy assignment
10583 // operator.
10584 // FIXME: Do not assign to a vbase that will be assigned by some other base
10585 // class. For a move-assignment, this can result in the vbase being moved
10586 // multiple times.
10587
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010588 // Form the assignment:
10589 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Stephen Hines651f13c2014-04-23 16:59:28 -070010590 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010591 if (!BaseType->isRecordType()) {
10592 Invalid = true;
10593 continue;
10594 }
10595
10596 CXXCastPath BasePath;
Stephen Hines651f13c2014-04-23 16:59:28 -070010597 BasePath.push_back(&Base);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010598
10599 // Construct the "from" expression, which is an implicit cast to the
10600 // appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +000010601 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010602
10603 // Dereference "this".
Pavel Labath66ea35d2013-08-30 08:52:28 +000010604 DerefBuilder DerefThis(This);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010605
10606 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +000010607 CastBuilder To(DerefThis,
10608 Context.getCVRQualifiedType(
10609 BaseType, MoveAssignOperator->getTypeQualifiers()),
10610 VK_LValue, BasePath);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010611
10612 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +000010613 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath66ea35d2013-08-30 08:52:28 +000010614 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010615 /*CopyingBaseSubobject=*/true,
10616 /*Copying=*/false);
10617 if (Move.isInvalid()) {
10618 Diag(CurrentLocation, diag::note_member_synthesized_at)
10619 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10620 MoveAssignOperator->setInvalidDecl();
10621 return;
10622 }
10623
10624 // Success! Record the move.
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010625 Statements.push_back(Move.getAs<Expr>());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010626 }
10627
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010628 // Assign non-static members.
Stephen Hines651f13c2014-04-23 16:59:28 -070010629 for (auto *Field : ClassDecl->fields()) {
Douglas Gregord61db332011-10-10 17:22:13 +000010630 if (Field->isUnnamedBitfield())
10631 continue;
10632
Eli Friedman8150da32013-06-07 01:48:56 +000010633 if (Field->isInvalidDecl()) {
10634 Invalid = true;
10635 continue;
10636 }
10637
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010638 // Check for members of reference type; we can't move those.
10639 if (Field->getType()->isReferenceType()) {
10640 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10641 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10642 Diag(Field->getLocation(), diag::note_declared_at);
10643 Diag(CurrentLocation, diag::note_member_synthesized_at)
10644 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10645 Invalid = true;
10646 continue;
10647 }
10648
10649 // Check for members of const-qualified, non-class type.
10650 QualType BaseType = Context.getBaseElementType(Field->getType());
10651 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10652 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10653 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10654 Diag(Field->getLocation(), diag::note_declared_at);
10655 Diag(CurrentLocation, diag::note_member_synthesized_at)
10656 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10657 Invalid = true;
10658 continue;
10659 }
10660
10661 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +000010662 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10663 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010664
10665 QualType FieldType = Field->getType().getNonReferenceType();
10666 if (FieldType->isIncompleteArrayType()) {
10667 assert(ClassDecl->hasFlexibleArrayMember() &&
10668 "Incomplete array type is not valid");
10669 continue;
10670 }
10671
10672 // Build references to the field in the object we're copying from and to.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010673 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10674 LookupMemberName);
Stephen Hines651f13c2014-04-23 16:59:28 -070010675 MemberLookup.addDecl(Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010676 MemberLookup.resolveKind();
Pavel Labath66ea35d2013-08-30 08:52:28 +000010677 MemberBuilder From(MoveOther, OtherRefType,
10678 /*IsArrow=*/false, MemberLookup);
10679 MemberBuilder To(This, getCurrentThisType(),
10680 /*IsArrow=*/true, MemberLookup);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010681
Pavel Labath66ea35d2013-08-30 08:52:28 +000010682 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010683 "Member reference with rvalue base must be rvalue except for reference "
10684 "members, which aren't allowed for move assignment.");
10685
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010686 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +000010687 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath66ea35d2013-08-30 08:52:28 +000010688 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010689 /*CopyingBaseSubobject=*/false,
10690 /*Copying=*/false);
10691 if (Move.isInvalid()) {
10692 Diag(CurrentLocation, diag::note_member_synthesized_at)
10693 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10694 MoveAssignOperator->setInvalidDecl();
10695 return;
10696 }
Richard Smithe7ce7092012-11-12 23:33:00 +000010697
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010698 // Success! Record the copy.
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010699 Statements.push_back(Move.getAs<Stmt>());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010700 }
10701
10702 if (!Invalid) {
10703 // Add a "return *this;"
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010704 ExprResult ThisObj =
10705 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10706
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010707 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010708 if (Return.isInvalid())
10709 Invalid = true;
10710 else {
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010711 Statements.push_back(Return.getAs<Stmt>());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010712
10713 if (Trap.hasErrorOccurred()) {
10714 Diag(CurrentLocation, diag::note_member_synthesized_at)
10715 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10716 Invalid = true;
10717 }
10718 }
10719 }
10720
Stephen Hines176edba2014-12-01 14:53:08 -080010721 // The exception specification is needed because we are defining the
10722 // function.
10723 ResolveExceptionSpec(CurrentLocation,
10724 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
10725
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010726 if (Invalid) {
10727 MoveAssignOperator->setInvalidDecl();
10728 return;
10729 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010730
10731 StmtResult Body;
10732 {
10733 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010734 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010735 /*isStmtExpr=*/false);
10736 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10737 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010738 MoveAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010739
10740 if (ASTMutationListener *L = getASTMutationListener()) {
10741 L->CompletedImplicitDefinition(MoveAssignOperator);
10742 }
10743}
10744
Richard Smithb9d0b762012-07-27 04:22:15 +000010745Sema::ImplicitExceptionSpecification
10746Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10747 CXXRecordDecl *ClassDecl = MD->getParent();
10748
10749 ImplicitExceptionSpecification ExceptSpec(*this);
10750 if (ClassDecl->isInvalidDecl())
10751 return ExceptSpec;
10752
10753 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -070010754 assert(T->getNumParams() >= 1 && "not a copy ctor");
10755 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithb9d0b762012-07-27 04:22:15 +000010756
Douglas Gregor0d405db2010-07-01 20:59:04 +000010757 // C++ [except.spec]p14:
10758 // An implicitly declared special member function (Clause 12) shall have an
10759 // exception-specification. [...]
Stephen Hines651f13c2014-04-23 16:59:28 -070010760 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor0d405db2010-07-01 20:59:04 +000010761 // Virtual bases are handled below.
Stephen Hines651f13c2014-04-23 16:59:28 -070010762 if (Base.isVirtual())
Douglas Gregor0d405db2010-07-01 20:59:04 +000010763 continue;
10764
Douglas Gregor22584312010-07-02 23:41:54 +000010765 CXXRecordDecl *BaseClassDecl
Stephen Hines651f13c2014-04-23 16:59:28 -070010766 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +000010767 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +000010768 LookupCopyingConstructor(BaseClassDecl, Quals))
Stephen Hines651f13c2014-04-23 16:59:28 -070010769 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +000010770 }
Stephen Hines651f13c2014-04-23 16:59:28 -070010771 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregor22584312010-07-02 23:41:54 +000010772 CXXRecordDecl *BaseClassDecl
Stephen Hines651f13c2014-04-23 16:59:28 -070010773 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +000010774 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +000010775 LookupCopyingConstructor(BaseClassDecl, Quals))
Stephen Hines651f13c2014-04-23 16:59:28 -070010776 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +000010777 }
Stephen Hines651f13c2014-04-23 16:59:28 -070010778 for (const auto *Field : ClassDecl->fields()) {
David Blaikie262bc182012-04-30 02:36:29 +000010779 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +000010780 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10781 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +000010782 LookupCopyingConstructor(FieldClassDecl,
10783 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +000010784 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +000010785 }
10786 }
Sebastian Redl60618fa2011-03-12 11:50:43 +000010787
Richard Smithb9d0b762012-07-27 04:22:15 +000010788 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +000010789}
10790
10791CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10792 CXXRecordDecl *ClassDecl) {
10793 // C++ [class.copy]p4:
10794 // If the class definition does not explicitly declare a copy
10795 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +000010796 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +000010797
Richard Smithafb49182012-11-29 01:34:07 +000010798 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10799 if (DSM.isAlreadyBeingDeclared())
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010800 return nullptr;
Richard Smithafb49182012-11-29 01:34:07 +000010801
Sean Hunt49634cf2011-05-13 06:10:58 +000010802 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10803 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +000010804 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +000010805 if (Const)
10806 ArgType = ArgType.withConst();
10807 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +000010808
Richard Smith7756afa2012-06-10 05:43:50 +000010809 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10810 CXXCopyConstructor,
10811 Const);
10812
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010813 DeclarationName Name
10814 = Context.DeclarationNames.getCXXConstructorName(
10815 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010816 SourceLocation ClassLoc = ClassDecl->getLocation();
10817 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +000010818
10819 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +000010820 // member of its class.
10821 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010822 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smith61802452011-12-22 02:22:31 +000010823 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +000010824 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010825 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +000010826 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +000010827
Stephen Hines176edba2014-12-01 14:53:08 -080010828 if (getLangOpts().CUDA) {
10829 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
10830 CopyConstructor,
10831 /* ConstRHS */ Const,
10832 /* Diagnose */ false);
10833 }
10834
Richard Smithb9d0b762012-07-27 04:22:15 +000010835 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +000010836 FunctionProtoType::ExtProtoInfo EPI =
10837 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithb9d0b762012-07-27 04:22:15 +000010838 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +000010839 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +000010840
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010841 // Add the parameter to the constructor.
10842 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010843 ClassLoc, ClassLoc,
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010844 /*IdentifierInfo=*/nullptr,
10845 ArgType, /*TInfo=*/nullptr,
10846 SC_None, nullptr);
David Blaikie4278c652011-09-21 18:16:56 +000010847 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +000010848
Richard Smithbc2a35d2012-12-08 08:32:28 +000010849 CopyConstructor->setTrivial(
10850 ClassDecl->needsOverloadResolutionForCopyConstructor()
10851 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10852 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +000010853
Richard Smith6c4c36c2012-03-30 20:53:28 +000010854 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +000010855 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +000010856
Richard Smithbc2a35d2012-12-08 08:32:28 +000010857 // Note that we have declared this constructor.
10858 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10859
10860 if (Scope *S = getScopeForContext(ClassDecl))
10861 PushOnScopeChains(CopyConstructor, S, false);
10862 ClassDecl->addDecl(CopyConstructor);
10863
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010864 return CopyConstructor;
10865}
10866
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010867void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +000010868 CXXConstructorDecl *CopyConstructor) {
10869 assert((CopyConstructor->isDefaulted() &&
10870 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +000010871 !CopyConstructor->doesThisDeclarationHaveABody() &&
10872 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010873 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +000010874
Anders Carlsson63010a72010-04-23 16:24:12 +000010875 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010876 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010877
Richard Smith36155c12013-06-13 03:23:42 +000010878 // C++11 [class.copy]p7:
Benjamin Kramere5753592013-09-09 14:48:42 +000010879 // The [definition of an implicitly declared copy constructor] is
Richard Smith36155c12013-06-13 03:23:42 +000010880 // deprecated if the class has a user-declared copy assignment operator
10881 // or a user-declared destructor.
10882 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10883 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10884
Eli Friedman9a14db32012-10-18 20:14:08 +000010885 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +000010886 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010887
David Blaikie93c86172013-01-17 05:26:25 +000010888 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +000010889 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +000010890 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +000010891 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +000010892 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +000010893 } else {
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010894 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10895 ? CopyConstructor->getLocEnd()
10896 : CopyConstructor->getLocation();
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010897 Sema::CompoundScopeRAII CompoundScope(*this);
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010898 CopyConstructor->setBody(
10899 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +000010900 }
Robert Wilhelmc895f4d2013-08-19 20:51:20 +000010901
Stephen Hines176edba2014-12-01 14:53:08 -080010902 // The exception specification is needed because we are defining the
10903 // function.
10904 ResolveExceptionSpec(CurrentLocation,
10905 CopyConstructor->getType()->castAs<FunctionProtoType>());
10906
Eli Friedman86164e82013-09-05 00:02:25 +000010907 CopyConstructor->markUsed(Context);
Stephen Hines176edba2014-12-01 14:53:08 -080010908 MarkVTableUsed(CurrentLocation, ClassDecl);
10909
Sebastian Redl58a2cd82011-04-24 16:28:06 +000010910 if (ASTMutationListener *L = getASTMutationListener()) {
10911 L->CompletedImplicitDefinition(CopyConstructor);
10912 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010913}
10914
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010915Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +000010916Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10917 CXXRecordDecl *ClassDecl = MD->getParent();
10918
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010919 // C++ [except.spec]p14:
10920 // An implicitly declared special member function (Clause 12) shall have an
10921 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +000010922 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010923 if (ClassDecl->isInvalidDecl())
10924 return ExceptSpec;
10925
10926 // Direct base-class constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -070010927 for (const auto &B : ClassDecl->bases()) {
10928 if (B.isVirtual()) // Handled below.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010929 continue;
10930
Stephen Hines651f13c2014-04-23 16:59:28 -070010931 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010932 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +000010933 CXXConstructorDecl *Constructor =
10934 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010935 // If this is a deleted function, add it anyway. This might be conformant
10936 // with the standard. This might not. I'm not sure. It might not matter.
10937 if (Constructor)
Stephen Hines651f13c2014-04-23 16:59:28 -070010938 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010939 }
10940 }
10941
10942 // Virtual base-class constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -070010943 for (const auto &B : ClassDecl->vbases()) {
10944 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010945 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +000010946 CXXConstructorDecl *Constructor =
10947 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010948 // If this is a deleted function, add it anyway. This might be conformant
10949 // with the standard. This might not. I'm not sure. It might not matter.
10950 if (Constructor)
Stephen Hines651f13c2014-04-23 16:59:28 -070010951 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010952 }
10953 }
10954
10955 // Field constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -070010956 for (const auto *F : ClassDecl->fields()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +000010957 QualType FieldType = Context.getBaseElementType(F->getType());
10958 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10959 CXXConstructorDecl *Constructor =
10960 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010961 // If this is a deleted function, add it anyway. This might be conformant
10962 // with the standard. This might not. I'm not sure. It might not matter.
10963 // In particular, the problem is that this function never gets called. It
10964 // might just be ill-formed because this function attempts to refer to
10965 // a deleted function here.
10966 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +000010967 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010968 }
10969 }
10970
10971 return ExceptSpec;
10972}
10973
10974CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10975 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +000010976 assert(ClassDecl->needsImplicitMoveConstructor());
10977
Richard Smithafb49182012-11-29 01:34:07 +000010978 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10979 if (DSM.isAlreadyBeingDeclared())
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010980 return nullptr;
Richard Smithafb49182012-11-29 01:34:07 +000010981
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010982 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10983 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010984
Richard Smith7756afa2012-06-10 05:43:50 +000010985 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10986 CXXMoveConstructor,
10987 false);
10988
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010989 DeclarationName Name
10990 = Context.DeclarationNames.getCXXConstructorName(
10991 Context.getCanonicalType(ClassType));
10992 SourceLocation ClassLoc = ClassDecl->getLocation();
10993 DeclarationNameInfo NameInfo(Name, ClassLoc);
10994
Richard Smitha8942d72013-05-07 03:19:20 +000010995 // C++11 [class.copy]p11:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010996 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +000010997 // member of its class.
10998 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010999 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smith61802452011-12-22 02:22:31 +000011000 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +000011001 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011002 MoveConstructor->setAccess(AS_public);
11003 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +000011004
Stephen Hines176edba2014-12-01 14:53:08 -080011005 if (getLangOpts().CUDA) {
11006 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
11007 MoveConstructor,
11008 /* ConstRHS */ false,
11009 /* Diagnose */ false);
11010 }
11011
Richard Smithb9d0b762012-07-27 04:22:15 +000011012 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +000011013 FunctionProtoType::ExtProtoInfo EPI =
11014 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithb9d0b762012-07-27 04:22:15 +000011015 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +000011016 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +000011017
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011018 // Add the parameter to the constructor.
11019 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
11020 ClassLoc, ClassLoc,
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011021 /*IdentifierInfo=*/nullptr,
11022 ArgType, /*TInfo=*/nullptr,
11023 SC_None, nullptr);
David Blaikie4278c652011-09-21 18:16:56 +000011024 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011025
Richard Smithbc2a35d2012-12-08 08:32:28 +000011026 MoveConstructor->setTrivial(
11027 ClassDecl->needsOverloadResolutionForMoveConstructor()
11028 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
11029 : ClassDecl->hasTrivialMoveConstructor());
11030
Sean Hunt769bb2d2011-10-11 06:43:29 +000011031 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith743cbb92013-11-04 01:48:18 +000011032 ClassDecl->setImplicitMoveConstructorIsDeleted();
11033 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011034 }
11035
11036 // Note that we have declared this constructor.
11037 ++ASTContext::NumImplicitMoveConstructorsDeclared;
11038
11039 if (Scope *S = getScopeForContext(ClassDecl))
11040 PushOnScopeChains(MoveConstructor, S, false);
11041 ClassDecl->addDecl(MoveConstructor);
11042
11043 return MoveConstructor;
11044}
11045
11046void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
11047 CXXConstructorDecl *MoveConstructor) {
11048 assert((MoveConstructor->isDefaulted() &&
11049 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +000011050 !MoveConstructor->doesThisDeclarationHaveABody() &&
11051 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011052 "DefineImplicitMoveConstructor - call it for implicit move ctor");
11053
11054 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
11055 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
11056
Eli Friedman9a14db32012-10-18 20:14:08 +000011057 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011058 DiagnosticErrorTrap Trap(Diags);
11059
David Blaikie93c86172013-01-17 05:26:25 +000011060 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011061 Trap.hasErrorOccurred()) {
11062 Diag(CurrentLocation, diag::note_member_synthesized_at)
11063 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
11064 MoveConstructor->setInvalidDecl();
11065 } else {
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011066 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
11067 ? MoveConstructor->getLocEnd()
11068 : MoveConstructor->getLocation();
Dmitri Gribenko625bb562012-02-14 22:14:32 +000011069 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +000011070 MoveConstructor->setBody(ActOnCompoundStmt(
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011071 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011072 }
11073
Stephen Hines176edba2014-12-01 14:53:08 -080011074 // The exception specification is needed because we are defining the
11075 // function.
11076 ResolveExceptionSpec(CurrentLocation,
11077 MoveConstructor->getType()->castAs<FunctionProtoType>());
11078
Eli Friedman86164e82013-09-05 00:02:25 +000011079 MoveConstructor->markUsed(Context);
Stephen Hines176edba2014-12-01 14:53:08 -080011080 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011081
11082 if (ASTMutationListener *L = getASTMutationListener()) {
11083 L->CompletedImplicitDefinition(MoveConstructor);
11084 }
11085}
11086
Douglas Gregore4e68d42012-02-15 19:33:52 +000011087bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanc4ef9482013-07-18 23:29:14 +000011088 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregore4e68d42012-02-15 19:33:52 +000011089}
Douglas Gregorf6e2e022012-02-16 01:06:16 +000011090
11091void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Valid6992ab2013-09-29 08:45:24 +000011092 SourceLocation CurrentLocation,
11093 CXXConversionDecl *Conv) {
11094 CXXRecordDecl *Lambda = Conv->getParent();
11095 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
11096 // If we are defining a specialization of a conversion to function-ptr
11097 // cache the deduced template arguments for this specialization
11098 // so that we can use them to retrieve the corresponding call-operator
11099 // and static-invoker.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011100 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
11101
Faisal Valid6992ab2013-09-29 08:45:24 +000011102 // Retrieve the corresponding call-operator specialization.
11103 if (Lambda->isGenericLambda()) {
11104 assert(Conv->isFunctionTemplateSpecialization());
11105 FunctionTemplateDecl *CallOpTemplate =
11106 CallOp->getDescribedFunctionTemplate();
11107 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011108 void *InsertPos = nullptr;
Faisal Valid6992ab2013-09-29 08:45:24 +000011109 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011110 DeducedTemplateArgs->asArray(),
Faisal Valid6992ab2013-09-29 08:45:24 +000011111 InsertPos);
11112 assert(CallOpSpec &&
11113 "Conversion operator must have a corresponding call operator");
11114 CallOp = cast<CXXMethodDecl>(CallOpSpec);
11115 }
11116 // Mark the call operator referenced (and add to pending instantiations
11117 // if necessary).
11118 // For both the conversion and static-invoker template specializations
11119 // we construct their body's in this function, so no need to add them
11120 // to the PendingInstantiations.
11121 MarkFunctionReferenced(CurrentLocation, CallOp);
11122
Eli Friedman9a14db32012-10-18 20:14:08 +000011123 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000011124 DiagnosticErrorTrap Trap(Diags);
Faisal Valid6992ab2013-09-29 08:45:24 +000011125
Stephen Hines651f13c2014-04-23 16:59:28 -070011126 // Retrieve the static invoker...
Faisal Valid6992ab2013-09-29 08:45:24 +000011127 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
11128 // ... and get the corresponding specialization for a generic lambda.
11129 if (Lambda->isGenericLambda()) {
11130 assert(DeducedTemplateArgs &&
11131 "Must have deduced template arguments from Conversion Operator");
11132 FunctionTemplateDecl *InvokeTemplate =
11133 Invoker->getDescribedFunctionTemplate();
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011134 void *InsertPos = nullptr;
Faisal Valid6992ab2013-09-29 08:45:24 +000011135 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011136 DeducedTemplateArgs->asArray(),
Faisal Valid6992ab2013-09-29 08:45:24 +000011137 InsertPos);
11138 assert(InvokeSpec &&
11139 "Must have a corresponding static invoker specialization");
11140 Invoker = cast<CXXMethodDecl>(InvokeSpec);
11141 }
11142 // Construct the body of the conversion function { return __invoke; }.
11143 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011144 VK_LValue, Conv->getLocation()).get();
Faisal Valid6992ab2013-09-29 08:45:24 +000011145 assert(FunctionRef && "Can't refer to __invoke function?");
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011146 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
Faisal Valid6992ab2013-09-29 08:45:24 +000011147 Conv->setBody(new (Context) CompoundStmt(Context, Return,
11148 Conv->getLocation(),
11149 Conv->getLocation()));
11150
11151 Conv->markUsed(Context);
11152 Conv->setReferenced();
Douglas Gregorf6e2e022012-02-16 01:06:16 +000011153
Faisal Valid6992ab2013-09-29 08:45:24 +000011154 // Fill in the __invoke function with a dummy implementation. IR generation
11155 // will fill in the actual details.
11156 Invoker->markUsed(Context);
11157 Invoker->setReferenced();
11158 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
11159
Douglas Gregorf6e2e022012-02-16 01:06:16 +000011160 if (ASTMutationListener *L = getASTMutationListener()) {
11161 L->CompletedImplicitDefinition(Conv);
Faisal Valid6992ab2013-09-29 08:45:24 +000011162 L->CompletedImplicitDefinition(Invoker);
11163 }
Douglas Gregorf6e2e022012-02-16 01:06:16 +000011164}
11165
Faisal Valid6992ab2013-09-29 08:45:24 +000011166
11167
Douglas Gregorf6e2e022012-02-16 01:06:16 +000011168void Sema::DefineImplicitLambdaToBlockPointerConversion(
11169 SourceLocation CurrentLocation,
11170 CXXConversionDecl *Conv)
11171{
Faisal Vali56fe35b2013-09-29 17:08:32 +000011172 assert(!Conv->getParent()->isGenericLambda());
Faisal Valid6992ab2013-09-29 08:45:24 +000011173
Eli Friedman86164e82013-09-05 00:02:25 +000011174 Conv->markUsed(Context);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000011175
Eli Friedman9a14db32012-10-18 20:14:08 +000011176 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000011177 DiagnosticErrorTrap Trap(Diags);
11178
Douglas Gregorac1303e2012-02-22 05:02:47 +000011179 // Copy-initialize the lambda object as needed to capture it.
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011180 Expr *This = ActOnCXXThis(CurrentLocation).get();
11181 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
Douglas Gregorf6e2e022012-02-16 01:06:16 +000011182
Eli Friedman23f02672012-03-01 04:01:32 +000011183 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
11184 Conv->getLocation(),
11185 Conv, DerefThis);
11186
11187 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
11188 // behavior. Note that only the general conversion function does this
11189 // (since it's unusable otherwise); in the case where we inline the
11190 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +000011191 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +000011192 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
11193 CK_CopyAndAutoreleaseBlockObject,
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011194 BuildBlock.get(), nullptr, VK_RValue);
Eli Friedman23f02672012-03-01 04:01:32 +000011195
11196 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +000011197 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +000011198 Conv->setInvalidDecl();
11199 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +000011200 }
Douglas Gregorac1303e2012-02-22 05:02:47 +000011201
Douglas Gregorac1303e2012-02-22 05:02:47 +000011202 // Create the return statement that returns the block from the conversion
11203 // function.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011204 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +000011205 if (Return.isInvalid()) {
11206 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11207 Conv->setInvalidDecl();
11208 return;
11209 }
11210
11211 // Set the body of the conversion function.
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011212 Stmt *ReturnS = Return.get();
Nico Weberd36aa352012-12-29 20:03:39 +000011213 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +000011214 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +000011215 Conv->getLocation()));
11216
Douglas Gregorac1303e2012-02-22 05:02:47 +000011217 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000011218 if (ASTMutationListener *L = getASTMutationListener()) {
11219 L->CompletedImplicitDefinition(Conv);
11220 }
11221}
11222
Douglas Gregorf52757d2012-03-10 06:53:13 +000011223/// \brief Determine whether the given list arguments contains exactly one
11224/// "real" (non-default) argument.
11225static bool hasOneRealArgument(MultiExprArg Args) {
11226 switch (Args.size()) {
11227 case 0:
11228 return false;
11229
11230 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011231 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +000011232 return false;
11233
11234 // fall through
11235 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011236 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +000011237 }
11238
11239 return false;
11240}
11241
John McCall60d7b3a2010-08-24 06:29:42 +000011242ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000011243Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +000011244 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +000011245 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011246 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000011247 bool IsListInitialization,
Stephen Hines176edba2014-12-01 14:53:08 -080011248 bool IsStdInitListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000011249 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000011250 unsigned ConstructKind,
11251 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000011252 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +000011253
Douglas Gregor2f599792010-04-02 18:24:57 +000011254 // C++0x [class.copy]p34:
11255 // When certain criteria are met, an implementation is allowed to
11256 // omit the copy/move construction of a class object, even if the
11257 // copy/move constructor and/or destructor for the object have
11258 // side effects. [...]
11259 // - when a temporary class object that has not been bound to a
11260 // reference (12.2) would be copied/moved to a class object
11261 // with the same cv-unqualified type, the copy/move operation
11262 // can be omitted by constructing the temporary object
11263 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +000011264 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +000011265 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +000011266 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +000011267 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000011268 }
Mike Stump1eb44332009-09-09 15:08:12 +000011269
11270 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011271 Elidable, ExprArgs, HadMultipleCandidates,
Stephen Hines176edba2014-12-01 14:53:08 -080011272 IsListInitialization,
11273 IsStdInitListInitialization, RequiresZeroInit,
Richard Smithc83c2302012-12-19 01:39:02 +000011274 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000011275}
11276
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000011277/// BuildCXXConstructExpr - Creates a complete call to a constructor,
11278/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +000011279ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000011280Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11281 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +000011282 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011283 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000011284 bool IsListInitialization,
Stephen Hines176edba2014-12-01 14:53:08 -080011285 bool IsStdInitListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000011286 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000011287 unsigned ConstructKind,
11288 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011289 MarkFunctionReferenced(ConstructLoc, Constructor);
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011290 return CXXConstructExpr::Create(
11291 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
Stephen Hines176edba2014-12-01 14:53:08 -080011292 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
11293 RequiresZeroInit,
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011294 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
11295 ParenRange);
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000011296}
11297
Stephen Hines176edba2014-12-01 14:53:08 -080011298ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
11299 assert(Field->hasInClassInitializer());
11300
11301 // If we already have the in-class initializer nothing needs to be done.
11302 if (Field->getInClassInitializer())
11303 return CXXDefaultInitExpr::Create(Context, Loc, Field);
11304
11305 // Maybe we haven't instantiated the in-class initializer. Go check the
11306 // pattern FieldDecl to see if it has one.
11307 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
11308
11309 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
11310 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
11311 DeclContext::lookup_result Lookup =
11312 ClassPattern->lookup(Field->getDeclName());
11313 assert(Lookup.size() == 1);
11314 FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]);
11315 if (InstantiateInClassInitializer(Loc, Field, Pattern,
11316 getTemplateInstantiationArgs(Field)))
11317 return ExprError();
11318 return CXXDefaultInitExpr::Create(Context, Loc, Field);
11319 }
11320
11321 // DR1351:
11322 // If the brace-or-equal-initializer of a non-static data member
11323 // invokes a defaulted default constructor of its class or of an
11324 // enclosing class in a potentially evaluated subexpression, the
11325 // program is ill-formed.
11326 //
11327 // This resolution is unworkable: the exception specification of the
11328 // default constructor can be needed in an unevaluated context, in
11329 // particular, in the operand of a noexcept-expression, and we can be
11330 // unable to compute an exception specification for an enclosed class.
11331 //
11332 // Any attempt to resolve the exception specification of a defaulted default
11333 // constructor before the initializer is lexically complete will ultimately
11334 // come here at which point we can diagnose it.
11335 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
11336 if (OutermostClass == ParentRD) {
11337 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
11338 << ParentRD << Field;
11339 } else {
11340 Diag(Field->getLocEnd(),
11341 diag::err_in_class_initializer_not_yet_parsed_outer_class)
11342 << ParentRD << OutermostClass << Field;
11343 }
11344
11345 return ExprError();
11346}
11347
John McCall68c6c9a2010-02-02 09:10:11 +000011348void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000011349 if (VD->isInvalidDecl()) return;
11350
John McCall68c6c9a2010-02-02 09:10:11 +000011351 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000011352 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +000011353 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000011354 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +000011355
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000011356 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +000011357 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000011358 CheckDestructorAccess(VD->getLocation(), Destructor,
11359 PDiag(diag::err_access_dtor_var)
11360 << VD->getDeclName()
11361 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +000011362 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +000011363
Stephen Hines651f13c2014-04-23 16:59:28 -070011364 if (Destructor->isTrivial()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000011365 if (!VD->hasGlobalStorage()) return;
11366
11367 // Emit warning for non-trivial dtor in global scope (a real global,
11368 // class-static, function-static).
11369 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
11370
11371 // TODO: this should be re-enabled for static locals by !CXAAtExit
11372 if (!VD->isStaticLocal())
11373 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000011374}
11375
Douglas Gregor39da0b82009-09-09 23:08:42 +000011376/// \brief Given a constructor and the set of arguments provided for the
11377/// constructor, convert the arguments and add any required default arguments
11378/// to form a proper call to this constructor.
11379///
11380/// \returns true if an error occurred, false otherwise.
11381bool
11382Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
11383 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +000011384 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +000011385 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000011386 bool AllowExplicit,
11387 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +000011388 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
11389 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +000011390 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +000011391
11392 const FunctionProtoType *Proto
11393 = Constructor->getType()->getAs<FunctionProtoType>();
11394 assert(Proto && "Constructor without a prototype?");
Stephen Hines651f13c2014-04-23 16:59:28 -070011395 unsigned NumParams = Proto->getNumParams();
11396
Douglas Gregor39da0b82009-09-09 23:08:42 +000011397 // If too few arguments are available, we'll fill in the rest with defaults.
Stephen Hines651f13c2014-04-23 16:59:28 -070011398 if (NumArgs < NumParams)
11399 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000011400 else
Douglas Gregor39da0b82009-09-09 23:08:42 +000011401 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000011402
11403 VariadicCallType CallType =
11404 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +000011405 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000011406 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011407 Proto, 0,
11408 llvm::makeArrayRef(Args, NumArgs),
11409 AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000011410 CallType, AllowExplicit,
11411 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +000011412 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +000011413
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011414 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmane61eb042012-02-18 04:48:30 +000011415
Dmitri Gribenko1c030e92013-01-13 20:46:02 +000011416 CheckConstructorCall(Constructor,
Stephen Hines176edba2014-12-01 14:53:08 -080011417 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +000011418 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +000011419
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000011420 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +000011421}
11422
Anders Carlsson20d45d22009-12-12 00:32:00 +000011423static inline bool
11424CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
11425 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011426 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +000011427 if (isa<NamespaceDecl>(DC)) {
11428 return SemaRef.Diag(FnDecl->getLocation(),
11429 diag::err_operator_new_delete_declared_in_namespace)
11430 << FnDecl->getDeclName();
11431 }
11432
11433 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +000011434 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000011435 return SemaRef.Diag(FnDecl->getLocation(),
11436 diag::err_operator_new_delete_declared_static)
11437 << FnDecl->getDeclName();
11438 }
11439
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +000011440 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +000011441}
11442
Anders Carlsson156c78e2009-12-13 17:53:43 +000011443static inline bool
11444CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
11445 CanQualType ExpectedResultType,
11446 CanQualType ExpectedFirstParamType,
11447 unsigned DependentParamTypeDiag,
11448 unsigned InvalidParamTypeDiag) {
Stephen Hines651f13c2014-04-23 16:59:28 -070011449 QualType ResultType =
11450 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson156c78e2009-12-13 17:53:43 +000011451
11452 // Check that the result type is not dependent.
11453 if (ResultType->isDependentType())
11454 return SemaRef.Diag(FnDecl->getLocation(),
11455 diag::err_operator_new_delete_dependent_result_type)
11456 << FnDecl->getDeclName() << ExpectedResultType;
11457
11458 // Check that the result type is what we expect.
11459 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
11460 return SemaRef.Diag(FnDecl->getLocation(),
11461 diag::err_operator_new_delete_invalid_result_type)
11462 << FnDecl->getDeclName() << ExpectedResultType;
11463
11464 // A function template must have at least 2 parameters.
11465 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
11466 return SemaRef.Diag(FnDecl->getLocation(),
11467 diag::err_operator_new_delete_template_too_few_parameters)
11468 << FnDecl->getDeclName();
11469
11470 // The function decl must have at least 1 parameter.
11471 if (FnDecl->getNumParams() == 0)
11472 return SemaRef.Diag(FnDecl->getLocation(),
11473 diag::err_operator_new_delete_too_few_parameters)
11474 << FnDecl->getDeclName();
11475
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000011476 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +000011477 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
11478 if (FirstParamType->isDependentType())
11479 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
11480 << FnDecl->getDeclName() << ExpectedFirstParamType;
11481
11482 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000011483 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000011484 ExpectedFirstParamType)
11485 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
11486 << FnDecl->getDeclName() << ExpectedFirstParamType;
11487
11488 return false;
11489}
11490
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000011491static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000011492CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000011493 // C++ [basic.stc.dynamic.allocation]p1:
11494 // A program is ill-formed if an allocation function is declared in a
11495 // namespace scope other than global scope or declared static in global
11496 // scope.
11497 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11498 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000011499
11500 CanQualType SizeTy =
11501 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11502
11503 // C++ [basic.stc.dynamic.allocation]p1:
11504 // The return type shall be void*. The first parameter shall have type
11505 // std::size_t.
11506 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
11507 SizeTy,
11508 diag::err_operator_new_dependent_param_type,
11509 diag::err_operator_new_param_type))
11510 return true;
11511
11512 // C++ [basic.stc.dynamic.allocation]p1:
11513 // The first parameter shall not have an associated default argument.
11514 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000011515 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000011516 diag::err_operator_new_default_arg)
11517 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11518
11519 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000011520}
11521
11522static bool
Richard Smith444d3842012-10-20 08:26:51 +000011523CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000011524 // C++ [basic.stc.dynamic.deallocation]p1:
11525 // A program is ill-formed if deallocation functions are declared in a
11526 // namespace scope other than global scope or declared static in global
11527 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000011528 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11529 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000011530
11531 // C++ [basic.stc.dynamic.deallocation]p2:
11532 // Each deallocation function shall return void and its first parameter
11533 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000011534 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
11535 SemaRef.Context.VoidPtrTy,
11536 diag::err_operator_delete_dependent_param_type,
11537 diag::err_operator_delete_param_type))
11538 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000011539
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000011540 return false;
11541}
11542
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011543/// CheckOverloadedOperatorDeclaration - Check whether the declaration
11544/// of this overloaded operator is well-formed. If so, returns false;
11545/// otherwise, emits appropriate diagnostics and returns true.
11546bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000011547 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011548 "Expected an overloaded operator declaration");
11549
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011550 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11551
Mike Stump1eb44332009-09-09 15:08:12 +000011552 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011553 // The allocation and deallocation functions, operator new,
11554 // operator new[], operator delete and operator delete[], are
11555 // described completely in 3.7.3. The attributes and restrictions
11556 // found in the rest of this subclause do not apply to them unless
11557 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000011558 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000011559 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000011560
Anders Carlssona3ccda52009-12-12 00:26:23 +000011561 if (Op == OO_New || Op == OO_Array_New)
11562 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011563
11564 // C++ [over.oper]p6:
11565 // An operator function shall either be a non-static member
11566 // function or be a non-member function and have at least one
11567 // parameter whose type is a class, a reference to a class, an
11568 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000011569 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11570 if (MethodDecl->isStatic())
11571 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000011572 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011573 } else {
11574 bool ClassOrEnumParam = false;
Stephen Hines651f13c2014-04-23 16:59:28 -070011575 for (auto Param : FnDecl->params()) {
11576 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000011577 if (ParamType->isDependentType() || ParamType->isRecordType() ||
11578 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011579 ClassOrEnumParam = true;
11580 break;
11581 }
11582 }
11583
Douglas Gregor43c7bad2008-11-17 16:14:12 +000011584 if (!ClassOrEnumParam)
11585 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000011586 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000011587 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011588 }
11589
11590 // C++ [over.oper]p8:
11591 // An operator function cannot have default arguments (8.3.6),
11592 // except where explicitly stated below.
11593 //
Mike Stump1eb44332009-09-09 15:08:12 +000011594 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011595 // (C++ [over.call]p1).
11596 if (Op != OO_Call) {
Stephen Hines651f13c2014-04-23 16:59:28 -070011597 for (auto Param : FnDecl->params()) {
11598 if (Param->hasDefaultArg())
11599 return Diag(Param->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000011600 diag::err_operator_overload_default_arg)
Stephen Hines651f13c2014-04-23 16:59:28 -070011601 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011602 }
11603 }
11604
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000011605 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11606 { false, false, false }
11607#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11608 , { Unary, Binary, MemberOnly }
11609#include "clang/Basic/OperatorKinds.def"
11610 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011611
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000011612 bool CanBeUnaryOperator = OperatorUses[Op][0];
11613 bool CanBeBinaryOperator = OperatorUses[Op][1];
11614 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011615
11616 // C++ [over.oper]p8:
11617 // [...] Operator functions cannot have more or fewer parameters
11618 // than the number required for the corresponding operator, as
11619 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000011620 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000011621 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011622 if (Op != OO_Call &&
11623 ((NumParams == 1 && !CanBeUnaryOperator) ||
11624 (NumParams == 2 && !CanBeBinaryOperator) ||
11625 (NumParams < 1) || (NumParams > 2))) {
11626 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000011627 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000011628 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000011629 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000011630 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000011631 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000011632 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000011633 assert(CanBeBinaryOperator &&
11634 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000011635 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000011636 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011637
Chris Lattner416e46f2008-11-21 07:57:12 +000011638 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000011639 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011640 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000011641
Douglas Gregor43c7bad2008-11-17 16:14:12 +000011642 // Overloaded operators other than operator() cannot be variadic.
11643 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000011644 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000011645 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000011646 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011647 }
11648
11649 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000011650 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11651 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000011652 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000011653 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011654 }
11655
11656 // C++ [over.inc]p1:
11657 // The user-defined function called operator++ implements the
11658 // prefix and postfix ++ operator. If this function is a member
11659 // function with no parameters, or a non-member function with one
11660 // parameter of class or enumeration type, it defines the prefix
11661 // increment operator ++ for objects of that type. If the function
11662 // is a member function with one parameter (which shall be of type
11663 // int) or a non-member function with two parameters (the second
11664 // of which shall be of type int), it defines the postfix
11665 // increment operator ++ for objects of that type.
11666 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11667 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Stephen Hines651f13c2014-04-23 16:59:28 -070011668 QualType ParamType = LastParam->getType();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011669
Stephen Hines651f13c2014-04-23 16:59:28 -070011670 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11671 !ParamType->isDependentType())
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000011672 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000011673 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000011674 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011675 }
11676
Douglas Gregor43c7bad2008-11-17 16:14:12 +000011677 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011678}
Chris Lattner5a003a42008-12-17 07:09:26 +000011679
Sean Hunta6c058d2010-01-13 09:01:02 +000011680/// CheckLiteralOperatorDeclaration - Check whether the declaration
11681/// of this literal operator function is well-formed. If so, returns
11682/// false; otherwise, emits appropriate diagnostics and returns true.
11683bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000011684 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000011685 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11686 << FnDecl->getDeclName();
11687 return true;
11688 }
11689
Richard Smithb4a7b1e2012-03-04 09:41:16 +000011690 if (FnDecl->isExternC()) {
11691 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11692 return true;
11693 }
11694
Sean Hunta6c058d2010-01-13 09:01:02 +000011695 bool Valid = false;
11696
Richard Smith36f5cfe2012-03-09 08:00:36 +000011697 // This might be the definition of a literal operator template.
11698 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11699 // This might be a specialization of a literal operator template.
11700 if (!TpDecl)
11701 TpDecl = FnDecl->getPrimaryTemplate();
11702
Richard Smithb328e292013-10-07 19:57:58 +000011703 // template <char...> type operator "" name() and
11704 // template <class T, T...> type operator "" name() are the only valid
11705 // template signatures, and the only valid signatures with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000011706 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000011707 if (FnDecl->param_size() == 0) {
Richard Smithb328e292013-10-07 19:57:58 +000011708 // Must have one or two template parameters
Sean Hunt216c2782010-04-07 23:11:06 +000011709 TemplateParameterList *Params = TpDecl->getTemplateParameters();
11710 if (Params->size() == 1) {
11711 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000011712 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000011713
Sean Hunt216c2782010-04-07 23:11:06 +000011714 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000011715 if (PmDecl && PmDecl->isTemplateParameterPack() &&
11716 Context.hasSameType(PmDecl->getType(), Context.CharTy))
11717 Valid = true;
Richard Smithb328e292013-10-07 19:57:58 +000011718 } else if (Params->size() == 2) {
11719 TemplateTypeParmDecl *PmType =
11720 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11721 NonTypeTemplateParmDecl *PmArgs =
11722 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11723
11724 // The second template parameter must be a parameter pack with the
11725 // first template parameter as its type.
11726 if (PmType && PmArgs &&
11727 !PmType->isTemplateParameterPack() &&
11728 PmArgs->isTemplateParameterPack()) {
11729 const TemplateTypeParmType *TArgs =
11730 PmArgs->getType()->getAs<TemplateTypeParmType>();
11731 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11732 TArgs->getIndex() == PmType->getIndex()) {
11733 Valid = true;
11734 if (ActiveTemplateInstantiations.empty())
11735 Diag(FnDecl->getLocation(),
11736 diag::ext_string_literal_operator_template);
11737 }
11738 }
Sean Hunt216c2782010-04-07 23:11:06 +000011739 }
11740 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000011741 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000011742 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000011743 FunctionDecl::param_iterator Param = FnDecl->param_begin();
11744
Richard Smithb4a7b1e2012-03-04 09:41:16 +000011745 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000011746
Sean Hunt30019c02010-04-07 22:57:35 +000011747 // unsigned long long int, long double, and any character type are allowed
11748 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000011749 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11750 Context.hasSameType(T, Context.LongDoubleTy) ||
11751 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000011752 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000011753 Context.hasSameType(T, Context.Char16Ty) ||
11754 Context.hasSameType(T, Context.Char32Ty)) {
11755 if (++Param == FnDecl->param_end())
11756 Valid = true;
11757 goto FinishedParams;
11758 }
11759
Sean Hunt30019c02010-04-07 22:57:35 +000011760 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000011761 const PointerType *PT = T->getAs<PointerType>();
11762 if (!PT)
11763 goto FinishedParams;
11764 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000011765 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000011766 goto FinishedParams;
11767 T = T.getUnqualifiedType();
11768
11769 // Move on to the second parameter;
11770 ++Param;
11771
11772 // If there is no second parameter, the first must be a const char *
11773 if (Param == FnDecl->param_end()) {
11774 if (Context.hasSameType(T, Context.CharTy))
11775 Valid = true;
11776 goto FinishedParams;
11777 }
11778
11779 // const char *, const wchar_t*, const char16_t*, and const char32_t*
11780 // are allowed as the first parameter to a two-parameter function
11781 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000011782 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000011783 Context.hasSameType(T, Context.Char16Ty) ||
11784 Context.hasSameType(T, Context.Char32Ty)))
11785 goto FinishedParams;
11786
11787 // The second and final parameter must be an std::size_t
11788 T = (*Param)->getType().getUnqualifiedType();
11789 if (Context.hasSameType(T, Context.getSizeType()) &&
11790 ++Param == FnDecl->param_end())
11791 Valid = true;
11792 }
11793
11794 // FIXME: This diagnostic is absolutely terrible.
11795FinishedParams:
11796 if (!Valid) {
11797 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11798 << FnDecl->getDeclName();
11799 return true;
11800 }
11801
Richard Smitha9e88b22012-03-09 08:16:22 +000011802 // A parameter-declaration-clause containing a default argument is not
11803 // equivalent to any of the permitted forms.
Stephen Hines651f13c2014-04-23 16:59:28 -070011804 for (auto Param : FnDecl->params()) {
11805 if (Param->hasDefaultArg()) {
11806 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smitha9e88b22012-03-09 08:16:22 +000011807 diag::err_literal_operator_default_argument)
Stephen Hines651f13c2014-04-23 16:59:28 -070011808 << Param->getDefaultArgRange();
Richard Smitha9e88b22012-03-09 08:16:22 +000011809 break;
11810 }
11811 }
11812
Richard Smith2fb4ae32012-03-08 02:39:21 +000011813 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000011814 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11815 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000011816 // C++11 [usrlit.suffix]p1:
11817 // Literal suffix identifiers that do not start with an underscore
11818 // are reserved for future standardization.
Richard Smith4ac537b2013-07-23 08:14:48 +000011819 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11820 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor1155c422011-08-30 22:40:35 +000011821 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000011822
Sean Hunta6c058d2010-01-13 09:01:02 +000011823 return false;
11824}
11825
Douglas Gregor074149e2009-01-05 19:45:36 +000011826/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11827/// linkage specification, including the language and (if present)
Stephen Hines651f13c2014-04-23 16:59:28 -070011828/// the '{'. ExternLoc is the location of the 'extern', Lang is the
11829/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor074149e2009-01-05 19:45:36 +000011830/// the '{' brace. Otherwise, this linkage specification does not
11831/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000011832Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Stephen Hines651f13c2014-04-23 16:59:28 -070011833 Expr *LangStr,
Chris Lattner7d642712010-11-09 20:15:55 +000011834 SourceLocation LBraceLoc) {
Stephen Hines651f13c2014-04-23 16:59:28 -070011835 StringLiteral *Lit = cast<StringLiteral>(LangStr);
11836 if (!Lit->isAscii()) {
11837 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11838 << LangStr->getSourceRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011839 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -070011840 }
11841
11842 StringRef Lang = Lit->getString();
Chris Lattnercc98eac2008-12-17 07:13:27 +000011843 LinkageSpecDecl::LanguageIDs Language;
Stephen Hines651f13c2014-04-23 16:59:28 -070011844 if (Lang == "C")
Chris Lattnercc98eac2008-12-17 07:13:27 +000011845 Language = LinkageSpecDecl::lang_c;
Stephen Hines651f13c2014-04-23 16:59:28 -070011846 else if (Lang == "C++")
Chris Lattnercc98eac2008-12-17 07:13:27 +000011847 Language = LinkageSpecDecl::lang_cxx;
11848 else {
Stephen Hines651f13c2014-04-23 16:59:28 -070011849 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11850 << LangStr->getSourceRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011851 return nullptr;
Chris Lattnercc98eac2008-12-17 07:13:27 +000011852 }
Mike Stump1eb44332009-09-09 15:08:12 +000011853
Chris Lattnercc98eac2008-12-17 07:13:27 +000011854 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000011855
Stephen Hines651f13c2014-04-23 16:59:28 -070011856 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11857 LangStr->getExprLoc(), Language,
Rafael Espindolae5e575d2013-04-26 01:30:23 +000011858 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011859 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000011860 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000011861 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000011862}
11863
Abramo Bagnara35f9a192010-07-30 16:47:02 +000011864/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000011865/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11866/// valid, it's the position of the closing '}' brace in a linkage
11867/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000011868Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000011869 Decl *LinkageSpec,
11870 SourceLocation RBraceLoc) {
Stephen Hines651f13c2014-04-23 16:59:28 -070011871 if (RBraceLoc.isValid()) {
11872 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11873 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000011874 }
Stephen Hines651f13c2014-04-23 16:59:28 -070011875 PopDeclContext();
Douglas Gregor074149e2009-01-05 19:45:36 +000011876 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000011877}
11878
Michael Han684aa732013-02-22 17:15:32 +000011879Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11880 AttributeList *AttrList,
11881 SourceLocation SemiLoc) {
11882 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11883 // Attribute declarations appertain to empty declaration so we handle
11884 // them here.
11885 if (AttrList)
11886 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000011887
Michael Han684aa732013-02-22 17:15:32 +000011888 CurContext->addDecl(ED);
11889 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000011890}
11891
Douglas Gregord308e622009-05-18 20:51:54 +000011892/// \brief Perform semantic analysis for the variable declaration that
11893/// occurs within a C++ catch clause, returning the newly-created
11894/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011895VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000011896 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011897 SourceLocation StartLoc,
11898 SourceLocation Loc,
11899 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000011900 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000011901 QualType ExDeclType = TInfo->getType();
11902
Sebastian Redl4b07b292008-12-22 19:15:10 +000011903 // Arrays and functions decay.
11904 if (ExDeclType->isArrayType())
11905 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11906 else if (ExDeclType->isFunctionType())
11907 ExDeclType = Context.getPointerType(ExDeclType);
11908
11909 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11910 // The exception-declaration shall not denote a pointer or reference to an
11911 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000011912 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000011913 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000011914 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000011915 Invalid = true;
11916 }
Douglas Gregord308e622009-05-18 20:51:54 +000011917
Sebastian Redl4b07b292008-12-22 19:15:10 +000011918 QualType BaseType = ExDeclType;
11919 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000011920 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000011921 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000011922 BaseType = Ptr->getPointeeType();
11923 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000011924 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000011925 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000011926 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000011927 BaseType = Ref->getPointeeType();
11928 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000011929 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011930 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000011931 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000011932 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000011933 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011934
Mike Stump1eb44332009-09-09 15:08:12 +000011935 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000011936 RequireNonAbstractType(Loc, ExDeclType,
11937 diag::err_abstract_type_in_decl,
11938 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000011939 Invalid = true;
11940
John McCall5a180392010-07-24 00:37:23 +000011941 // Only the non-fragile NeXT runtime currently supports C++ catches
11942 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000011943 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000011944 QualType T = ExDeclType;
11945 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11946 T = RT->getPointeeType();
11947
11948 if (T->isObjCObjectType()) {
11949 Diag(Loc, diag::err_objc_object_catch);
11950 Invalid = true;
11951 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000011952 // FIXME: should this be a test for macosx-fragile specifically?
11953 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000011954 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000011955 }
11956 }
11957
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011958 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000011959 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000011960 ExDecl->setExceptionVariable(true);
11961
Douglas Gregor9aab9c42011-12-10 01:22:52 +000011962 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000011963 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000011964 Invalid = true;
11965
Douglas Gregorc41b8782011-07-06 18:14:43 +000011966 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000011967 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000011968 // Insulate this from anything else we might currently be parsing.
11969 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11970
Douglas Gregor6d182892010-03-05 23:38:39 +000011971 // C++ [except.handle]p16:
Nick Lewyckyee0bc3b2013-09-22 10:06:57 +000011972 // The object declared in an exception-declaration or, if the
11973 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6d182892010-03-05 23:38:39 +000011974 // copy-initialized (8.5) from the exception object. [...]
11975 // The object is destroyed when the handler exits, after the destruction
11976 // of any automatic objects initialized within the handler.
11977 //
Nick Lewyckyee0bc3b2013-09-22 10:06:57 +000011978 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6d182892010-03-05 23:38:39 +000011979 // it can be destroyed later.
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -070011980 QualType initType = Context.getExceptionObjectType(ExDeclType);
John McCalle996ffd2011-02-16 08:02:54 +000011981
11982 InitializedEntity entity =
11983 InitializedEntity::InitializeVariable(ExDecl);
11984 InitializationKind initKind =
11985 InitializationKind::CreateCopy(Loc, SourceLocation());
11986
11987 Expr *opaqueValue =
11988 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +000011989 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11990 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCalle996ffd2011-02-16 08:02:54 +000011991 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000011992 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000011993 else {
11994 // If the constructor used was non-trivial, set this as the
11995 // "initializer".
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011996 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
John McCalle996ffd2011-02-16 08:02:54 +000011997 if (!construct->getConstructor()->isTrivial()) {
11998 Expr *init = MaybeCreateExprWithCleanups(construct);
11999 ExDecl->setInit(init);
12000 }
12001
12002 // And make sure it's destructable.
12003 FinalizeVarWithDestructor(ExDecl, recordType);
12004 }
Douglas Gregor6d182892010-03-05 23:38:39 +000012005 }
12006 }
12007
Douglas Gregord308e622009-05-18 20:51:54 +000012008 if (Invalid)
12009 ExDecl->setInvalidDecl();
12010
12011 return ExDecl;
12012}
12013
12014/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
12015/// handler.
John McCalld226f652010-08-21 09:40:31 +000012016Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000012017 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000012018 bool Invalid = D.isInvalidType();
12019
12020 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000012021 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12022 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000012023 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12024 D.getIdentifierLoc());
12025 Invalid = true;
12026 }
12027
Sebastian Redl4b07b292008-12-22 19:15:10 +000012028 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000012029 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000012030 LookupOrdinaryName,
12031 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000012032 // The scope should be freshly made just for us. There is just no way
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012033 // it contains any previous declaration, except for function parameters in
12034 // a function-try-block's catch statement.
John McCalld226f652010-08-21 09:40:31 +000012035 assert(!S->isDeclScope(PrevDecl));
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012036 if (isDeclInScope(PrevDecl, CurContext, S)) {
12037 Diag(D.getIdentifierLoc(), diag::err_redefinition)
12038 << D.getIdentifier();
12039 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12040 Invalid = true;
12041 } else if (PrevDecl->isTemplateParameter())
Sebastian Redl4b07b292008-12-22 19:15:10 +000012042 // Maybe we will complain about the shadowed template parameter.
12043 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000012044 }
12045
Chris Lattnereaaebc72009-04-25 08:06:05 +000012046 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000012047 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
12048 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000012049 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000012050 }
12051
Douglas Gregor83cb9422010-09-09 17:09:21 +000012052 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000012053 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000012054 D.getIdentifierLoc(),
12055 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000012056 if (Invalid)
12057 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000012058
Sebastian Redl4b07b292008-12-22 19:15:10 +000012059 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000012060 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000012061 PushOnScopeChains(ExDecl, S);
12062 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000012063 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000012064
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000012065 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000012066 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000012067}
Anders Carlssonfb311762009-03-14 00:25:26 +000012068
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000012069Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000012070 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000012071 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000012072 SourceLocation RParenLoc) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012073 StringLiteral *AssertMessage =
12074 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
Anders Carlssonfb311762009-03-14 00:25:26 +000012075
Richard Smithe3f470a2012-07-11 22:37:56 +000012076 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012077 return nullptr;
Richard Smithe3f470a2012-07-11 22:37:56 +000012078
12079 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
12080 AssertMessage, RParenLoc, false);
12081}
12082
12083Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12084 Expr *AssertExpr,
12085 StringLiteral *AssertMessage,
12086 SourceLocation RParenLoc,
12087 bool Failed) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012088 assert(AssertExpr != nullptr && "Expected non-null condition");
Richard Smithe3f470a2012-07-11 22:37:56 +000012089 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
12090 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000012091 // In a static_assert-declaration, the constant-expression shall be a
12092 // constant expression that can be contextually converted to bool.
12093 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
12094 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000012095 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000012096
Richard Smithdaaefc52011-12-14 23:32:26 +000012097 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000012098 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000012099 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000012100 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000012101 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000012102
Richard Smithe3f470a2012-07-11 22:37:56 +000012103 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012104 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000012105 llvm::raw_svector_ostream Msg(MsgBuffer);
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012106 if (AssertMessage)
12107 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000012108 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012109 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000012110 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000012111 }
Anders Carlssonc3082412009-03-14 00:33:21 +000012112 }
Mike Stump1eb44332009-09-09 15:08:12 +000012113
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000012114 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000012115 AssertExpr, AssertMessage, RParenLoc,
12116 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000012117
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000012118 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000012119 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000012120}
Sebastian Redl50de12f2009-03-24 22:27:57 +000012121
Douglas Gregor1d869352010-04-07 16:53:43 +000012122/// \brief Perform semantic analysis of the given friend type declaration.
12123///
12124/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000012125FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000012126 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000012127 TypeSourceInfo *TSInfo) {
12128 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
12129
12130 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000012131 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000012132
Richard Smith6b130222011-10-18 21:39:00 +000012133 // C++03 [class.friend]p2:
12134 // An elaborated-type-specifier shall be used in a friend declaration
12135 // for a class.*
12136 //
12137 // * The class-key of the elaborated-type-specifier is required.
12138 if (!ActiveTemplateInstantiations.empty()) {
12139 // Do not complain about the form of friend template types during
12140 // template instantiation; we will already have complained when the
12141 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000012142 } else {
12143 if (!T->isElaboratedTypeSpecifier()) {
12144 // If we evaluated the type to a record type, suggest putting
12145 // a tag in front.
12146 if (const RecordType *RT = T->getAs<RecordType>()) {
12147 RecordDecl *RD = RT->getDecl();
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012148
12149 SmallString<16> InsertionText(" ");
12150 InsertionText += RD->getKindName();
12151
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000012152 Diag(TypeRange.getBegin(),
12153 getLangOpts().CPlusPlus11 ?
12154 diag::warn_cxx98_compat_unelaborated_friend_type :
12155 diag::ext_unelaborated_friend_type)
12156 << (unsigned) RD->getTagKind()
12157 << T
12158 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
12159 InsertionText);
12160 } else {
12161 Diag(FriendLoc,
12162 getLangOpts().CPlusPlus11 ?
12163 diag::warn_cxx98_compat_nonclass_type_friend :
12164 diag::ext_nonclass_type_friend)
12165 << T
12166 << TypeRange;
12167 }
12168 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000012169 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000012170 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000012171 diag::warn_cxx98_compat_enum_friend :
12172 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000012173 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000012174 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000012175 }
Douglas Gregor1d869352010-04-07 16:53:43 +000012176
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000012177 // C++11 [class.friend]p3:
12178 // A friend declaration that does not declare a function shall have one
12179 // of the following forms:
12180 // friend elaborated-type-specifier ;
12181 // friend simple-type-specifier ;
12182 // friend typename-specifier ;
12183 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
12184 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
12185 }
Richard Smithd6f80da2012-09-20 01:31:00 +000012186
Douglas Gregor06245bf2010-04-07 17:57:12 +000012187 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000012188 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000012189 // the friend declaration is ignored.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012190 return FriendDecl::Create(Context, CurContext,
12191 TSInfo->getTypeLoc().getLocStart(), TSInfo,
12192 FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000012193}
12194
John McCall9a34edb2010-10-19 01:40:49 +000012195/// Handle a friend tag declaration where the scope specifier was
12196/// templated.
12197Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
12198 unsigned TagSpec, SourceLocation TagLoc,
12199 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000012200 IdentifierInfo *Name,
12201 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000012202 AttributeList *Attr,
12203 MultiTemplateParamsArg TempParamLists) {
12204 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12205
12206 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000012207 bool Invalid = false;
12208
Robert Wilhelm1169e2f2013-07-21 15:20:44 +000012209 if (TemplateParameterList *TemplateParams =
12210 MatchTemplateParametersToScopeSpecifier(
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012211 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
Robert Wilhelm1169e2f2013-07-21 15:20:44 +000012212 isExplicitSpecialization, Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000012213 if (TemplateParams->size() > 0) {
12214 // This is a declaration of a class template.
12215 if (Invalid)
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012216 return nullptr;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000012217
Stephen Hines176edba2014-12-01 14:53:08 -080012218 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
12219 NameLoc, Attr, TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000012220 /*ModulePrivateLoc=*/SourceLocation(),
Stephen Hines176edba2014-12-01 14:53:08 -080012221 FriendLoc, TempParamLists.size() - 1,
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012222 TempParamLists.data()).get();
John McCall9a34edb2010-10-19 01:40:49 +000012223 } else {
12224 // The "template<>" header is extraneous.
12225 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12226 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12227 isExplicitSpecialization = true;
12228 }
12229 }
12230
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012231 if (Invalid) return nullptr;
John McCall9a34edb2010-10-19 01:40:49 +000012232
John McCall9a34edb2010-10-19 01:40:49 +000012233 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000012234 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000012235 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000012236 isAllExplicitSpecializations = false;
12237 break;
12238 }
12239 }
12240
12241 // FIXME: don't ignore attributes.
12242
12243 // If it's explicit specializations all the way down, just forget
12244 // about the template header and build an appropriate non-templated
12245 // friend. TODO: for source fidelity, remember the headers.
12246 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000012247 if (SS.isEmpty()) {
12248 bool Owned = false;
12249 bool IsDependent = false;
12250 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Stephen Hines651f13c2014-04-23 16:59:28 -070012251 Attr, AS_public,
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000012252 /*ModulePrivateLoc=*/SourceLocation(),
Stephen Hines651f13c2014-04-23 16:59:28 -070012253 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000012254 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000012255 /*ScopedEnumUsesClassTag=*/false,
Stephen Hines651f13c2014-04-23 16:59:28 -070012256 /*UnderlyingType=*/TypeResult(),
12257 /*IsTypeSpecifier=*/false);
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000012258 }
Stephen Hines651f13c2014-04-23 16:59:28 -070012259
Douglas Gregor2494dd02011-03-01 01:34:45 +000012260 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000012261 ElaboratedTypeKeyword Keyword
12262 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000012263 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000012264 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000012265 if (T.isNull())
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012266 return nullptr;
John McCall9a34edb2010-10-19 01:40:49 +000012267
12268 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12269 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000012270 DependentNameTypeLoc TL =
12271 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000012272 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000012273 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000012274 TL.setNameLoc(NameLoc);
12275 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000012276 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000012277 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000012278 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000012279 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000012280 }
12281
12282 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000012283 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000012284 Friend->setAccess(AS_public);
12285 CurContext->addDecl(Friend);
12286 return Friend;
12287 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000012288
12289 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
12290
12291
John McCall9a34edb2010-10-19 01:40:49 +000012292
12293 // Handle the case of a templated-scope friend class. e.g.
12294 // template <class T> class A<T>::B;
12295 // FIXME: we don't support these right now.
Richard Smithce6426f2013-11-08 18:59:56 +000012296 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
12297 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCall9a34edb2010-10-19 01:40:49 +000012298 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12299 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
12300 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000012301 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000012302 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000012303 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000012304 TL.setNameLoc(NameLoc);
12305
12306 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000012307 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000012308 Friend->setAccess(AS_public);
12309 Friend->setUnsupportedFriend(true);
12310 CurContext->addDecl(Friend);
12311 return Friend;
12312}
12313
12314
John McCalldd4a3b02009-09-16 22:47:08 +000012315/// Handle a friend type declaration. This works in tandem with
12316/// ActOnTag.
12317///
12318/// Notes on friend class templates:
12319///
12320/// We generally treat friend class declarations as if they were
12321/// declaring a class. So, for example, the elaborated type specifier
12322/// in a friend declaration is required to obey the restrictions of a
12323/// class-head (i.e. no typedefs in the scope chain), template
12324/// parameters are required to match up with simple template-ids, &c.
12325/// However, unlike when declaring a template specialization, it's
12326/// okay to refer to a template specialization without an empty
12327/// template parameter declaration, e.g.
12328/// friend class A<T>::B<unsigned>;
12329/// We permit this as a special case; if there are any template
12330/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000012331/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000012332Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000012333 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000012334 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000012335
12336 assert(DS.isFriendSpecified());
12337 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12338
John McCalldd4a3b02009-09-16 22:47:08 +000012339 // Try to convert the decl specifier to a type. This works for
12340 // friend templates because ActOnTag never produces a ClassTemplateDecl
12341 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000012342 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000012343 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
12344 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000012345 if (TheDeclarator.isInvalidType())
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012346 return nullptr;
John McCall67d1a672009-08-06 02:15:43 +000012347
Douglas Gregor6ccab972010-12-16 01:14:37 +000012348 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012349 return nullptr;
Douglas Gregor6ccab972010-12-16 01:14:37 +000012350
John McCalldd4a3b02009-09-16 22:47:08 +000012351 // This is definitely an error in C++98. It's probably meant to
12352 // be forbidden in C++0x, too, but the specification is just
12353 // poorly written.
12354 //
12355 // The problem is with declarations like the following:
12356 // template <T> friend A<T>::foo;
12357 // where deciding whether a class C is a friend or not now hinges
12358 // on whether there exists an instantiation of A that causes
12359 // 'foo' to equal C. There are restrictions on class-heads
12360 // (which we declare (by fiat) elaborated friend declarations to
12361 // be) that makes this tractable.
12362 //
12363 // FIXME: handle "template <> friend class A<T>;", which
12364 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000012365 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000012366 Diag(Loc, diag::err_tagless_friend_type_template)
12367 << DS.getSourceRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012368 return nullptr;
John McCalldd4a3b02009-09-16 22:47:08 +000012369 }
Douglas Gregor1d869352010-04-07 16:53:43 +000012370
John McCall02cace72009-08-28 07:59:38 +000012371 // C++98 [class.friend]p1: A friend of a class is a function
12372 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000012373 // This is fixed in DR77, which just barely didn't make the C++03
12374 // deadline. It's also a very silly restriction that seriously
12375 // affects inner classes and which nobody else seems to implement;
12376 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000012377 //
12378 // But note that we could warn about it: it's always useless to
12379 // friend one of your own members (it's not, however, worthless to
12380 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000012381
John McCalldd4a3b02009-09-16 22:47:08 +000012382 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000012383 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000012384 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000012385 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000012386 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000012387 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000012388 DS.getFriendSpecLoc());
12389 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000012390 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000012391
12392 if (!D)
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012393 return nullptr;
12394
John McCalldd4a3b02009-09-16 22:47:08 +000012395 D->setAccess(AS_public);
12396 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000012397
John McCalld226f652010-08-21 09:40:31 +000012398 return D;
John McCall02cace72009-08-28 07:59:38 +000012399}
12400
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000012401NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
12402 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000012403 const DeclSpec &DS = D.getDeclSpec();
12404
12405 assert(DS.isFriendSpecified());
12406 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12407
12408 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000012409 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000012410
12411 // C++ [class.friend]p1
12412 // A friend of a class is a function or class....
12413 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000012414 // It *doesn't* see through dependent types, which is correct
12415 // according to [temp.arg.type]p3:
12416 // If a declaration acquires a function type through a
12417 // type dependent on a template-parameter and this causes
12418 // a declaration that does not use the syntactic form of a
12419 // function declarator to have a function type, the program
12420 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000012421 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000012422 Diag(Loc, diag::err_unexpected_friend);
12423
12424 // It might be worthwhile to try to recover by creating an
12425 // appropriate declaration.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012426 return nullptr;
John McCall67d1a672009-08-06 02:15:43 +000012427 }
12428
12429 // C++ [namespace.memdef]p3
12430 // - If a friend declaration in a non-local class first declares a
12431 // class or function, the friend class or function is a member
12432 // of the innermost enclosing namespace.
12433 // - The name of the friend is not found by simple name lookup
12434 // until a matching declaration is provided in that namespace
12435 // scope (either before or after the class declaration granting
12436 // friendship).
12437 // - If a friend function is called, its name may be found by the
12438 // name lookup that considers functions from namespaces and
12439 // classes associated with the types of the function arguments.
12440 // - When looking for a prior declaration of a class or a function
12441 // declared as a friend, scopes outside the innermost enclosing
12442 // namespace scope are not considered.
12443
John McCall337ec3d2010-10-12 23:13:28 +000012444 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000012445 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
12446 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000012447 assert(Name);
12448
Douglas Gregor6ccab972010-12-16 01:14:37 +000012449 // Check for unexpanded parameter packs.
12450 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
12451 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
12452 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012453 return nullptr;
Douglas Gregor6ccab972010-12-16 01:14:37 +000012454
John McCall67d1a672009-08-06 02:15:43 +000012455 // The context we found the declaration in, or in which we should
12456 // create the declaration.
12457 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000012458 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000012459 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000012460 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000012461
Richard Smith4e9686b2013-08-09 04:35:01 +000012462 // There are five cases here.
12463 // - There's no scope specifier and we're in a local class. Only look
12464 // for functions declared in the immediately-enclosing block scope.
12465 // We recover from invalid scope qualifiers as if they just weren't there.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012466 FunctionDecl *FunctionContainingLocalClass = nullptr;
Richard Smith4e9686b2013-08-09 04:35:01 +000012467 if ((SS.isInvalid() || !SS.isSet()) &&
12468 (FunctionContainingLocalClass =
12469 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
12470 // C++11 [class.friend]p11:
John McCall29ae6e52010-10-13 05:45:15 +000012471 // If a friend declaration appears in a local class and the name
12472 // specified is an unqualified name, a prior declaration is
12473 // looked up without considering scopes that are outside the
12474 // innermost enclosing non-class scope. For a friend function
12475 // declaration, if there is no prior declaration, the program is
12476 // ill-formed.
Richard Smith4e9686b2013-08-09 04:35:01 +000012477
12478 // Find the innermost enclosing non-class scope. This is the block
12479 // scope containing the local class definition (or for a nested class,
12480 // the outer local class).
12481 DCScope = S->getFnParent();
12482
12483 // Look up the function name in the scope.
12484 Previous.clear(LookupLocalFriendName);
12485 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
12486
12487 if (!Previous.empty()) {
12488 // All possible previous declarations must have the same context:
12489 // either they were declared at block scope or they are members of
12490 // one of the enclosing local classes.
12491 DC = Previous.getRepresentativeDecl()->getDeclContext();
12492 } else {
12493 // This is ill-formed, but provide the context that we would have
12494 // declared the function in, if we were permitted to, for error recovery.
12495 DC = FunctionContainingLocalClass;
12496 }
Richard Smitha41c97a2013-09-20 01:15:31 +000012497 adjustContextForLocalExternDecl(DC);
Richard Smith4e9686b2013-08-09 04:35:01 +000012498
12499 // C++ [class.friend]p6:
12500 // A function can be defined in a friend declaration of a class if and
12501 // only if the class is a non-local class (9.8), the function name is
12502 // unqualified, and the function has namespace scope.
12503 if (D.isFunctionDefinition()) {
12504 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12505 }
12506
12507 // - There's no scope specifier, in which case we just go to the
12508 // appropriate scope and look for a function or function template
12509 // there as appropriate.
12510 } else if (SS.isInvalid() || !SS.isSet()) {
12511 // C++11 [namespace.memdef]p3:
12512 // If the name in a friend declaration is neither qualified nor
12513 // a template-id and the declaration is a function or an
12514 // elaborated-type-specifier, the lookup to determine whether
12515 // the entity has been previously declared shall not consider
12516 // any scopes outside the innermost enclosing namespace.
John McCall8a407372010-10-14 22:22:28 +000012517 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000012518
John McCall29ae6e52010-10-13 05:45:15 +000012519 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000012520 DC = CurContext;
John McCall67d1a672009-08-06 02:15:43 +000012521
Rafael Espindola11dc6342013-04-25 20:12:36 +000012522 // Skip class contexts. If someone can cite chapter and verse
12523 // for this behavior, that would be nice --- it's what GCC and
12524 // EDG do, and it seems like a reasonable intent, but the spec
12525 // really only says that checks for unqualified existing
12526 // declarations should stop at the nearest enclosing namespace,
12527 // not that they should only consider the nearest enclosing
12528 // namespace.
12529 while (DC->isRecord())
12530 DC = DC->getParent();
12531
12532 DeclContext *LookupDC = DC;
12533 while (LookupDC->isTransparentContext())
12534 LookupDC = LookupDC->getParent();
12535
12536 while (true) {
12537 LookupQualifiedName(Previous, LookupDC);
John McCall67d1a672009-08-06 02:15:43 +000012538
Rafael Espindola11dc6342013-04-25 20:12:36 +000012539 if (!Previous.empty()) {
12540 DC = LookupDC;
12541 break;
John McCall8a407372010-10-14 22:22:28 +000012542 }
Rafael Espindola11dc6342013-04-25 20:12:36 +000012543
12544 if (isTemplateId) {
12545 if (isa<TranslationUnitDecl>(LookupDC)) break;
12546 } else {
12547 if (LookupDC->isFileContext()) break;
12548 }
12549 LookupDC = LookupDC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000012550 }
12551
John McCall380aaa42010-10-13 06:22:15 +000012552 DCScope = getScopeForDeclContext(S, DC);
Richard Smith4e9686b2013-08-09 04:35:01 +000012553
John McCall337ec3d2010-10-12 23:13:28 +000012554 // - There's a non-dependent scope specifier, in which case we
12555 // compute it and do a previous lookup there for a function
12556 // or function template.
12557 } else if (!SS.getScopeRep()->isDependent()) {
12558 DC = computeDeclContext(SS);
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012559 if (!DC) return nullptr;
John McCall337ec3d2010-10-12 23:13:28 +000012560
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012561 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
John McCall337ec3d2010-10-12 23:13:28 +000012562
12563 LookupQualifiedName(Previous, DC);
12564
12565 // Ignore things found implicitly in the wrong scope.
12566 // TODO: better diagnostics for this case. Suggesting the right
12567 // qualified scope would be nice...
12568 LookupResult::Filter F = Previous.makeFilter();
12569 while (F.hasNext()) {
12570 NamedDecl *D = F.next();
12571 if (!DC->InEnclosingNamespaceSetOf(
12572 D->getDeclContext()->getRedeclContext()))
12573 F.erase();
12574 }
12575 F.done();
12576
12577 if (Previous.empty()) {
12578 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000012579 Diag(Loc, diag::err_qualified_friend_not_found)
12580 << Name << TInfo->getType();
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012581 return nullptr;
John McCall337ec3d2010-10-12 23:13:28 +000012582 }
12583
12584 // C++ [class.friend]p1: A friend of a class is a function or
12585 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000012586 if (DC->Equals(CurContext))
12587 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000012588 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000012589 diag::warn_cxx98_compat_friend_is_member :
12590 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000012591
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000012592 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000012593 // C++ [class.friend]p6:
12594 // A function can be defined in a friend declaration of a class if and
12595 // only if the class is a non-local class (9.8), the function name is
12596 // unqualified, and the function has namespace scope.
12597 SemaDiagnosticBuilder DB
12598 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12599
12600 DB << SS.getScopeRep();
12601 if (DC->isFileContext())
12602 DB << FixItHint::CreateRemoval(SS.getRange());
12603 SS.clear();
12604 }
John McCall337ec3d2010-10-12 23:13:28 +000012605
12606 // - There's a scope specifier that does not match any template
12607 // parameter lists, in which case we use some arbitrary context,
12608 // create a method or method template, and wait for instantiation.
12609 // - There's a scope specifier that does match some template
12610 // parameter lists, which we don't handle right now.
12611 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000012612 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000012613 // C++ [class.friend]p6:
12614 // A function can be defined in a friend declaration of a class if and
12615 // only if the class is a non-local class (9.8), the function name is
12616 // unqualified, and the function has namespace scope.
12617 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12618 << SS.getScopeRep();
12619 }
12620
John McCall337ec3d2010-10-12 23:13:28 +000012621 DC = CurContext;
12622 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000012623 }
Douglas Gregor883af832011-10-10 01:11:59 +000012624
John McCall29ae6e52010-10-13 05:45:15 +000012625 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000012626 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000012627 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
12628 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
12629 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000012630 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000012631 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
12632 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012633 return nullptr;
John McCall67d1a672009-08-06 02:15:43 +000012634 }
John McCall67d1a672009-08-06 02:15:43 +000012635 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000012636
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000012637 // FIXME: This is an egregious hack to cope with cases where the scope stack
12638 // does not contain the declaration context, i.e., in an out-of-line
12639 // definition of a class.
12640 Scope FakeDCScope(S, Scope::DeclScope, Diags);
12641 if (!DCScope) {
12642 FakeDCScope.setEntity(DC);
12643 DCScope = &FakeDCScope;
12644 }
Richard Smith4e9686b2013-08-09 04:35:01 +000012645
Francois Pichetaf0f4d02011-08-14 03:52:19 +000012646 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000012647 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000012648 TemplateParams, AddToScope);
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012649 if (!ND) return nullptr;
John McCallab88d972009-08-31 22:39:49 +000012650
Douglas Gregor182ddf02009-09-28 00:08:27 +000012651 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000012652
Richard Smith4e9686b2013-08-09 04:35:01 +000012653 // If we performed typo correction, we might have added a scope specifier
12654 // and changed the decl context.
12655 DC = ND->getDeclContext();
12656
John McCallab88d972009-08-31 22:39:49 +000012657 // Add the function declaration to the appropriate lookup tables,
12658 // adjusting the redeclarations list as necessary. We don't
12659 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000012660 //
John McCallab88d972009-08-31 22:39:49 +000012661 // Also update the scope-based lookup if the target context's
12662 // lookup context is in lexical scope.
12663 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000012664 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000012665 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000012666 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000012667 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000012668 }
John McCall02cace72009-08-28 07:59:38 +000012669
12670 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000012671 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000012672 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000012673 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000012674 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000012675
John McCall1f2e1a92012-08-10 03:15:35 +000012676 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000012677 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000012678 } else {
12679 if (DC->isRecord()) CheckFriendAccess(ND);
12680
John McCall6102ca12010-10-16 06:59:13 +000012681 FunctionDecl *FD;
12682 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12683 FD = FTD->getTemplatedDecl();
12684 else
12685 FD = cast<FunctionDecl>(ND);
12686
David Majnemerf6a144f2013-06-25 23:09:30 +000012687 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12688 // default argument expression, that declaration shall be a definition
12689 // and shall be the only declaration of the function or function
12690 // template in the translation unit.
12691 if (functionDeclHasDefaultArgument(FD)) {
12692 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12693 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12694 Diag(OldFD->getLocation(), diag::note_previous_declaration);
12695 } else if (!D.isFunctionDefinition())
12696 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12697 }
12698
John McCall6102ca12010-10-16 06:59:13 +000012699 // Mark templated-scope function declarations as unsupported.
Stephen Hines176edba2014-12-01 14:53:08 -080012700 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
12701 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
12702 << SS.getScopeRep() << SS.getRange()
12703 << cast<CXXRecordDecl>(CurContext);
John McCall6102ca12010-10-16 06:59:13 +000012704 FrD->setUnsupportedFriend(true);
Stephen Hines176edba2014-12-01 14:53:08 -080012705 }
John McCall6102ca12010-10-16 06:59:13 +000012706 }
John McCall337ec3d2010-10-12 23:13:28 +000012707
John McCalld226f652010-08-21 09:40:31 +000012708 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000012709}
12710
John McCalld226f652010-08-21 09:40:31 +000012711void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12712 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000012713
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000012714 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000012715 if (!Fn) {
12716 Diag(DelLoc, diag::err_deleted_non_function);
12717 return;
12718 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000012719
Douglas Gregoref96ee02012-01-14 16:38:05 +000012720 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000012721 // Don't consider the implicit declaration we generate for explicit
12722 // specializations. FIXME: Do not generate these implicit declarations.
Stephen Hines651f13c2014-04-23 16:59:28 -070012723 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12724 Prev->getPreviousDecl()) &&
12725 !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000012726 Diag(DelLoc, diag::err_deleted_decl_not_first);
Stephen Hines651f13c2014-04-23 16:59:28 -070012727 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12728 Prev->isImplicit() ? diag::note_previous_implicit_declaration
12729 : diag::note_previous_declaration);
David Blaikied9cf8262012-06-25 21:55:30 +000012730 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000012731 // If the declaration wasn't the first, we delete the function anyway for
12732 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000012733 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000012734 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000012735
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012736 // dllimport/dllexport cannot be deleted.
12737 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12738 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12739 Fn->setInvalidDecl();
12740 }
12741
Richard Smith0ab5b4c2013-04-02 19:38:47 +000012742 if (Fn->isDeleted())
12743 return;
12744
12745 // See if we're deleting a function which is already known to override a
12746 // non-deleted virtual function.
12747 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12748 bool IssuedDiagnostic = false;
12749 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12750 E = MD->end_overridden_methods();
12751 I != E; ++I) {
12752 if (!(*MD->begin_overridden_methods())->isDeleted()) {
12753 if (!IssuedDiagnostic) {
12754 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12755 IssuedDiagnostic = true;
12756 }
12757 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12758 }
12759 }
12760 }
12761
Stephen Hines651f13c2014-04-23 16:59:28 -070012762 // C++11 [basic.start.main]p3:
12763 // A program that defines main as deleted [...] is ill-formed.
12764 if (Fn->isMain())
12765 Diag(DelLoc, diag::err_deleted_main);
12766
Sean Hunt10620eb2011-05-06 20:44:56 +000012767 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000012768}
Sebastian Redl13e88542009-04-27 21:33:24 +000012769
Sean Hunte4246a62011-05-12 06:15:49 +000012770void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000012771 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000012772
12773 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000012774 if (MD->getParent()->isDependentType()) {
12775 MD->setDefaulted();
12776 MD->setExplicitlyDefaulted();
12777 return;
12778 }
12779
Sean Hunte4246a62011-05-12 06:15:49 +000012780 CXXSpecialMember Member = getSpecialMember(MD);
12781 if (Member == CXXInvalid) {
Eli Friedmanfcb5a252013-07-11 23:55:07 +000012782 if (!MD->isInvalidDecl())
12783 Diag(DefaultLoc, diag::err_default_special_members);
Sean Hunte4246a62011-05-12 06:15:49 +000012784 return;
12785 }
12786
12787 MD->setDefaulted();
12788 MD->setExplicitlyDefaulted();
12789
Sean Huntcd10dec2011-05-23 23:14:04 +000012790 // If this definition appears within the record, do the checking when
12791 // the record is complete.
12792 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000012793 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000012794 // Find the uninstantiated declaration that actually had the '= default'
12795 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000012796 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000012797
Richard Smith12fef492013-03-27 00:22:47 +000012798 // If the method was defaulted on its first declaration, we will have
12799 // already performed the checking in CheckCompletedCXXClass. Such a
12800 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000012801 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000012802 return;
12803
Richard Smithb9d0b762012-07-27 04:22:15 +000012804 CheckExplicitlyDefaultedSpecialMember(MD);
12805
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012806 if (MD->isInvalidDecl())
12807 return;
12808
Sean Hunte4246a62011-05-12 06:15:49 +000012809 switch (Member) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012810 case CXXDefaultConstructor:
12811 DefineImplicitDefaultConstructor(DefaultLoc,
12812 cast<CXXConstructorDecl>(MD));
Sean Hunt49634cf2011-05-13 06:10:58 +000012813 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012814 case CXXCopyConstructor:
12815 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Sean Hunte4246a62011-05-12 06:15:49 +000012816 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012817 case CXXCopyAssignment:
12818 DefineImplicitCopyAssignment(DefaultLoc, MD);
Sean Hunt2b188082011-05-14 05:23:28 +000012819 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012820 case CXXDestructor:
12821 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Sean Huntcb45a0f2011-05-12 22:46:25 +000012822 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012823 case CXXMoveConstructor:
12824 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Sean Hunt82713172011-05-25 23:16:36 +000012825 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012826 case CXXMoveAssignment:
12827 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000012828 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000012829 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000012830 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000012831 }
12832 } else {
12833 Diag(DefaultLoc, diag::err_default_special_members);
12834 }
12835}
12836
Sebastian Redl13e88542009-04-27 21:33:24 +000012837static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000012838 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000012839 Stmt *SubStmt = *CI;
12840 if (!SubStmt)
12841 continue;
12842 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000012843 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000012844 diag::err_return_in_constructor_handler);
12845 if (!isa<Expr>(SubStmt))
12846 SearchForReturnInStmt(Self, SubStmt);
12847 }
12848}
12849
12850void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12851 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12852 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12853 SearchForReturnInStmt(*this, Handler);
12854 }
12855}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012856
David Blaikie299adab2013-01-18 23:03:15 +000012857bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000012858 const CXXMethodDecl *Old) {
12859 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12860 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12861
12862 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12863
12864 // If the calling conventions match, everything is fine
12865 if (NewCC == OldCC)
12866 return false;
12867
Stephen Hines651f13c2014-04-23 16:59:28 -070012868 // If the calling conventions mismatch because the new function is static,
12869 // suppress the calling convention mismatch error; the error about static
12870 // function override (err_static_overrides_virtual from
12871 // Sema::CheckFunctionDeclaration) is more clear.
12872 if (New->getStorageClass() == SC_Static)
12873 return false;
12874
Reid Kleckneref072032013-08-27 23:08:25 +000012875 Diag(New->getLocation(),
12876 diag::err_conflicting_overriding_cc_attributes)
12877 << New->getDeclName() << New->getType() << Old->getType();
12878 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12879 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000012880}
12881
Mike Stump1eb44332009-09-09 15:08:12 +000012882bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012883 const CXXMethodDecl *Old) {
Stephen Hines651f13c2014-04-23 16:59:28 -070012884 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12885 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012886
Chandler Carruth73857792010-02-15 11:53:20 +000012887 if (Context.hasSameType(NewTy, OldTy) ||
12888 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012889 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000012890
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012891 // Check if the return types are covariant
12892 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000012893
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012894 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000012895 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12896 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012897 NewClassTy = NewPT->getPointeeType();
12898 OldClassTy = OldPT->getPointeeType();
12899 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000012900 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12901 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12902 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12903 NewClassTy = NewRT->getPointeeType();
12904 OldClassTy = OldRT->getPointeeType();
12905 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012906 }
12907 }
Mike Stump1eb44332009-09-09 15:08:12 +000012908
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012909 // The return types aren't either both pointers or references to a class type.
12910 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000012911 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012912 diag::err_different_return_type_for_overriding_virtual_function)
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012913 << New->getDeclName() << NewTy << OldTy
12914 << New->getReturnTypeSourceRange();
12915 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12916 << Old->getReturnTypeSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +000012917
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012918 return true;
12919 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012920
Anders Carlssonbe2e2052009-12-31 18:34:24 +000012921 // C++ [class.virtual]p6:
12922 // If the return type of D::f differs from the return type of B::f, the
12923 // class type in the return type of D::f shall be complete at the point of
12924 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000012925 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12926 if (!RT->isBeingDefined() &&
12927 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000012928 diag::err_covariant_return_incomplete,
12929 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000012930 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000012931 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000012932
Douglas Gregora4923eb2009-11-16 21:35:15 +000012933 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012934 // Check if the new class derives from the old class.
12935 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012936 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
12937 << New->getDeclName() << NewTy << OldTy
12938 << New->getReturnTypeSourceRange();
12939 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12940 << Old->getReturnTypeSourceRange();
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012941 return true;
12942 }
Mike Stump1eb44332009-09-09 15:08:12 +000012943
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012944 // Check if we the conversion from derived to base is valid.
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012945 if (CheckDerivedToBaseConversion(
12946 NewClassTy, OldClassTy,
12947 diag::err_covariant_return_inaccessible_base,
12948 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12949 New->getLocation(), New->getReturnTypeSourceRange(),
12950 New->getDeclName(), nullptr)) {
John McCalleee1d542011-02-14 07:13:47 +000012951 // FIXME: this note won't trigger for delayed access control
12952 // diagnostics, and it's impossible to get an undelayed error
12953 // here from access control during the original parse because
12954 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012955 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12956 << Old->getReturnTypeSourceRange();
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012957 return true;
12958 }
12959 }
Mike Stump1eb44332009-09-09 15:08:12 +000012960
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012961 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000012962 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012963 Diag(New->getLocation(),
12964 diag::err_covariant_return_type_different_qualifications)
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012965 << New->getDeclName() << NewTy << OldTy
12966 << New->getReturnTypeSourceRange();
12967 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12968 << Old->getReturnTypeSourceRange();
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012969 return true;
12970 };
Mike Stump1eb44332009-09-09 15:08:12 +000012971
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012972
12973 // The new class type must have the same or less qualifiers as the old type.
12974 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12975 Diag(New->getLocation(),
12976 diag::err_covariant_return_type_class_type_more_qualified)
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012977 << New->getDeclName() << NewTy << OldTy
12978 << New->getReturnTypeSourceRange();
12979 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12980 << Old->getReturnTypeSourceRange();
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012981 return true;
12982 };
Mike Stump1eb44332009-09-09 15:08:12 +000012983
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012984 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012985}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012986
Douglas Gregor4ba31362009-12-01 17:24:26 +000012987/// \brief Mark the given method pure.
12988///
12989/// \param Method the method to be marked pure.
12990///
12991/// \param InitRange the source range that covers the "0" initializer.
12992bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000012993 SourceLocation EndLoc = InitRange.getEnd();
12994 if (EndLoc.isValid())
12995 Method->setRangeEnd(EndLoc);
12996
Douglas Gregor4ba31362009-12-01 17:24:26 +000012997 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12998 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000012999 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000013000 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000013001
13002 if (!Method->isInvalidDecl())
13003 Diag(Method->getLocation(), diag::err_non_virtual_pure)
13004 << Method->getDeclName() << InitRange;
13005 return true;
13006}
13007
Douglas Gregor552e2992012-02-21 02:22:07 +000013008/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000013009static bool isStaticDataMember(const Decl *D) {
13010 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
13011 return Var->isStaticDataMember();
13012
13013 return false;
Douglas Gregor552e2992012-02-21 02:22:07 +000013014}
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000013015
John McCall731ad842009-12-19 09:28:58 +000013016/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
13017/// an initializer for the out-of-line declaration 'Dcl'. The scope
13018/// is a fresh scope pushed for just this purpose.
13019///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000013020/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
13021/// static data member of class X, names should be looked up in the scope of
13022/// class X.
John McCalld226f652010-08-21 09:40:31 +000013023void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000013024 // If there is no declaration, there was an error parsing it.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070013025 if (!D || D->isInvalidDecl())
13026 return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000013027
Stephen Hines651f13c2014-04-23 16:59:28 -070013028 // We will always have a nested name specifier here, but this declaration
13029 // might not be out of line if the specifier names the current namespace:
13030 // extern int n;
13031 // int ::n = 0;
13032 if (D->isOutOfLine())
13033 EnterDeclaratorContext(S, D->getDeclContext());
13034
Douglas Gregor552e2992012-02-21 02:22:07 +000013035 // If we are parsing the initializer for a static data member, push a
13036 // new expression evaluation context that is associated with this static
13037 // data member.
13038 if (isStaticDataMember(D))
13039 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000013040}
13041
13042/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000013043/// initializer for the out-of-line declaration 'D'.
13044void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000013045 // If there is no declaration, there was an error parsing it.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070013046 if (!D || D->isInvalidDecl())
13047 return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000013048
Douglas Gregor552e2992012-02-21 02:22:07 +000013049 if (isStaticDataMember(D))
Stephen Hines651f13c2014-04-23 16:59:28 -070013050 PopExpressionEvaluationContext();
Douglas Gregor552e2992012-02-21 02:22:07 +000013051
Stephen Hines651f13c2014-04-23 16:59:28 -070013052 if (D->isOutOfLine())
13053 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000013054}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000013055
13056/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
13057/// C++ if/switch/while/for statement.
13058/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000013059DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000013060 // C++ 6.4p2:
13061 // The declarator shall not specify a function or an array.
13062 // The type-specifier-seq shall not contain typedef and shall not declare a
13063 // new class or enumeration.
13064 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
13065 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000013066
13067 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000013068 if (!Dcl)
13069 return true;
13070
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000013071 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
13072 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000013073 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000013074 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000013075 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000013076
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000013077 return Dcl;
13078}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000013079
Douglas Gregordfe65432011-07-28 19:11:31 +000013080void Sema::LoadExternalVTableUses() {
13081 if (!ExternalSource)
13082 return;
13083
13084 SmallVector<ExternalVTableUse, 4> VTables;
13085 ExternalSource->ReadUsedVTables(VTables);
13086 SmallVector<VTableUse, 4> NewUses;
13087 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
13088 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
13089 = VTablesUsed.find(VTables[I].Record);
13090 // Even if a definition wasn't required before, it may be required now.
13091 if (Pos != VTablesUsed.end()) {
13092 if (!Pos->second && VTables[I].DefinitionRequired)
13093 Pos->second = true;
13094 continue;
13095 }
13096
13097 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
13098 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
13099 }
13100
13101 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
13102}
13103
Douglas Gregor6fb745b2010-05-13 16:44:06 +000013104void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
13105 bool DefinitionRequired) {
13106 // Ignore any vtable uses in unevaluated operands or for classes that do
13107 // not have a vtable.
13108 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallaeeacf72013-05-03 00:10:13 +000013109 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000013110 return;
13111
Douglas Gregor6fb745b2010-05-13 16:44:06 +000013112 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000013113 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000013114 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13115 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
13116 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
13117 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000013118 // If we already had an entry, check to see if we are promoting this vtable
Stephen Hines0e2c34f2015-03-23 12:09:02 -070013119 // to require a definition. If so, we need to reappend to the VTableUses
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000013120 // list, since we may have already processed the first entry.
13121 if (DefinitionRequired && !Pos.first->second) {
13122 Pos.first->second = true;
13123 } else {
13124 // Otherwise, we can early exit.
13125 return;
13126 }
Stephen Hines651f13c2014-04-23 16:59:28 -070013127 } else {
13128 // The Microsoft ABI requires that we perform the destructor body
13129 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
13130 // the deleting destructor is emitted with the vtable, not with the
13131 // destructor definition as in the Itanium ABI.
13132 // If it has a definition, we do the check at that point instead.
13133 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13134 Class->hasUserDeclaredDestructor() &&
13135 !Class->getDestructor()->isDefined() &&
13136 !Class->getDestructor()->isDeleted()) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -070013137 CXXDestructorDecl *DD = Class->getDestructor();
13138 ContextRAII SavedContext(*this, DD);
13139 CheckDestructor(DD);
Stephen Hines651f13c2014-04-23 16:59:28 -070013140 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000013141 }
13142
13143 // Local classes need to have their virtual members marked
13144 // immediately. For all other classes, we mark their virtual members
13145 // at the end of the translation unit.
13146 if (Class->isLocalClass())
13147 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000013148 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000013149 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000013150}
13151
Douglas Gregor6fb745b2010-05-13 16:44:06 +000013152bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000013153 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000013154 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000013155 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000013156
Douglas Gregor6fb745b2010-05-13 16:44:06 +000013157 // Note: The VTableUses vector could grow as a result of marking
13158 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000013159 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000013160 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000013161 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000013162 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000013163 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000013164 if (!Class)
13165 continue;
13166
13167 SourceLocation Loc = VTableUses[I].second;
13168
Richard Smithb9d0b762012-07-27 04:22:15 +000013169 bool DefineVTable = true;
13170
Douglas Gregor6fb745b2010-05-13 16:44:06 +000013171 // If this class has a key function, but that key function is
13172 // defined in another translation unit, we don't need to emit the
13173 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000013174 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000013175 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolafc218132013-08-26 23:23:21 +000013176 // The key function is in another translation unit.
13177 DefineVTable = false;
13178 TemplateSpecializationKind TSK =
13179 KeyFunction->getTemplateSpecializationKind();
13180 assert(TSK != TSK_ExplicitInstantiationDefinition &&
13181 TSK != TSK_ImplicitInstantiation &&
13182 "Instantiations don't have key functions");
13183 (void)TSK;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000013184 } else if (!KeyFunction) {
13185 // If we have a class with no key function that is the subject
13186 // of an explicit instantiation declaration, suppress the
13187 // vtable; it will live with the explicit instantiation
13188 // definition.
13189 bool IsExplicitInstantiationDeclaration
13190 = Class->getTemplateSpecializationKind()
13191 == TSK_ExplicitInstantiationDeclaration;
Stephen Hines651f13c2014-04-23 16:59:28 -070013192 for (auto R : Class->redecls()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000013193 TemplateSpecializationKind TSK
Stephen Hines651f13c2014-04-23 16:59:28 -070013194 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000013195 if (TSK == TSK_ExplicitInstantiationDeclaration)
13196 IsExplicitInstantiationDeclaration = true;
13197 else if (TSK == TSK_ExplicitInstantiationDefinition) {
13198 IsExplicitInstantiationDeclaration = false;
13199 break;
13200 }
13201 }
13202
13203 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000013204 DefineVTable = false;
13205 }
13206
13207 // The exception specifications for all virtual members may be needed even
13208 // if we are not providing an authoritative form of the vtable in this TU.
13209 // We may choose to emit it available_externally anyway.
13210 if (!DefineVTable) {
13211 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
13212 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000013213 }
13214
13215 // Mark all of the virtual members of this class as referenced, so
13216 // that we can build a vtable. Then, tell the AST consumer that a
13217 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000013218 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000013219 MarkVirtualMembersReferenced(Loc, Class);
13220 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
Stephen Hines0e2c34f2015-03-23 12:09:02 -070013221 if (VTablesUsed[Canonical])
13222 Consumer.HandleVTable(Class);
Douglas Gregor6fb745b2010-05-13 16:44:06 +000013223
13224 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +000013225 if (Class->isExternallyVisible() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000013226 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -070013227 const FunctionDecl *KeyFunctionDef = nullptr;
Douglas Gregora120d012011-09-23 19:04:03 +000013228 if (!KeyFunction ||
13229 (KeyFunction->hasBody(KeyFunctionDef) &&
13230 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000013231 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
13232 TSK_ExplicitInstantiationDefinition
13233 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
13234 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000013235 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000013236 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000013237 VTableUses.clear();
13238
Douglas Gregor78844032011-04-22 22:25:37 +000013239 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000013240}
Anders Carlssond6a637f2009-12-07 08:24:59 +000013241
Richard Smithb9d0b762012-07-27 04:22:15 +000013242void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
13243 const CXXRecordDecl *RD) {
Stephen Hines651f13c2014-04-23 16:59:28 -070013244 for (const auto *I : RD->methods())
13245 if (I->isVirtual() && !I->isPure())
13246 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithb9d0b762012-07-27 04:22:15 +000013247}
13248
Rafael Espindola3e1ae932010-03-26 00:36:59 +000013249void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
13250 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000013251 // Mark all functions which will appear in RD's vtable as used.
13252 CXXFinalOverriderMap FinalOverriders;
13253 RD->getFinalOverriders(FinalOverriders);
13254 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
13255 E = FinalOverriders.end();
13256 I != E; ++I) {
13257 for (OverridingMethods::const_iterator OI = I->second.begin(),
13258 OE = I->second.end();
13259 OI != OE; ++OI) {
13260 assert(OI->second.size() > 0 && "no final overrider");
13261 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000013262
Richard Smithff817f72012-07-07 06:59:51 +000013263 // C++ [basic.def.odr]p2:
13264 // [...] A virtual member function is used if it is not pure. [...]
13265 if (!Overrider->isPure())
13266 MarkFunctionReferenced(Loc, Overrider);
13267 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000013268 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000013269
13270 // Only classes that have virtual bases need a VTT.
13271 if (RD->getNumVBases() == 0)
13272 return;
13273
Stephen Hines651f13c2014-04-23 16:59:28 -070013274 for (const auto &I : RD->bases()) {
Rafael Espindola3e1ae932010-03-26 00:36:59 +000013275 const CXXRecordDecl *Base =
Stephen Hines651f13c2014-04-23 16:59:28 -070013276 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000013277 if (Base->getNumVBases() == 0)
13278 continue;
13279 MarkVirtualMembersReferenced(Loc, Base);
13280 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000013281}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000013282
13283/// SetIvarInitializers - This routine builds initialization ASTs for the
13284/// Objective-C implementation whose ivars need be initialized.
13285void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000013286 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000013287 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000013288 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000013289 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000013290 CollectIvarsToConstructOrDestruct(OID, ivars);
13291 if (ivars.empty())
13292 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000013293 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000013294 for (unsigned i = 0; i < ivars.size(); i++) {
13295 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000013296 if (Field->isInvalidDecl())
13297 continue;
13298
Sean Huntcbb67482011-01-08 20:30:50 +000013299 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000013300 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
13301 InitializationKind InitKind =
13302 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000013303
13304 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
13305 ExprResult MemberInit =
13306 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregor53c374f2010-12-07 00:41:46 +000013307 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000013308 // Note, MemberInit could actually come back empty if no initialization
13309 // is required (e.g., because it would call a trivial default constructor)
13310 if (!MemberInit.get() || MemberInit.isInvalid())
13311 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000013312
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000013313 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000013314 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
13315 SourceLocation(),
Stephen Hinesc568f1e2014-07-21 00:47:37 -070013316 MemberInit.getAs<Expr>(),
Sean Huntcbb67482011-01-08 20:30:50 +000013317 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000013318 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000013319
13320 // Be sure that the destructor is accessible and is marked as referenced.
Stephen Hines176edba2014-12-01 14:53:08 -080013321 if (const RecordType *RecordTy =
13322 Context.getBaseElementType(Field->getType())
13323 ->getAs<RecordType>()) {
13324 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000013325 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000013326 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000013327 CheckDestructorAccess(Field->getLocation(), Destructor,
13328 PDiag(diag::err_access_dtor_ivar)
13329 << Context.getBaseElementType(Field->getType()));
13330 }
13331 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000013332 }
13333 ObjCImplementation->setIvarInitializers(Context,
13334 AllToInit.data(), AllToInit.size());
13335 }
13336}
Sean Huntfe57eef2011-05-04 05:57:24 +000013337
Sean Huntebcbe1d2011-05-04 23:29:54 +000013338static
13339void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
13340 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
13341 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
13342 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
13343 Sema &S) {
Sean Huntebcbe1d2011-05-04 23:29:54 +000013344 if (Ctor->isInvalidDecl())
13345 return;
13346
Richard Smitha8eaf002012-08-23 06:16:52 +000013347 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
13348
13349 // Target may not be determinable yet, for instance if this is a dependent
13350 // call in an uninstantiated template.
13351 if (Target) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -070013352 const FunctionDecl *FNTarget = nullptr;
Richard Smitha8eaf002012-08-23 06:16:52 +000013353 (void)Target->hasBody(FNTarget);
13354 Target = const_cast<CXXConstructorDecl*>(
13355 cast_or_null<CXXConstructorDecl>(FNTarget));
13356 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000013357
13358 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
13359 // Avoid dereferencing a null pointer here.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070013360 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
Sean Huntebcbe1d2011-05-04 23:29:54 +000013361
Stephen Hines176edba2014-12-01 14:53:08 -080013362 if (!Current.insert(Canonical).second)
Sean Huntebcbe1d2011-05-04 23:29:54 +000013363 return;
13364
13365 // We know that beyond here, we aren't chaining into a cycle.
13366 if (!Target || !Target->isDelegatingConstructor() ||
13367 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000013368 Valid.insert(Current.begin(), Current.end());
Sean Huntebcbe1d2011-05-04 23:29:54 +000013369 Current.clear();
13370 // We've hit a cycle.
13371 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
13372 Current.count(TCanonical)) {
13373 // If we haven't diagnosed this cycle yet, do so now.
13374 if (!Invalid.count(TCanonical)) {
13375 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000013376 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000013377 << Ctor;
13378
Richard Smitha8eaf002012-08-23 06:16:52 +000013379 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000013380 if (TCanonical != Canonical)
13381 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
13382
13383 CXXConstructorDecl *C = Target;
13384 while (C->getCanonicalDecl() != Canonical) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -070013385 const FunctionDecl *FNTarget = nullptr;
Sean Huntebcbe1d2011-05-04 23:29:54 +000013386 (void)C->getTargetConstructor()->hasBody(FNTarget);
13387 assert(FNTarget && "Ctor cycle through bodiless function");
13388
Richard Smitha8eaf002012-08-23 06:16:52 +000013389 C = const_cast<CXXConstructorDecl*>(
13390 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000013391 S.Diag(C->getLocation(), diag::note_which_delegates_to);
13392 }
13393 }
13394
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000013395 Invalid.insert(Current.begin(), Current.end());
Sean Huntebcbe1d2011-05-04 23:29:54 +000013396 Current.clear();
13397 } else {
13398 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
13399 }
13400}
13401
13402
Sean Huntfe57eef2011-05-04 05:57:24 +000013403void Sema::CheckDelegatingCtorCycles() {
13404 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
13405
Douglas Gregor0129b562011-07-27 21:57:17 +000013406 for (DelegatingCtorDeclsType::iterator
13407 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000013408 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000013409 I != E; ++I)
13410 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000013411
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000013412 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
13413 CE = Invalid.end();
13414 CI != CE; ++CI)
Sean Huntebcbe1d2011-05-04 23:29:54 +000013415 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000013416}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000013417
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013418namespace {
13419 /// \brief AST visitor that finds references to the 'this' expression.
13420 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
13421 Sema &S;
13422
13423 public:
13424 explicit FindCXXThisExpr(Sema &S) : S(S) { }
13425
13426 bool VisitCXXThisExpr(CXXThisExpr *E) {
13427 S.Diag(E->getLocation(), diag::err_this_static_member_func)
13428 << E->isImplicit();
13429 return false;
13430 }
13431 };
13432}
13433
13434bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
13435 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13436 if (!TSInfo)
13437 return false;
13438
13439 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000013440 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013441 if (!ProtoTL)
13442 return false;
13443
13444 // C++11 [expr.prim.general]p3:
13445 // [The expression this] shall not appear before the optional
13446 // cv-qualifier-seq and it shall not appear within the declaration of a
13447 // static member function (although its type and value category are defined
13448 // within a static member function as they are within a non-static member
13449 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000013450 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000013451 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013452 FindCXXThisExpr Finder(*this);
13453
13454 // If the return type came after the cv-qualifier-seq, check it now.
13455 if (Proto->hasTrailingReturn() &&
Stephen Hines651f13c2014-04-23 16:59:28 -070013456 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013457 return true;
13458
13459 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000013460 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
13461 return true;
13462
13463 return checkThisInStaticMemberFunctionAttributes(Method);
13464}
13465
13466bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
13467 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13468 if (!TSInfo)
13469 return false;
13470
13471 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000013472 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000013473 if (!ProtoTL)
13474 return false;
13475
David Blaikie39e6ab42013-02-18 22:06:02 +000013476 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000013477 FindCXXThisExpr Finder(*this);
13478
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013479 switch (Proto->getExceptionSpecType()) {
Stephen Hines176edba2014-12-01 14:53:08 -080013480 case EST_Unparsed:
Richard Smithe6975e92012-04-17 00:58:00 +000013481 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000013482 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013483 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013484 case EST_DynamicNone:
13485 case EST_MSAny:
13486 case EST_None:
13487 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000013488
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013489 case EST_ComputedNoexcept:
13490 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
13491 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000013492
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013493 case EST_Dynamic:
Stephen Hines651f13c2014-04-23 16:59:28 -070013494 for (const auto &E : Proto->exceptions()) {
13495 if (!Finder.TraverseType(E))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013496 return true;
13497 }
13498 break;
13499 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000013500
13501 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013502}
13503
13504bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
13505 FindCXXThisExpr Finder(*this);
13506
13507 // Check attributes.
Stephen Hines651f13c2014-04-23 16:59:28 -070013508 for (const auto *A : Method->attrs()) {
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013509 // FIXME: This should be emitted by tblgen.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070013510 Expr *Arg = nullptr;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013511 ArrayRef<Expr *> Args;
Stephen Hines651f13c2014-04-23 16:59:28 -070013512 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013513 Arg = G->getArg();
Stephen Hines651f13c2014-04-23 16:59:28 -070013514 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013515 Arg = G->getArg();
Stephen Hines651f13c2014-04-23 16:59:28 -070013516 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Stephen Hines176edba2014-12-01 14:53:08 -080013517 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
Stephen Hines651f13c2014-04-23 16:59:28 -070013518 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Stephen Hines176edba2014-12-01 14:53:08 -080013519 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
Stephen Hines651f13c2014-04-23 16:59:28 -070013520 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013521 Arg = ETLF->getSuccessValue();
Stephen Hines176edba2014-12-01 14:53:08 -080013522 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
Stephen Hines651f13c2014-04-23 16:59:28 -070013523 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013524 Arg = STLF->getSuccessValue();
Stephen Hines176edba2014-12-01 14:53:08 -080013525 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
Stephen Hines651f13c2014-04-23 16:59:28 -070013526 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013527 Arg = LR->getArg();
Stephen Hines651f13c2014-04-23 16:59:28 -070013528 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Stephen Hines176edba2014-12-01 14:53:08 -080013529 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
Stephen Hines651f13c2014-04-23 16:59:28 -070013530 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Stephen Hines176edba2014-12-01 14:53:08 -080013531 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Stephen Hines651f13c2014-04-23 16:59:28 -070013532 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Stephen Hines176edba2014-12-01 14:53:08 -080013533 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Stephen Hines651f13c2014-04-23 16:59:28 -070013534 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
Stephen Hines176edba2014-12-01 14:53:08 -080013535 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Stephen Hines651f13c2014-04-23 16:59:28 -070013536 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Stephen Hines176edba2014-12-01 14:53:08 -080013537 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013538
13539 if (Arg && !Finder.TraverseStmt(Arg))
13540 return true;
13541
13542 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13543 if (!Finder.TraverseStmt(Args[I]))
13544 return true;
13545 }
13546 }
13547
13548 return false;
13549}
13550
Stephen Hines176edba2014-12-01 14:53:08 -080013551void Sema::checkExceptionSpecification(
13552 bool IsTopLevel, ExceptionSpecificationType EST,
13553 ArrayRef<ParsedType> DynamicExceptions,
13554 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
13555 SmallVectorImpl<QualType> &Exceptions,
13556 FunctionProtoType::ExceptionSpecInfo &ESI) {
Douglas Gregor74e2fc32012-04-16 18:27:27 +000013557 Exceptions.clear();
Stephen Hines176edba2014-12-01 14:53:08 -080013558 ESI.Type = EST;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000013559 if (EST == EST_Dynamic) {
13560 Exceptions.reserve(DynamicExceptions.size());
13561 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13562 // FIXME: Preserve type source info.
13563 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13564
Stephen Hines176edba2014-12-01 14:53:08 -080013565 if (IsTopLevel) {
13566 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13567 collectUnexpandedParameterPacks(ET, Unexpanded);
13568 if (!Unexpanded.empty()) {
13569 DiagnoseUnexpandedParameterPacks(
13570 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
13571 Unexpanded);
13572 continue;
13573 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000013574 }
13575
13576 // Check that the type is valid for an exception spec, and
13577 // drop it if not.
13578 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13579 Exceptions.push_back(ET);
13580 }
Stephen Hines176edba2014-12-01 14:53:08 -080013581 ESI.Exceptions = Exceptions;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000013582 return;
13583 }
Stephen Hines176edba2014-12-01 14:53:08 -080013584
Douglas Gregor74e2fc32012-04-16 18:27:27 +000013585 if (EST == EST_ComputedNoexcept) {
13586 // If an error occurred, there's no expression here.
13587 if (NoexceptExpr) {
13588 assert((NoexceptExpr->isTypeDependent() ||
13589 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13590 Context.BoolTy) &&
13591 "Parser should have made sure that the expression is boolean");
Stephen Hines176edba2014-12-01 14:53:08 -080013592 if (IsTopLevel && NoexceptExpr &&
13593 DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
13594 ESI.Type = EST_BasicNoexcept;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000013595 return;
13596 }
Stephen Hines176edba2014-12-01 14:53:08 -080013597
Douglas Gregor74e2fc32012-04-16 18:27:27 +000013598 if (!NoexceptExpr->isValueDependent())
Stephen Hines6bcf27b2014-05-29 04:14:42 -070013599 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
Douglas Gregorab41fe92012-05-04 22:38:52 +000013600 diag::err_noexcept_needs_constant_expression,
Stephen Hinesc568f1e2014-07-21 00:47:37 -070013601 /*AllowFold*/ false).get();
Stephen Hines176edba2014-12-01 14:53:08 -080013602 ESI.NoexceptExpr = NoexceptExpr;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000013603 }
13604 return;
13605 }
13606}
13607
Stephen Hines176edba2014-12-01 14:53:08 -080013608void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
13609 ExceptionSpecificationType EST,
13610 SourceRange SpecificationRange,
13611 ArrayRef<ParsedType> DynamicExceptions,
13612 ArrayRef<SourceRange> DynamicExceptionRanges,
13613 Expr *NoexceptExpr) {
13614 if (!MethodD)
13615 return;
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000013616
Stephen Hines176edba2014-12-01 14:53:08 -080013617 // Dig out the method we're referring to.
13618 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
13619 MethodD = FunTmpl->getTemplatedDecl();
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000013620
Stephen Hines176edba2014-12-01 14:53:08 -080013621 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
13622 if (!Method)
13623 return;
13624
13625 // Check the exception specification.
13626 llvm::SmallVector<QualType, 4> Exceptions;
13627 FunctionProtoType::ExceptionSpecInfo ESI;
13628 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
13629 DynamicExceptionRanges, NoexceptExpr, Exceptions,
13630 ESI);
13631
13632 // Update the exception specification on the function type.
13633 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
13634
13635 if (Method->isStatic())
13636 checkThisInStaticMemberFunctionExceptionSpec(Method);
13637
13638 if (Method->isVirtual()) {
13639 // Check overrides, which we previously had to delay.
13640 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
13641 OEnd = Method->end_overridden_methods();
13642 O != OEnd; ++O)
13643 CheckOverridingFunctionExceptionSpec(Method, *O);
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000013644 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000013645}
John McCall76da55d2013-04-16 07:28:30 +000013646
13647/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13648///
13649MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13650 SourceLocation DeclStart,
13651 Declarator &D, Expr *BitWidth,
13652 InClassInitStyle InitStyle,
13653 AccessSpecifier AS,
13654 AttributeList *MSPropertyAttr) {
13655 IdentifierInfo *II = D.getIdentifier();
13656 if (!II) {
13657 Diag(DeclStart, diag::err_anonymous_property);
Stephen Hines6bcf27b2014-05-29 04:14:42 -070013658 return nullptr;
John McCall76da55d2013-04-16 07:28:30 +000013659 }
13660 SourceLocation Loc = D.getIdentifierLoc();
13661
13662 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13663 QualType T = TInfo->getType();
13664 if (getLangOpts().CPlusPlus) {
13665 CheckExtraCXXDefaultArguments(D);
13666
13667 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13668 UPPC_DataMemberType)) {
13669 D.setInvalidType();
13670 T = Context.IntTy;
13671 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13672 }
13673 }
13674
13675 DiagnoseFunctionSpecifiers(D.getDeclSpec());
13676
13677 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13678 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13679 diag::err_invalid_thread)
13680 << DeclSpec::getSpecifierName(TSCS);
13681
13682 // Check to see if this name was declared as a member previously
Stephen Hines6bcf27b2014-05-29 04:14:42 -070013683 NamedDecl *PrevDecl = nullptr;
John McCall76da55d2013-04-16 07:28:30 +000013684 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13685 LookupName(Previous, S);
13686 switch (Previous.getResultKind()) {
13687 case LookupResult::Found:
13688 case LookupResult::FoundUnresolvedValue:
13689 PrevDecl = Previous.getAsSingle<NamedDecl>();
13690 break;
13691
13692 case LookupResult::FoundOverloaded:
13693 PrevDecl = Previous.getRepresentativeDecl();
13694 break;
13695
13696 case LookupResult::NotFound:
13697 case LookupResult::NotFoundInCurrentInstantiation:
13698 case LookupResult::Ambiguous:
13699 break;
13700 }
13701
13702 if (PrevDecl && PrevDecl->isTemplateParameter()) {
13703 // Maybe we will complain about the shadowed template parameter.
13704 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13705 // Just pretend that we didn't see the previous declaration.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070013706 PrevDecl = nullptr;
John McCall76da55d2013-04-16 07:28:30 +000013707 }
13708
13709 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Stephen Hines6bcf27b2014-05-29 04:14:42 -070013710 PrevDecl = nullptr;
John McCall76da55d2013-04-16 07:28:30 +000013711
13712 SourceLocation TSSL = D.getLocStart();
John McCall76da55d2013-04-16 07:28:30 +000013713 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Stephen Hines651f13c2014-04-23 16:59:28 -070013714 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13715 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall76da55d2013-04-16 07:28:30 +000013716 ProcessDeclAttributes(TUScope, NewPD, D);
13717 NewPD->setAccess(AS);
13718
13719 if (NewPD->isInvalidDecl())
13720 Record->setInvalidDecl();
13721
13722 if (D.getDeclSpec().isModulePrivateSpecified())
13723 NewPD->setModulePrivate();
13724
13725 if (NewPD->isInvalidDecl() && PrevDecl) {
13726 // Don't introduce NewFD into scope; there's already something
13727 // with the same name in the same scope.
13728 } else if (II) {
13729 PushOnScopeChains(NewPD, S);
13730 } else
13731 Record->addDecl(NewPD);
13732
13733 return NewPD;
13734}