blob: c373b46a510657c701780499c2778c7daf032994 [file] [log] [blame]
Chris Lattner199abbc2008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Faisal Vali2b391ab2013-09-26 19:54:12 +000017#include "clang/AST/ASTLambda.h"
Sebastian Redlab238a72011-04-24 16:28:06 +000018#include "clang/AST/ASTMutationListener.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/CharUnits.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000021#include "clang/AST/DeclVisitor.h"
Richard Trieu4fc85362012-06-14 23:11:34 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Alexis Huntc5575cc2011-02-26 19:13:13 +000023#include "clang/AST/ExprCXX.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000024#include "clang/AST/RecordLayout.h"
Douglas Gregor3024f072012-04-16 07:05:22 +000025#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000026#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000027#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000028#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000029#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballman02df2e02012-12-09 17:45:41 +000030#include "clang/Basic/TargetInfo.h"
Richard Smithf4198b72013-07-23 08:14:48 +000031#include "clang/Lex/LiteralSupport.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000032#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000033#include "clang/Sema/CXXFieldCollector.h"
34#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Initialization.h"
36#include "clang/Sema/Lookup.h"
37#include "clang/Sema/ParsedTemplate.h"
38#include "clang/Sema/Scope.h"
39#include "clang/Sema/ScopeInfo.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000040#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000041#include "llvm/ADT/SmallString.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000042#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000043#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000044
45using namespace clang;
46
Chris Lattner58258242008-04-10 02:22:51 +000047//===----------------------------------------------------------------------===//
48// CheckDefaultArgumentVisitor
49//===----------------------------------------------------------------------===//
50
Chris Lattnerb0d38442008-04-12 23:52:44 +000051namespace {
52 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
53 /// the default argument of a parameter to determine whether it
54 /// contains any ill-formed subexpressions. For example, this will
55 /// diagnose the use of local variables or parameters within the
56 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000057 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000058 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000059 Expr *DefaultArg;
60 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000061
Chris Lattnerb0d38442008-04-12 23:52:44 +000062 public:
Mike Stump11289f42009-09-09 15:08:12 +000063 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000064 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000065
Chris Lattnerb0d38442008-04-12 23:52:44 +000066 bool VisitExpr(Expr *Node);
67 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000068 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0d49512012-02-10 23:30:22 +000069 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall7353c862013-04-09 01:56:28 +000070 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000071 };
Chris Lattner58258242008-04-10 02:22:51 +000072
Chris Lattnerb0d38442008-04-12 23:52:44 +000073 /// VisitExpr - Visit all of the children of this expression.
74 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
75 bool IsInvalid = false;
John McCall8322c3a2011-02-13 04:07:26 +000076 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattner574dee62008-07-26 22:17:49 +000077 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000078 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000079 }
80
Chris Lattnerb0d38442008-04-12 23:52:44 +000081 /// VisitDeclRefExpr - Visit a reference to a declaration, to
82 /// determine whether this declaration can be used in the default
83 /// argument expression.
84 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000085 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000086 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
87 // C++ [dcl.fct.default]p9
88 // Default arguments are evaluated each time the function is
89 // called. The order of evaluation of function arguments is
90 // unspecified. Consequently, parameters of a function shall not
91 // be used in default argument expressions, even if they are not
92 // evaluated. Parameters of a function declared before a default
93 // argument expression are in scope and can hide namespace and
94 // class member names.
Daniel Dunbar62ee6412012-03-09 18:35:03 +000095 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +000096 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000097 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000098 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000099 // C++ [dcl.fct.default]p7
100 // Local variables shall not be used in default argument
101 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +0000102 if (VDecl->isLocalVarDecl())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000103 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000104 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +0000105 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000106 }
Chris Lattner58258242008-04-10 02:22:51 +0000107
Douglas Gregor8e12c382008-11-04 13:41:56 +0000108 return false;
109 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000110
Douglas Gregor97a9c812008-11-04 14:32:21 +0000111 /// VisitCXXThisExpr - Visit a C++ "this" expression.
112 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
113 // C++ [dcl.fct.default]p8:
114 // The keyword this shall not be used in a default argument of a
115 // member function.
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000116 return S->Diag(ThisE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000117 diag::err_param_default_argument_references_this)
118 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000119 }
Douglas Gregorf0d49512012-02-10 23:30:22 +0000120
John McCall7353c862013-04-09 01:56:28 +0000121 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
122 bool Invalid = false;
123 for (PseudoObjectExpr::semantics_iterator
124 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
125 Expr *E = *i;
126
127 // Look through bindings.
128 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
129 E = OVE->getSourceExpr();
130 assert(E && "pseudo-object binding without source expression?");
131 }
132
133 Invalid |= Visit(E);
134 }
135 return Invalid;
136 }
137
Douglas Gregorf0d49512012-02-10 23:30:22 +0000138 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
139 // C++11 [expr.lambda.prim]p13:
140 // A lambda-expression appearing in a default argument shall not
141 // implicitly or explicitly capture any entity.
142 if (Lambda->capture_begin() == Lambda->capture_end())
143 return false;
144
145 return S->Diag(Lambda->getLocStart(),
146 diag::err_lambda_capture_default_arg);
147 }
Chris Lattner58258242008-04-10 02:22:51 +0000148}
149
Richard Smithb7151b92013-04-10 06:11:48 +0000150void
151Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152 const CXXMethodDecl *Method) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000153 // If we have an MSAny spec already, don't bother.
154 if (!Method || ComputedEST == EST_MSAny)
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000155 return;
156
157 const FunctionProtoType *Proto
158 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +0000159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160 if (!Proto)
161 return;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000162
163 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
164
165 // If this function can throw any exceptions, make a note of that.
Richard Smithd3b5c9082012-07-27 04:22:15 +0000166 if (EST == EST_MSAny || EST == EST_None) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000167 ClearExceptions();
168 ComputedEST = EST;
169 return;
170 }
171
Richard Smith938f40b2011-06-11 17:19:42 +0000172 // FIXME: If the call to this decl is using any of its default arguments, we
173 // need to search them for potentially-throwing calls.
174
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000175 // If this function has a basic noexcept, it doesn't affect the outcome.
176 if (EST == EST_BasicNoexcept)
177 return;
178
179 // If we have a throw-all spec at this point, ignore the function.
180 if (ComputedEST == EST_None)
181 return;
182
183 // If we're still at noexcept(true) and there's a nothrow() callee,
184 // change to that specification.
185 if (EST == EST_DynamicNone) {
186 if (ComputedEST == EST_BasicNoexcept)
187 ComputedEST = EST_DynamicNone;
188 return;
189 }
190
191 // Check out noexcept specs.
192 if (EST == EST_ComputedNoexcept) {
Richard Smithf623c962012-04-17 00:58:00 +0000193 FunctionProtoType::NoexceptResult NR =
194 Proto->getNoexceptSpec(Self->Context);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000195 assert(NR != FunctionProtoType::NR_NoNoexcept &&
196 "Must have noexcept result for EST_ComputedNoexcept.");
197 assert(NR != FunctionProtoType::NR_Dependent &&
198 "Should not generate implicit declarations for dependent cases, "
199 "and don't know how to handle them anyway.");
200
201 // noexcept(false) -> no spec on the new function
202 if (NR == FunctionProtoType::NR_Throw) {
203 ClearExceptions();
204 ComputedEST = EST_None;
205 }
206 // noexcept(true) won't change anything either.
207 return;
208 }
209
210 assert(EST == EST_Dynamic && "EST case not considered earlier.");
211 assert(ComputedEST != EST_None &&
212 "Shouldn't collect exceptions when throw-all is guaranteed.");
213 ComputedEST = EST_Dynamic;
214 // Record the exceptions in this function's exception specification.
215 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
216 EEnd = Proto->exception_end();
217 E != EEnd; ++E)
Richard Smithf623c962012-04-17 00:58:00 +0000218 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000219 Exceptions.push_back(*E);
220}
221
Richard Smith938f40b2011-06-11 17:19:42 +0000222void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000223 if (!E || ComputedEST == EST_MSAny)
Richard Smith938f40b2011-06-11 17:19:42 +0000224 return;
225
226 // FIXME:
227 //
228 // C++0x [except.spec]p14:
NAKAMURA Takumi53648472011-06-21 03:19:28 +0000229 // [An] implicit exception-specification specifies the type-id T if and
230 // only if T is allowed by the exception-specification of a function directly
231 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith938f40b2011-06-11 17:19:42 +0000232 // function it directly invokes allows all exceptions, and f shall allow no
233 // exceptions if every function it directly invokes allows no exceptions.
234 //
235 // Note in particular that if an implicit exception-specification is generated
236 // for a function containing a throw-expression, that specification can still
237 // be noexcept(true).
238 //
239 // Note also that 'directly invoked' is not defined in the standard, and there
240 // is no indication that we should only consider potentially-evaluated calls.
241 //
242 // Ultimately we should implement the intent of the standard: the exception
243 // specification should be the set of exceptions which can be thrown by the
244 // implicit definition. For now, we assume that any non-nothrow expression can
245 // throw any exception.
246
Richard Smithf623c962012-04-17 00:58:00 +0000247 if (Self->canThrow(E))
Richard Smith938f40b2011-06-11 17:19:42 +0000248 ComputedEST = EST_None;
249}
250
Anders Carlssonc80a1272009-08-25 02:29:20 +0000251bool
John McCallb268a282010-08-23 23:25:46 +0000252Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000253 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000254 if (RequireCompleteType(Param->getLocation(), Param->getType(),
255 diag::err_typecheck_decl_incomplete_type)) {
256 Param->setInvalidDecl();
257 return true;
258 }
259
Anders Carlssonc80a1272009-08-25 02:29:20 +0000260 // C++ [dcl.fct.default]p5
261 // A default argument expression is implicitly converted (clause
262 // 4) to the parameter type. The default argument expression has
263 // the same semantic constraints as the initializer expression in
264 // a declaration of a variable of the parameter type, using the
265 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000266 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
267 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000268 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
269 EqualLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000270 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000271 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman5f101b92009-12-22 02:46:13 +0000272 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000273 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000274 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000275
Richard Smithc406cb72013-01-17 01:17:56 +0000276 CheckCompletedExpr(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000277 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000278
Anders Carlssonc80a1272009-08-25 02:29:20 +0000279 // Okay: add the default argument to the parameter
280 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000281
Douglas Gregor758cb672010-10-12 18:23:32 +0000282 // We have already instantiated this parameter; provide each of the
283 // instantiations with the uninstantiated default argument.
284 UnparsedDefaultArgInstantiationsMap::iterator InstPos
285 = UnparsedDefaultArgInstantiations.find(Param);
286 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
287 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
288 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
289
290 // We're done tracking this parameter's instantiations.
291 UnparsedDefaultArgInstantiations.erase(InstPos);
292 }
293
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000294 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000295}
296
Chris Lattner58258242008-04-10 02:22:51 +0000297/// ActOnParamDefaultArgument - Check whether the default argument
298/// provided for a function parameter is well-formed. If so, attach it
299/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000300void
John McCall48871652010-08-21 09:40:31 +0000301Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000302 Expr *DefaultArg) {
303 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000304 return;
Mike Stump11289f42009-09-09 15:08:12 +0000305
John McCall48871652010-08-21 09:40:31 +0000306 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000307 UnparsedDefaultArgLocs.erase(Param);
308
Chris Lattner199abbc2008-04-08 05:04:30 +0000309 // Default arguments are only permitted in C++
David Blaikiebbafb8a2012-03-11 07:00:24 +0000310 if (!getLangOpts().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000311 Diag(EqualLoc, diag::err_param_default_argument)
312 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000313 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000314 return;
315 }
316
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000317 // Check for unexpanded parameter packs.
318 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
319 Param->setInvalidDecl();
320 return;
321 }
322
Anders Carlssonf1c26952009-08-25 01:02:06 +0000323 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000324 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
325 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000326 Param->setInvalidDecl();
327 return;
328 }
Mike Stump11289f42009-09-09 15:08:12 +0000329
John McCallb268a282010-08-23 23:25:46 +0000330 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000331}
332
Douglas Gregor58354032008-12-24 00:01:03 +0000333/// ActOnParamUnparsedDefaultArgument - We've seen a default
334/// argument for a function parameter, but we can't parse it yet
335/// because we're inside a class definition. Note that this default
336/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000337void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000338 SourceLocation EqualLoc,
339 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000340 if (!param)
341 return;
Mike Stump11289f42009-09-09 15:08:12 +0000342
John McCall48871652010-08-21 09:40:31 +0000343 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Nick Lewycky0f292892013-09-22 10:06:57 +0000344 Param->setUnparsedDefaultArg();
Anders Carlsson84613c42009-06-12 16:51:40 +0000345 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000346}
347
Douglas Gregor4d87df52008-12-16 21:30:33 +0000348/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
349/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000350void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000351 if (!param)
352 return;
Mike Stump11289f42009-09-09 15:08:12 +0000353
John McCall48871652010-08-21 09:40:31 +0000354 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000355 Param->setInvalidDecl();
Anders Carlsson84613c42009-06-12 16:51:40 +0000356 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000357}
358
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000359/// CheckExtraCXXDefaultArguments - Check for any extra default
360/// arguments in the declarator, which is not a function declaration
361/// or definition and therefore is not permitted to have default
362/// arguments. This routine should be invoked for every declarator
363/// that is not a function declaration or definition.
364void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
365 // C++ [dcl.fct.default]p3
366 // A default argument expression shall be specified only in the
367 // parameter-declaration-clause of a function declaration or in a
368 // template-parameter (14.1). It shall not be specified for a
369 // parameter pack. If it is specified in a
370 // parameter-declaration-clause, it shall not occur within a
371 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000372 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattner83f095c2009-03-28 19:18:32 +0000373 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000374 DeclaratorChunk &chunk = D.getTypeObject(i);
375 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000376 if (MightBeFunction) {
377 // This is a function declaration. It can have default arguments, but
378 // keep looking in case its return type is a function type with default
379 // arguments.
380 MightBeFunction = false;
381 continue;
382 }
Alp Tokerc5350722014-02-26 22:27:52 +0000383 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
384 ++argIdx) {
385 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000386 if (Param->hasUnparsedDefaultArg()) {
Alp Tokerc5350722014-02-26 22:27:52 +0000387 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000388 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000389 << SourceRange((*Toks)[1].getLocation(),
390 Toks->back().getLocation());
Douglas Gregor4d87df52008-12-16 21:30:33 +0000391 delete Toks;
Alp Tokerc5350722014-02-26 22:27:52 +0000392 chunk.Fun.Params[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000393 } else if (Param->getDefaultArg()) {
394 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
395 << Param->getDefaultArg()->getSourceRange();
396 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000397 }
398 }
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000399 } else if (chunk.Kind != DeclaratorChunk::Paren) {
400 MightBeFunction = false;
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000401 }
402 }
403}
404
David Majnemer502b0ed2013-06-25 23:09:30 +0000405static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
406 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
407 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
408 if (!PVD->hasDefaultArg())
409 return false;
410 if (!PVD->hasInheritedDefaultArg())
411 return true;
412 }
413 return false;
414}
415
Craig Toppere4794282012-09-21 04:33:26 +0000416/// MergeCXXFunctionDecl - Merge two declarations of the same C++
417/// function, once we already know that they have the same
418/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
419/// error, false otherwise.
James Molloye9430032012-03-13 08:55:35 +0000420bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
421 Scope *S) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000422 bool Invalid = false;
423
Chris Lattner199abbc2008-04-08 05:04:30 +0000424 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000425 // For non-template functions, default arguments can be added in
426 // later declarations of a function in the same
427 // scope. Declarations in different scopes have completely
428 // distinct sets of default arguments. That is, declarations in
429 // inner scopes do not acquire default arguments from
430 // declarations in outer scopes, and vice versa. In a given
431 // function declaration, all parameters subsequent to a
432 // parameter with a default argument shall have default
433 // arguments supplied in this or previous declarations. A
434 // default argument shall not be redefined by a later
435 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000436 //
437 // C++ [dcl.fct.default]p6:
Richard Smith541b38b2013-09-20 01:15:31 +0000438 // Except for member functions of class templates, the default arguments
439 // in a member function definition that appears outside of the class
440 // definition are added to the set of default arguments provided by the
Douglas Gregorc732aba2009-09-11 18:44:32 +0000441 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000442 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
443 ParmVarDecl *OldParam = Old->getParamDecl(p);
444 ParmVarDecl *NewParam = New->getParamDecl(p);
445
James Molloye9430032012-03-13 08:55:35 +0000446 bool OldParamHasDfl = OldParam->hasDefaultArg();
447 bool NewParamHasDfl = NewParam->hasDefaultArg();
448
449 NamedDecl *ND = Old;
Richard Smith541b38b2013-09-20 01:15:31 +0000450
451 // The declaration context corresponding to the scope is the semantic
452 // parent, unless this is a local function declaration, in which case
453 // it is that surrounding function.
454 DeclContext *ScopeDC = New->getLexicalDeclContext();
455 if (!ScopeDC->isFunctionOrMethod())
456 ScopeDC = New->getDeclContext();
457 if (S && !isDeclInScope(ND, ScopeDC, S) &&
458 !New->getDeclContext()->isRecord())
James Molloye9430032012-03-13 08:55:35 +0000459 // Ignore default parameters of old decl if they are not in
Richard Smith541b38b2013-09-20 01:15:31 +0000460 // the same scope and this is not an out-of-line definition of
461 // a member function.
James Molloye9430032012-03-13 08:55:35 +0000462 OldParamHasDfl = false;
463
464 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000465
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000466 unsigned DiagDefaultParamID =
467 diag::err_param_default_argument_redefinition;
468
469 // MSVC accepts that default parameters be redefined for member functions
470 // of template class. The new default parameter's value is ignored.
471 Invalid = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000472 if (getLangOpts().MicrosoftExt) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000473 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
474 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000475 // Merge the old default argument into the new parameter.
476 NewParam->setHasInheritedDefaultArg();
477 if (OldParam->hasUninstantiatedDefaultArg())
478 NewParam->setUninstantiatedDefaultArg(
479 OldParam->getUninstantiatedDefaultArg());
480 else
481 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichet93921652011-04-22 08:25:24 +0000482 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000483 Invalid = false;
484 }
485 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000486
Francois Pichet8cb243a2011-04-10 04:58:30 +0000487 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
488 // hint here. Alternatively, we could walk the type-source information
489 // for NewParam to find the last source location in the type... but it
490 // isn't worth the effort right now. This is the kind of test case that
491 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000492 // int f(int);
493 // void g(int (*fp)(int) = f);
494 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000495 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000496 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000497
498 // Look for the function declaration where the default argument was
499 // actually written, which may be a declaration prior to Old.
Douglas Gregorec9fd132012-01-14 16:38:05 +0000500 for (FunctionDecl *Older = Old->getPreviousDecl();
501 Older; Older = Older->getPreviousDecl()) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000502 if (!Older->getParamDecl(p)->hasDefaultArg())
503 break;
504
505 OldParam = Older->getParamDecl(p);
506 }
507
508 Diag(OldParam->getLocation(), diag::note_previous_definition)
509 << OldParam->getDefaultArgRange();
James Molloye9430032012-03-13 08:55:35 +0000510 } else if (OldParamHasDfl) {
John McCalle61b02b2010-05-04 01:53:42 +0000511 // Merge the old default argument into the new parameter.
512 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000513 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000514 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000515 if (OldParam->hasUninstantiatedDefaultArg())
516 NewParam->setUninstantiatedDefaultArg(
517 OldParam->getUninstantiatedDefaultArg());
518 else
John McCalle61b02b2010-05-04 01:53:42 +0000519 NewParam->setDefaultArg(OldParam->getInit());
James Molloye9430032012-03-13 08:55:35 +0000520 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000521 if (New->getDescribedFunctionTemplate()) {
522 // Paragraph 4, quoted above, only applies to non-template functions.
523 Diag(NewParam->getLocation(),
524 diag::err_param_default_argument_template_redecl)
525 << NewParam->getDefaultArgRange();
526 Diag(Old->getLocation(), diag::note_template_prev_declaration)
527 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000528 } else if (New->getTemplateSpecializationKind()
529 != TSK_ImplicitInstantiation &&
530 New->getTemplateSpecializationKind() != TSK_Undeclared) {
531 // C++ [temp.expr.spec]p21:
532 // Default function arguments shall not be specified in a declaration
533 // or a definition for one of the following explicit specializations:
534 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000535 // - the explicit specialization of a member function template;
536 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000537 // template where the class template specialization to which the
538 // member function specialization belongs is implicitly
539 // instantiated.
540 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
541 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
542 << New->getDeclName()
543 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000544 } else if (New->getDeclContext()->isDependentContext()) {
545 // C++ [dcl.fct.default]p6 (DR217):
546 // Default arguments for a member function of a class template shall
547 // be specified on the initial declaration of the member function
548 // within the class template.
549 //
550 // Reading the tea leaves a bit in DR217 and its reference to DR205
551 // leads me to the conclusion that one cannot add default function
552 // arguments for an out-of-line definition of a member function of a
553 // dependent type.
554 int WhichKind = 2;
555 if (CXXRecordDecl *Record
556 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
557 if (Record->getDescribedClassTemplate())
558 WhichKind = 0;
559 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
560 WhichKind = 1;
561 else
562 WhichKind = 2;
563 }
564
565 Diag(NewParam->getLocation(),
566 diag::err_param_default_argument_member_template_redecl)
567 << WhichKind
568 << NewParam->getDefaultArgRange();
569 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000570 }
571 }
572
Richard Smith58c3cc12012-11-28 03:45:24 +0000573 // DR1344: If a default argument is added outside a class definition and that
574 // default argument makes the function a special member function, the program
575 // is ill-formed. This can only happen for constructors.
576 if (isa<CXXConstructorDecl>(New) &&
577 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
578 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
579 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
580 if (NewSM != OldSM) {
581 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
582 assert(NewParam->hasDefaultArg());
583 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
584 << NewParam->getDefaultArgRange() << NewSM;
585 Diag(Old->getLocation(), diag::note_previous_declaration);
586 }
587 }
588
Richard Smith5b8b3db2012-02-20 23:28:05 +0000589 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000590 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000591 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000592 if (New->isConstexpr() != Old->isConstexpr()) {
593 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
594 << New << New->isConstexpr();
595 Diag(Old->getLocation(), diag::note_previous_declaration);
596 Invalid = true;
597 }
598
David Majnemer502b0ed2013-06-25 23:09:30 +0000599 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000600 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000601 // the only declaration of the function or function template in the
602 // translation unit.
603 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
604 functionDeclHasDefaultArgument(Old)) {
605 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
606 Diag(Old->getLocation(), diag::note_previous_declaration);
607 Invalid = true;
608 }
609
Douglas Gregorf40863c2010-02-12 07:32:17 +0000610 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000611 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000612
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000613 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000614}
615
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000616/// \brief Merge the exception specifications of two variable declarations.
617///
618/// This is called when there's a redeclaration of a VarDecl. The function
619/// checks if the redeclaration might have an exception specification and
620/// validates compatibility and merges the specs if necessary.
621void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
622 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000623 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000624 return;
625
626 assert(Context.hasSameType(New->getType(), Old->getType()) &&
627 "Should only be called if types are otherwise the same.");
628
629 QualType NewType = New->getType();
630 QualType OldType = Old->getType();
631
632 // We're only interested in pointers and references to functions, as well
633 // as pointers to member functions.
634 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
635 NewType = R->getPointeeType();
636 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
637 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
638 NewType = P->getPointeeType();
639 OldType = OldType->getAs<PointerType>()->getPointeeType();
640 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
641 NewType = M->getPointeeType();
642 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
643 }
644
645 if (!NewType->isFunctionProtoType())
646 return;
647
648 // There's lots of special cases for functions. For function pointers, system
649 // libraries are hopefully not as broken so that we don't need these
650 // workarounds.
651 if (CheckEquivalentExceptionSpec(
652 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
653 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
654 New->setInvalidDecl();
655 }
656}
657
Chris Lattner199abbc2008-04-08 05:04:30 +0000658/// CheckCXXDefaultArguments - Verify that the default arguments for a
659/// function declaration are well-formed according to C++
660/// [dcl.fct.default].
661void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
662 unsigned NumParams = FD->getNumParams();
663 unsigned p;
664
665 // Find first parameter with a default argument
666 for (p = 0; p < NumParams; ++p) {
667 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +0000668 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000669 break;
670 }
671
672 // C++ [dcl.fct.default]p4:
673 // In a given function declaration, all parameters
674 // subsequent to a parameter with a default argument shall
675 // have default arguments supplied in this or previous
676 // declarations. A default argument shall not be redefined
677 // by a later declaration (not even to the same value).
678 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000679 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000680 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000681 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000682 if (Param->isInvalidDecl())
683 /* We already complained about this parameter. */;
684 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000685 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000686 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000687 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000688 else
Mike Stump11289f42009-09-09 15:08:12 +0000689 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000690 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000691
Chris Lattner199abbc2008-04-08 05:04:30 +0000692 LastMissingDefaultArg = p;
693 }
694 }
695
696 if (LastMissingDefaultArg > 0) {
697 // Some default arguments were missing. Clear out all of the
698 // default arguments up to (and including) the last missing
699 // default argument, so that we leave the function parameters
700 // in a semantically valid state.
701 for (p = 0; p <= LastMissingDefaultArg; ++p) {
702 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000703 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000704 Param->setDefaultArg(0);
705 }
706 }
707 }
708}
Douglas Gregor556877c2008-04-13 21:30:24 +0000709
Richard Smitheb3c10c2011-10-01 02:31:28 +0000710// CheckConstexprParameterTypes - Check whether a function's parameter types
711// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +0000712// diagnostic and return false.
713static bool CheckConstexprParameterTypes(Sema &SemaRef,
714 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000715 unsigned ArgIndex = 0;
716 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +0000717 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
718 e = FT->param_type_end();
719 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000720 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
721 SourceLocation ParamLoc = PD->getLocation();
722 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000723 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000724 diag::err_constexpr_non_literal_param,
725 ArgIndex+1, PD->getSourceRange(),
726 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000727 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000728 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000729 return true;
730}
731
732/// \brief Get diagnostic %select index for tag kind for
733/// record diagnostic message.
734/// WARNING: Indexes apply to particular diagnostics only!
735///
736/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +0000737static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +0000738 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +0000739 case TTK_Struct: return 0;
740 case TTK_Interface: return 1;
741 case TTK_Class: return 2;
742 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +0000743 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000744}
745
746// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
747// the requirements of a constexpr function definition or a constexpr
748// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +0000749// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000750//
Richard Smith3607ffe2012-02-13 03:54:03 +0000751// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
752bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +0000753 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
754 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000755 // C++11 [dcl.constexpr]p4:
756 // The definition of a constexpr constructor shall satisfy the following
757 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000758 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +0000759 const CXXRecordDecl *RD = MD->getParent();
760 if (RD->getNumVBases()) {
761 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
762 << isa<CXXConstructorDecl>(NewFD)
763 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
764 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
765 E = RD->vbases_end(); I != E; ++I)
766 Diag(I->getLocStart(),
Richard Smith3607ffe2012-02-13 03:54:03 +0000767 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000768 return false;
769 }
Richard Smith7971b692012-01-13 04:54:00 +0000770 }
771
772 if (!isa<CXXConstructorDecl>(NewFD)) {
773 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000774 // The definition of a constexpr function shall satisfy the following
775 // constraints:
776 // - it shall not be virtual;
777 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
778 if (Method && Method->isVirtual()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000779 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000780
Richard Smith3607ffe2012-02-13 03:54:03 +0000781 // If it's not obvious why this function is virtual, find an overridden
782 // function which uses the 'virtual' keyword.
783 const CXXMethodDecl *WrittenVirtual = Method;
784 while (!WrittenVirtual->isVirtualAsWritten())
785 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
786 if (WrittenVirtual != Method)
787 Diag(WrittenVirtual->getLocation(),
788 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000789 return false;
790 }
791
792 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +0000793 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000794 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000795 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000796 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000797 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000798 }
799
Richard Smith7971b692012-01-13 04:54:00 +0000800 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +0000801 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +0000802 return false;
803
Richard Smitheb3c10c2011-10-01 02:31:28 +0000804 return true;
805}
806
807/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +0000808/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000809///
Richard Smithd9f663b2013-04-22 15:31:51 +0000810/// \return true if the body is OK (maybe only as an extension), false if we
811/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000812static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +0000813 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
814 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000815 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
816 // contain only
817 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
818 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
819 switch ((*DclIt)->getKind()) {
820 case Decl::StaticAssert:
821 case Decl::Using:
822 case Decl::UsingShadow:
823 case Decl::UsingDirective:
824 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +0000825 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000826 // - static_assert-declarations
827 // - using-declarations,
828 // - using-directives,
829 continue;
830
831 case Decl::Typedef:
832 case Decl::TypeAlias: {
833 // - typedef declarations and alias-declarations that do not define
834 // classes or enumerations,
835 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
836 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
837 // Don't allow variably-modified types in constexpr functions.
838 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
839 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
840 << TL.getSourceRange() << TL.getType()
841 << isa<CXXConstructorDecl>(Dcl);
842 return false;
843 }
844 continue;
845 }
846
847 case Decl::Enum:
848 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +0000849 // C++1y allows types to be defined, not just declared.
850 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
851 SemaRef.Diag(DS->getLocStart(),
852 SemaRef.getLangOpts().CPlusPlus1y
853 ? diag::warn_cxx11_compat_constexpr_type_definition
854 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000855 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000856 continue;
857
Richard Smithd9f663b2013-04-22 15:31:51 +0000858 case Decl::EnumConstant:
859 case Decl::IndirectField:
860 case Decl::ParmVar:
861 // These can only appear with other declarations which are banned in
862 // C++11 and permitted in C++1y, so ignore them.
863 continue;
864
865 case Decl::Var: {
866 // C++1y [dcl.constexpr]p3 allows anything except:
867 // a definition of a variable of non-literal type or of static or
868 // thread storage duration or for which no initialization is performed.
869 VarDecl *VD = cast<VarDecl>(*DclIt);
870 if (VD->isThisDeclarationADefinition()) {
871 if (VD->isStaticLocal()) {
872 SemaRef.Diag(VD->getLocation(),
873 diag::err_constexpr_local_var_static)
874 << isa<CXXConstructorDecl>(Dcl)
875 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
876 return false;
877 }
Richard Smith3da88fa2013-04-26 14:36:30 +0000878 if (!VD->getType()->isDependentType() &&
879 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +0000880 VD->getLocation(), VD->getType(),
881 diag::err_constexpr_local_var_non_literal_type,
882 isa<CXXConstructorDecl>(Dcl)))
883 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +0000884 if (!VD->getType()->isDependentType() &&
885 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000886 SemaRef.Diag(VD->getLocation(),
887 diag::err_constexpr_local_var_no_init)
888 << isa<CXXConstructorDecl>(Dcl);
889 return false;
890 }
891 }
892 SemaRef.Diag(VD->getLocation(),
893 SemaRef.getLangOpts().CPlusPlus1y
894 ? diag::warn_cxx11_compat_constexpr_local_var
895 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000896 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +0000897 continue;
898 }
899
900 case Decl::NamespaceAlias:
901 case Decl::Function:
902 // These are disallowed in C++11 and permitted in C++1y. Allow them
903 // everywhere as an extension.
904 if (!Cxx1yLoc.isValid())
905 Cxx1yLoc = DS->getLocStart();
906 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000907
908 default:
909 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
910 << isa<CXXConstructorDecl>(Dcl);
911 return false;
912 }
913 }
914
915 return true;
916}
917
918/// Check that the given field is initialized within a constexpr constructor.
919///
920/// \param Dcl The constexpr constructor being checked.
921/// \param Field The field being checked. This may be a member of an anonymous
922/// struct or union nested within the class being checked.
923/// \param Inits All declarations, including anonymous struct/union members and
924/// indirect members, for which any initialization was provided.
925/// \param Diagnosed Set to true if an error is produced.
926static void CheckConstexprCtorInitializer(Sema &SemaRef,
927 const FunctionDecl *Dcl,
928 FieldDecl *Field,
929 llvm::SmallSet<Decl*, 16> &Inits,
930 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +0000931 if (Field->isInvalidDecl())
932 return;
933
Douglas Gregor556e5862011-10-10 17:22:13 +0000934 if (Field->isUnnamedBitfield())
935 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +0000936
Richard Smithab44d5b2013-12-10 08:25:00 +0000937 // Anonymous unions with no variant members and empty anonymous structs do not
938 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
939 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +0000940 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +0000941 (Field->getType()->isUnionType()
942 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
943 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +0000944 return;
945
Richard Smitheb3c10c2011-10-01 02:31:28 +0000946 if (!Inits.count(Field)) {
947 if (!Diagnosed) {
948 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
949 Diagnosed = true;
950 }
951 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
952 } else if (Field->isAnonymousStructOrUnion()) {
953 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
954 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
955 I != E; ++I)
956 // If an anonymous union contains an anonymous struct of which any member
957 // is initialized, all members must be initialized.
David Blaikie40ed2972012-06-06 20:45:41 +0000958 if (!RD->isUnion() || Inits.count(*I))
959 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000960 }
961}
962
Richard Smithd9f663b2013-04-22 15:31:51 +0000963/// Check the provided statement is allowed in a constexpr function
964/// definition.
965static bool
966CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +0000967 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +0000968 SourceLocation &Cxx1yLoc) {
969 // - its function-body shall be [...] a compound-statement that contains only
970 switch (S->getStmtClass()) {
971 case Stmt::NullStmtClass:
972 // - null statements,
973 return true;
974
975 case Stmt::DeclStmtClass:
976 // - static_assert-declarations
977 // - using-declarations,
978 // - using-directives,
979 // - typedef declarations and alias-declarations that do not define
980 // classes or enumerations,
981 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
982 return false;
983 return true;
984
985 case Stmt::ReturnStmtClass:
986 // - and exactly one return statement;
987 if (isa<CXXConstructorDecl>(Dcl)) {
988 // C++1y allows return statements in constexpr constructors.
989 if (!Cxx1yLoc.isValid())
990 Cxx1yLoc = S->getLocStart();
991 return true;
992 }
993
994 ReturnStmts.push_back(S->getLocStart());
995 return true;
996
997 case Stmt::CompoundStmtClass: {
998 // C++1y allows compound-statements.
999 if (!Cxx1yLoc.isValid())
1000 Cxx1yLoc = S->getLocStart();
1001
1002 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1003 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
1004 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
1005 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
1006 Cxx1yLoc))
1007 return false;
1008 }
1009 return true;
1010 }
1011
1012 case Stmt::AttributedStmtClass:
1013 if (!Cxx1yLoc.isValid())
1014 Cxx1yLoc = S->getLocStart();
1015 return true;
1016
1017 case Stmt::IfStmtClass: {
1018 // C++1y allows if-statements.
1019 if (!Cxx1yLoc.isValid())
1020 Cxx1yLoc = S->getLocStart();
1021
1022 IfStmt *If = cast<IfStmt>(S);
1023 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1024 Cxx1yLoc))
1025 return false;
1026 if (If->getElse() &&
1027 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1028 Cxx1yLoc))
1029 return false;
1030 return true;
1031 }
1032
1033 case Stmt::WhileStmtClass:
1034 case Stmt::DoStmtClass:
1035 case Stmt::ForStmtClass:
1036 case Stmt::CXXForRangeStmtClass:
1037 case Stmt::ContinueStmtClass:
1038 // C++1y allows all of these. We don't allow them as extensions in C++11,
1039 // because they don't make sense without variable mutation.
1040 if (!SemaRef.getLangOpts().CPlusPlus1y)
1041 break;
1042 if (!Cxx1yLoc.isValid())
1043 Cxx1yLoc = S->getLocStart();
1044 for (Stmt::child_range Children = S->children(); Children; ++Children)
1045 if (*Children &&
1046 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1047 Cxx1yLoc))
1048 return false;
1049 return true;
1050
1051 case Stmt::SwitchStmtClass:
1052 case Stmt::CaseStmtClass:
1053 case Stmt::DefaultStmtClass:
1054 case Stmt::BreakStmtClass:
1055 // C++1y allows switch-statements, and since they don't need variable
1056 // mutation, we can reasonably allow them in C++11 as an extension.
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 default:
1067 if (!isa<Expr>(S))
1068 break;
1069
1070 // C++1y allows expression-statements.
1071 if (!Cxx1yLoc.isValid())
1072 Cxx1yLoc = S->getLocStart();
1073 return true;
1074 }
1075
1076 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1077 << isa<CXXConstructorDecl>(Dcl);
1078 return false;
1079}
1080
Richard Smitheb3c10c2011-10-01 02:31:28 +00001081/// Check the body for the given constexpr function declaration only contains
1082/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1083///
1084/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001085bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001086 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001087 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001088 // The definition of a constexpr function shall satisfy the following
1089 // constraints: [...]
1090 // - its function-body shall be = delete, = default, or a
1091 // compound-statement
1092 //
Richard Smith74388b42012-02-04 00:33:54 +00001093 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001094 // In the definition of a constexpr constructor, [...]
1095 // - its function-body shall not be a function-try-block;
1096 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1097 << isa<CXXConstructorDecl>(Dcl);
1098 return false;
1099 }
1100
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001101 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001102
1103 // - its function-body shall be [...] a compound-statement that contains only
1104 // [... list of cases ...]
1105 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1106 SourceLocation Cxx1yLoc;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001107 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1108 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001109 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1110 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001111 }
1112
Richard Smithd9f663b2013-04-22 15:31:51 +00001113 if (Cxx1yLoc.isValid())
1114 Diag(Cxx1yLoc,
1115 getLangOpts().CPlusPlus1y
1116 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1117 : diag::ext_constexpr_body_invalid_stmt)
1118 << isa<CXXConstructorDecl>(Dcl);
1119
Richard Smitheb3c10c2011-10-01 02:31:28 +00001120 if (const CXXConstructorDecl *Constructor
1121 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1122 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001123 // DR1359:
1124 // - every non-variant non-static data member and base class sub-object
1125 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001126 // DR1460:
1127 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001128 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001129 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001130 if (Constructor->getNumCtorInitializers() == 0 &&
1131 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001132 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1133 return false;
1134 }
Richard Smithf368fb42011-10-10 16:38:04 +00001135 } else if (!Constructor->isDependentContext() &&
1136 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001137 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1138
1139 // Skip detailed checking if we have enough initializers, and we would
1140 // allow at most one initializer per member.
1141 bool AnyAnonStructUnionMembers = false;
1142 unsigned Fields = 0;
1143 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1144 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001145 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001146 AnyAnonStructUnionMembers = true;
1147 break;
1148 }
1149 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001150 // DR1460:
1151 // - if the class is a union-like class, but is not a union, for each of
1152 // its anonymous union members having variant members, exactly one of
1153 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001154 if (AnyAnonStructUnionMembers ||
1155 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1156 // Check initialization of non-static data members. Base classes are
1157 // always initialized so do not need to be checked. Dependent bases
1158 // might not have initializers in the member initializer list.
1159 llvm::SmallSet<Decl*, 16> Inits;
1160 for (CXXConstructorDecl::init_const_iterator
1161 I = Constructor->init_begin(), E = Constructor->init_end();
1162 I != E; ++I) {
1163 if (FieldDecl *FD = (*I)->getMember())
1164 Inits.insert(FD);
1165 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1166 Inits.insert(ID->chain_begin(), ID->chain_end());
1167 }
1168
1169 bool Diagnosed = false;
1170 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1171 E = RD->field_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001172 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001173 if (Diagnosed)
1174 return false;
1175 }
1176 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001177 } else {
1178 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001179 // C++1y doesn't require constexpr functions to contain a 'return'
1180 // statement. We still do, unless the return type is void, because
1181 // otherwise if there's no return statement, the function cannot
1182 // be used in a core constant expression.
Alp Toker314cc812014-01-25 16:55:45 +00001183 bool OK = getLangOpts().CPlusPlus1y && Dcl->getReturnType()->isVoidType();
Richard Smithd9f663b2013-04-22 15:31:51 +00001184 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00001185 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1186 : diag::err_constexpr_body_no_return);
1187 return OK;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001188 }
1189 if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001190 Diag(ReturnStmts.back(),
1191 getLangOpts().CPlusPlus1y
1192 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1193 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001194 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1195 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001196 }
1197 }
1198
Richard Smith74388b42012-02-04 00:33:54 +00001199 // C++11 [dcl.constexpr]p5:
1200 // if no function argument values exist such that the function invocation
1201 // substitution would produce a constant expression, the program is
1202 // ill-formed; no diagnostic required.
1203 // C++11 [dcl.constexpr]p3:
1204 // - every constructor call and implicit conversion used in initializing the
1205 // return value shall be one of those allowed in a constant expression.
1206 // C++11 [dcl.constexpr]p4:
1207 // - every constructor involved in initializing non-static data members and
1208 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001209 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00001210 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00001211 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00001212 << isa<CXXConstructorDecl>(Dcl);
1213 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1214 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00001215 // Don't return false here: we allow this for compatibility in
1216 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00001217 }
1218
Richard Smitheb3c10c2011-10-01 02:31:28 +00001219 return true;
1220}
1221
Douglas Gregor61956c42008-10-31 09:07:45 +00001222/// isCurrentClassName - Determine whether the identifier II is the
1223/// name of the class type currently being defined. In the case of
1224/// nested classes, this will only return true if II is the name of
1225/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001226bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1227 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001228 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00001229
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001230 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00001231 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00001232 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001233 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1234 } else
1235 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1236
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00001237 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00001238 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00001239 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00001240}
1241
Richard Smithfb8b7b92013-10-15 00:00:26 +00001242/// \brief Determine whether the identifier II is a typo for the name of
1243/// the class type currently being defined. If so, update it to the identifier
1244/// that should have been used.
1245bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1246 assert(getLangOpts().CPlusPlus && "No class names in C!");
1247
1248 if (!getLangOpts().SpellChecking)
1249 return false;
1250
1251 CXXRecordDecl *CurDecl;
1252 if (SS && SS->isSet() && !SS->isInvalid()) {
1253 DeclContext *DC = computeDeclContext(*SS, true);
1254 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1255 } else
1256 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1257
1258 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1259 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1260 < II->getLength()) {
1261 II = CurDecl->getIdentifier();
1262 return true;
1263 }
1264
1265 return false;
1266}
1267
Douglas Gregordc974572012-11-10 07:24:09 +00001268/// \brief Determine whether the given class is a base class of the given
1269/// class, including looking at dependent bases.
1270static bool findCircularInheritance(const CXXRecordDecl *Class,
1271 const CXXRecordDecl *Current) {
1272 SmallVector<const CXXRecordDecl*, 8> Queue;
1273
1274 Class = Class->getCanonicalDecl();
1275 while (true) {
1276 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1277 E = Current->bases_end();
1278 I != E; ++I) {
1279 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1280 if (!Base)
1281 continue;
1282
1283 Base = Base->getDefinition();
1284 if (!Base)
1285 continue;
1286
1287 if (Base->getCanonicalDecl() == Class)
1288 return true;
1289
1290 Queue.push_back(Base);
1291 }
1292
1293 if (Queue.empty())
1294 return false;
1295
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001296 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00001297 }
1298
1299 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00001300}
1301
Mike Stump11289f42009-09-09 15:08:12 +00001302/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001303///
1304/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1305/// and returns NULL otherwise.
1306CXXBaseSpecifier *
1307Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1308 SourceRange SpecifierRange,
1309 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001310 TypeSourceInfo *TInfo,
1311 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001312 QualType BaseType = TInfo->getType();
1313
Douglas Gregor463421d2009-03-03 04:44:36 +00001314 // C++ [class.union]p1:
1315 // A union shall not have base classes.
1316 if (Class->isUnion()) {
1317 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1318 << SpecifierRange;
1319 return 0;
1320 }
1321
Douglas Gregor752a5952011-01-03 22:36:02 +00001322 if (EllipsisLoc.isValid() &&
1323 !TInfo->getType()->containsUnexpandedParameterPack()) {
1324 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1325 << TInfo->getTypeLoc().getSourceRange();
1326 EllipsisLoc = SourceLocation();
1327 }
Douglas Gregor62004702012-11-10 01:18:17 +00001328
1329 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1330
1331 if (BaseType->isDependentType()) {
1332 // Make sure that we don't have circular inheritance among our dependent
1333 // bases. For non-dependent bases, the check for completeness below handles
1334 // this.
1335 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1336 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1337 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00001338 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00001339 Diag(BaseLoc, diag::err_circular_inheritance)
1340 << BaseType << Context.getTypeDeclType(Class);
1341
1342 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1343 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1344 << BaseType;
1345
1346 return 0;
1347 }
1348 }
1349
Mike Stump11289f42009-09-09 15:08:12 +00001350 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001351 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001352 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00001353 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001354
1355 // Base specifiers must be record types.
1356 if (!BaseType->isRecordType()) {
1357 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1358 return 0;
1359 }
1360
1361 // C++ [class.union]p1:
1362 // A union shall not be used as a base class.
1363 if (BaseType->isUnionType()) {
1364 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1365 return 0;
1366 }
1367
1368 // C++ [class.derived]p2:
1369 // The class-name in a base-specifier shall not be an incompletely
1370 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001371 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001372 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00001373 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001374 return 0;
John McCall3696dcb2010-08-17 07:23:57 +00001375 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001376
Eli Friedmanc96d4962009-08-15 21:55:26 +00001377 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001378 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001379 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001380 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001381 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00001382 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00001383 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001384
David Majnemer9b1754d2013-11-02 12:00:36 +00001385 // A class which contains a flexible array member is not suitable for use as a
1386 // base class:
1387 // - If the layout determines that a base comes before another base,
1388 // the flexible array member would index into the subsequent base.
1389 // - If the layout determines that base comes before the derived class,
1390 // the flexible array member would index into the derived class.
1391 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1392 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1393 << CXXBaseDecl->getDeclName();
1394 return 0;
1395 }
1396
Anders Carlsson65c76d32011-03-25 14:55:14 +00001397 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00001398 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00001399 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00001400 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00001401 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00001402 << CXXBaseDecl->getDeclName()
1403 << FA->isSpelledAsSealed();
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001404 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1405 << CXXBaseDecl->getDeclName();
1406 return 0;
1407 }
1408
John McCall3696dcb2010-08-17 07:23:57 +00001409 if (BaseDecl->isInvalidDecl())
1410 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00001411
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001412 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001413 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001414 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001415 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001416}
1417
Douglas Gregor556877c2008-04-13 21:30:24 +00001418/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1419/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001420/// example:
1421/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001422/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001423BaseResult
John McCall48871652010-08-21 09:40:31 +00001424Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00001425 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00001426 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001427 ParsedType basetype, SourceLocation BaseLoc,
1428 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001429 if (!classdecl)
1430 return true;
1431
Douglas Gregorc40290e2009-03-09 23:48:35 +00001432 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001433 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001434 if (!Class)
1435 return true;
1436
Richard Smith4c96e992013-02-19 23:47:15 +00001437 // We do not support any C++11 attributes on base-specifiers yet.
1438 // Diagnose any attributes we see.
1439 if (!Attributes.empty()) {
1440 for (AttributeList *Attr = Attributes.getList(); Attr;
1441 Attr = Attr->getNext()) {
1442 if (Attr->isInvalid() ||
1443 Attr->getKind() == AttributeList::IgnoredAttribute)
1444 continue;
1445 Diag(Attr->getLoc(),
1446 Attr->getKind() == AttributeList::UnknownAttribute
1447 ? diag::warn_unknown_attribute_ignored
1448 : diag::err_base_specifier_attribute)
1449 << Attr->getName();
1450 }
1451 }
1452
Nick Lewycky19b9f952010-07-26 16:56:01 +00001453 TypeSourceInfo *TInfo = 0;
1454 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001455
Douglas Gregor752a5952011-01-03 22:36:02 +00001456 if (EllipsisLoc.isInvalid() &&
1457 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001458 UPPC_BaseType))
1459 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001460
Douglas Gregor463421d2009-03-03 04:44:36 +00001461 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001462 Virtual, Access, TInfo,
1463 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001464 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001465 else
1466 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001467
Douglas Gregor463421d2009-03-03 04:44:36 +00001468 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001469}
Douglas Gregor556877c2008-04-13 21:30:24 +00001470
Douglas Gregor463421d2009-03-03 04:44:36 +00001471/// \brief Performs the actual work of attaching the given base class
1472/// specifiers to a C++ class.
1473bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1474 unsigned NumBases) {
1475 if (NumBases == 0)
1476 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001477
1478 // Used to keep track of which base types we have already seen, so
1479 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001480 // that the key is always the unqualified canonical type of the base
1481 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001482 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1483
1484 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001485 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001486 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001487 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001488 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001489 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001490 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001491
1492 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1493 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00001494 // C++ [class.mi]p3:
1495 // A class shall not be specified as a direct base class of a
1496 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001497 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001498 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001499 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001500 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001501
1502 // Delete the duplicate base class specifier; we're going to
1503 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001504 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001505
1506 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001507 } else {
1508 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001509 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00001510 Bases[NumGoodBases++] = Bases[idx];
John McCalldb632ac2012-09-25 07:32:39 +00001511 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1512 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1513 if (Class->isInterface() &&
1514 (!RD->isInterface() ||
1515 KnownBase->getAccessSpecifier() != AS_public)) {
1516 // The Microsoft extension __interface does not permit bases that
1517 // are not themselves public interfaces.
1518 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1519 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1520 << RD->getSourceRange();
1521 Invalid = true;
1522 }
1523 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00001524 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00001525 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001526 }
1527 }
1528
1529 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001530 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001531
1532 // Delete the remaining (good) base class specifiers, since their
1533 // data has been copied into the CXXRecordDecl.
1534 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001535 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001536
1537 return Invalid;
1538}
1539
1540/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1541/// class, after checking whether there are any duplicate base
1542/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001543void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001544 unsigned NumBases) {
1545 if (!ClassDecl || !Bases || !NumBases)
1546 return;
1547
1548 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelme3cea802013-07-22 05:04:01 +00001549 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001550}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001551
Douglas Gregor36d1b142009-10-06 17:59:45 +00001552/// \brief Determine whether the type \p Derived is a C++ class that is
1553/// derived from the type \p Base.
1554bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001555 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001556 return false;
John McCalle78aac42010-03-10 03:28:59 +00001557
Douglas Gregor45bb4832013-03-26 23:36:30 +00001558 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001559 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001560 return false;
1561
Douglas Gregor45bb4832013-03-26 23:36:30 +00001562 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001563 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001564 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00001565
1566 // If either the base or the derived type is invalid, don't try to
1567 // check whether one is derived from the other.
1568 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1569 return false;
1570
John McCall67da35c2010-02-04 22:26:26 +00001571 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1572 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001573}
1574
1575/// \brief Determine whether the type \p Derived is a C++ class that is
1576/// derived from the type \p Base.
1577bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001578 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001579 return false;
1580
Douglas Gregor45bb4832013-03-26 23:36:30 +00001581 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001582 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001583 return false;
1584
Douglas Gregor45bb4832013-03-26 23:36:30 +00001585 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001586 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001587 return false;
1588
Douglas Gregor36d1b142009-10-06 17:59:45 +00001589 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1590}
1591
Anders Carlssona70cff62010-04-24 19:06:50 +00001592void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001593 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001594 assert(BasePathArray.empty() && "Base path array must be empty!");
1595 assert(Paths.isRecordingPaths() && "Must record paths!");
1596
1597 const CXXBasePath &Path = Paths.front();
1598
1599 // We first go backward and check if we have a virtual base.
1600 // FIXME: It would be better if CXXBasePath had the base specifier for
1601 // the nearest virtual base.
1602 unsigned Start = 0;
1603 for (unsigned I = Path.size(); I != 0; --I) {
1604 if (Path[I - 1].Base->isVirtual()) {
1605 Start = I - 1;
1606 break;
1607 }
1608 }
1609
1610 // Now add all bases.
1611 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001612 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001613}
1614
Douglas Gregor88d292c2010-05-13 16:44:06 +00001615/// \brief Determine whether the given base path includes a virtual
1616/// base class.
John McCallcf142162010-08-07 06:22:56 +00001617bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1618 for (CXXCastPath::const_iterator B = BasePath.begin(),
1619 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +00001620 B != BEnd; ++B)
1621 if ((*B)->isVirtual())
1622 return true;
1623
1624 return false;
1625}
1626
Douglas Gregor36d1b142009-10-06 17:59:45 +00001627/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1628/// conversion (where Derived and Base are class types) is
1629/// well-formed, meaning that the conversion is unambiguous (and
1630/// that all of the base classes are accessible). Returns true
1631/// and emits a diagnostic if the code is ill-formed, returns false
1632/// otherwise. Loc is the location where this routine should point to
1633/// if there is an error, and Range is the source range to highlight
1634/// if there is an error.
1635bool
1636Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001637 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001638 unsigned AmbigiousBaseConvID,
1639 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001640 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001641 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001642 // First, determine whether the path from Derived to Base is
1643 // ambiguous. This is slightly more expensive than checking whether
1644 // the Derived to Base conversion exists, because here we need to
1645 // explore multiple paths to determine if there is an ambiguity.
1646 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1647 /*DetectVirtual=*/false);
1648 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1649 assert(DerivationOkay &&
1650 "Can only be used with a derived-to-base conversion");
1651 (void)DerivationOkay;
1652
1653 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001654 if (InaccessibleBaseID) {
1655 // Check that the base class can be accessed.
1656 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1657 InaccessibleBaseID)) {
1658 case AR_inaccessible:
1659 return true;
1660 case AR_accessible:
1661 case AR_dependent:
1662 case AR_delayed:
1663 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001664 }
John McCall5b0829a2010-02-10 09:31:12 +00001665 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001666
1667 // Build a base path if necessary.
1668 if (BasePath)
1669 BuildBasePathArray(Paths, *BasePath);
1670 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001671 }
1672
David Majnemer626032f2013-06-22 06:43:58 +00001673 if (AmbigiousBaseConvID) {
1674 // We know that the derived-to-base conversion is ambiguous, and
1675 // we're going to produce a diagnostic. Perform the derived-to-base
1676 // search just one more time to compute all of the possible paths so
1677 // that we can print them out. This is more expensive than any of
1678 // the previous derived-to-base checks we've done, but at this point
1679 // performance isn't as much of an issue.
1680 Paths.clear();
1681 Paths.setRecordingPaths(true);
1682 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1683 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1684 (void)StillOkay;
1685
1686 // Build up a textual representation of the ambiguous paths, e.g.,
1687 // D -> B -> A, that will be used to illustrate the ambiguous
1688 // conversions in the diagnostic. We only print one of the paths
1689 // to each base class subobject.
1690 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1691
1692 Diag(Loc, AmbigiousBaseConvID)
1693 << Derived << Base << PathDisplayStr << Range << Name;
1694 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00001695 return true;
1696}
1697
1698bool
1699Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001700 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001701 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001702 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001703 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001704 IgnoreAccess ? 0
1705 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001706 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001707 Loc, Range, DeclarationName(),
1708 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001709}
1710
1711
1712/// @brief Builds a string representing ambiguous paths from a
1713/// specific derived class to different subobjects of the same base
1714/// class.
1715///
1716/// This function builds a string that can be used in error messages
1717/// to show the different paths that one can take through the
1718/// inheritance hierarchy to go from the derived class to different
1719/// subobjects of a base class. The result looks something like this:
1720/// @code
1721/// struct D -> struct B -> struct A
1722/// struct D -> struct C -> struct A
1723/// @endcode
1724std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1725 std::string PathDisplayStr;
1726 std::set<unsigned> DisplayedPaths;
1727 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1728 Path != Paths.end(); ++Path) {
1729 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1730 // We haven't displayed a path to this particular base
1731 // class subobject yet.
1732 PathDisplayStr += "\n ";
1733 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1734 for (CXXBasePath::const_iterator Element = Path->begin();
1735 Element != Path->end(); ++Element)
1736 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1737 }
1738 }
1739
1740 return PathDisplayStr;
1741}
1742
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001743//===----------------------------------------------------------------------===//
1744// C++ class member Handling
1745//===----------------------------------------------------------------------===//
1746
Abramo Bagnarad7340582010-06-05 05:09:32 +00001747/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001748bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1749 SourceLocation ASLoc,
1750 SourceLocation ColonLoc,
1751 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001752 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001753 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001754 ASLoc, ColonLoc);
1755 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001756 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001757}
1758
Richard Smith18f07db2012-08-06 03:25:17 +00001759/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001760void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00001761 if (D->isInvalidDecl())
1762 return;
1763
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001764 // We only care about "override" and "final" declarations.
1765 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1766 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00001767
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001768 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001769
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001770 // We can't check dependent instance methods.
1771 if (MD && MD->isInstance() &&
1772 (MD->getParent()->hasAnyDependentBases() ||
1773 MD->getType()->isDependentType()))
1774 return;
1775
1776 if (MD && !MD->isVirtual()) {
1777 // If we have a non-virtual method, check if if hides a virtual method.
1778 // (In that case, it's most likely the method has the wrong type.)
1779 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1780 FindHiddenVirtualMethods(MD, OverloadedMethods);
1781
1782 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001783 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1784 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001785 diag::override_keyword_hides_virtual_member_function)
1786 << "override" << (OverloadedMethods.size() > 1);
1787 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001788 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001789 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00001790 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1791 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00001792 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001793 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1794 MD->setInvalidDecl();
1795 return;
1796 }
1797 // Fall through into the general case diagnostic.
1798 // FIXME: We might want to attempt typo correction here.
1799 }
1800
1801 if (!MD || !MD->isVirtual()) {
1802 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1803 Diag(OA->getLocation(),
1804 diag::override_keyword_only_allowed_on_virtual_member_functions)
1805 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1806 D->dropAttr<OverrideAttr>();
1807 }
1808 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1809 Diag(FA->getLocation(),
1810 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00001811 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1812 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001813 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00001814 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001815 return;
1816 }
Richard Smith18f07db2012-08-06 03:25:17 +00001817
Richard Smith18f07db2012-08-06 03:25:17 +00001818 // C++11 [class.virtual]p5:
1819 // If a virtual function is marked with the virt-specifier override and
1820 // does not override a member function of a base class, the program is
1821 // ill-formed.
1822 bool HasOverriddenMethods =
1823 MD->begin_overridden_methods() != MD->end_overridden_methods();
1824 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1825 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1826 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00001827}
1828
Richard Smith18f07db2012-08-06 03:25:17 +00001829/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00001830/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00001831/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00001832bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1833 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00001834 FinalAttr *FA = Old->getAttr<FinalAttr>();
1835 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00001836 return false;
1837
1838 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00001839 << New->getDeclName()
1840 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00001841 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1842 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001843}
1844
Daniel Jasper0baec5492012-06-06 08:32:04 +00001845static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00001846 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1847 // FIXME: Destruction of ObjC lifetime types has side-effects.
1848 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1849 return !RD->isCompleteDefinition() ||
1850 !RD->hasTrivialDefaultConstructor() ||
1851 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00001852 return false;
1853}
1854
John McCall5e77d762013-04-16 07:28:30 +00001855static AttributeList *getMSPropertyAttr(AttributeList *list) {
1856 for (AttributeList* it = list; it != 0; it = it->getNext())
1857 if (it->isDeclspecPropertyAttribute())
1858 return it;
1859 return 0;
1860}
1861
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001862/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1863/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001864/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00001865/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1866/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001867NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001868Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001869 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001870 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00001871 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001872 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001873 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1874 DeclarationName Name = NameInfo.getName();
1875 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001876
1877 // For anonymous bitfields, the location should point to the type.
1878 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001879 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001880
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001881 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001882
John McCallb1cd7da2010-06-04 08:34:12 +00001883 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001884 assert(!DS.isFriendSpecified());
1885
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001886 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001887
John McCalldb632ac2012-09-25 07:32:39 +00001888 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1889 // The Microsoft extension __interface only permits public member functions
1890 // and prohibits constructors, destructors, operators, non-public member
1891 // functions, static methods and data members.
1892 unsigned InvalidDecl;
1893 bool ShowDeclName = true;
1894 if (!isFunc)
1895 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1896 else if (AS != AS_public)
1897 InvalidDecl = 2;
1898 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1899 InvalidDecl = 3;
1900 else switch (Name.getNameKind()) {
1901 case DeclarationName::CXXConstructorName:
1902 InvalidDecl = 4;
1903 ShowDeclName = false;
1904 break;
1905
1906 case DeclarationName::CXXDestructorName:
1907 InvalidDecl = 5;
1908 ShowDeclName = false;
1909 break;
1910
1911 case DeclarationName::CXXOperatorName:
1912 case DeclarationName::CXXConversionFunctionName:
1913 InvalidDecl = 6;
1914 break;
1915
1916 default:
1917 InvalidDecl = 0;
1918 break;
1919 }
1920
1921 if (InvalidDecl) {
1922 if (ShowDeclName)
1923 Diag(Loc, diag::err_invalid_member_in_interface)
1924 << (InvalidDecl-1) << Name;
1925 else
1926 Diag(Loc, diag::err_invalid_member_in_interface)
1927 << (InvalidDecl-1) << "";
1928 return 0;
1929 }
1930 }
1931
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001932 // C++ 9.2p6: A member shall not be declared to have automatic storage
1933 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001934 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1935 // data members and cannot be applied to names declared const or static,
1936 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001937 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00001938 case DeclSpec::SCS_unspecified:
1939 case DeclSpec::SCS_typedef:
1940 case DeclSpec::SCS_static:
1941 break;
1942 case DeclSpec::SCS_mutable:
1943 if (isFunc) {
1944 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00001945
Richard Smithb4a9e862013-04-12 22:46:28 +00001946 // FIXME: It would be nicer if the keyword was ignored only for this
1947 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001948 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00001949 }
1950 break;
1951 default:
1952 Diag(DS.getStorageClassSpecLoc(),
1953 diag::err_storageclass_invalid_for_member);
1954 D.getMutableDeclSpec().ClearStorageClassSpecs();
1955 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001956 }
1957
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001958 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1959 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00001960 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001961
David Blaikie35506f82013-01-30 01:22:18 +00001962 if (DS.isConstexprSpecified() && isInstField) {
1963 SemaDiagnosticBuilder B =
1964 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1965 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1966 if (InitStyle == ICIS_NoInit) {
1967 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1968 D.getMutableDeclSpec().ClearConstexprSpec();
1969 const char *PrevSpec;
1970 unsigned DiagID;
1971 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1972 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00001973 (void)Failed;
David Blaikie35506f82013-01-30 01:22:18 +00001974 assert(!Failed && "Making a constexpr member const shouldn't fail");
1975 } else {
1976 B << 1;
1977 const char *PrevSpec;
1978 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00001979 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001980 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
1981 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00001982 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00001983 "This is the only DeclSpec that should fail to be applied");
1984 B << 1;
1985 } else {
1986 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1987 isInstField = false;
1988 }
1989 }
1990 }
1991
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001992 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00001993 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00001994 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00001995
1996 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00001997 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00001998 Diag(Loc, diag::err_bad_variable_name)
1999 << Name;
2000 return 0;
2001 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002002
Benjamin Kramer365082d2012-05-19 16:34:46 +00002003 IdentifierInfo *II = Name.getAsIdentifierInfo();
2004
Douglas Gregor7c26c042011-09-21 14:40:46 +00002005 // Member field could not be with "template" keyword.
2006 // So TemplateParameterLists should be empty in this case.
2007 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002008 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002009 if (TemplateParams->size()) {
2010 // There is no such thing as a member field template.
2011 Diag(D.getIdentifierLoc(), diag::err_template_member)
2012 << II
2013 << SourceRange(TemplateParams->getTemplateLoc(),
2014 TemplateParams->getRAngleLoc());
2015 } else {
2016 // There is an extraneous 'template<>' for this member.
2017 Diag(TemplateParams->getTemplateLoc(),
2018 diag::err_template_member_noparams)
2019 << II
2020 << SourceRange(TemplateParams->getTemplateLoc(),
2021 TemplateParams->getRAngleLoc());
2022 }
2023 return 0;
2024 }
2025
Douglas Gregora007d362010-10-13 22:19:53 +00002026 if (SS.isSet() && !SS.isInvalid()) {
2027 // The user provided a superfluous scope specifier inside a class
2028 // definition:
2029 //
2030 // class X {
2031 // int X::member;
2032 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002033 if (DeclContext *DC = computeDeclContext(SS, false))
2034 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002035 else
2036 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2037 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002038
Douglas Gregora007d362010-10-13 22:19:53 +00002039 SS.clear();
2040 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002041
John McCall5e77d762013-04-16 07:28:30 +00002042 AttributeList *MSPropertyAttr =
2043 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002044 if (MSPropertyAttr) {
2045 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2046 BitWidth, InitStyle, AS, MSPropertyAttr);
2047 if (!Member)
2048 return 0;
2049 isInstField = false;
2050 } else {
2051 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2052 BitWidth, InitStyle, AS);
2053 assert(Member && "HandleField never returns null");
2054 }
2055 } else {
2056 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2057
2058 Member = HandleDeclarator(S, D, TemplateParameterLists);
2059 if (!Member)
2060 return 0;
2061
2062 // Non-instance-fields can't have a bitfield.
2063 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002064 if (Member->isInvalidDecl()) {
2065 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00002066 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002067 // C++ 9.6p3: A bit-field shall not be a static member.
2068 // "static member 'A' cannot be a bit-field"
2069 Diag(Loc, diag::err_static_not_bitfield)
2070 << Name << BitWidth->getSourceRange();
2071 } else if (isa<TypedefDecl>(Member)) {
2072 // "typedef member 'x' cannot be a bit-field"
2073 Diag(Loc, diag::err_typedef_not_bitfield)
2074 << Name << BitWidth->getSourceRange();
2075 } else {
2076 // A function typedef ("typedef int f(); f a;").
2077 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2078 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002079 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002080 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002081 }
Mike Stump11289f42009-09-09 15:08:12 +00002082
Chris Lattnerd26760a2009-03-05 23:01:03 +00002083 BitWidth = 0;
2084 Member->setInvalidDecl();
2085 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002086
2087 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002088
Larisse Voufo39a1e502013-08-06 01:03:05 +00002089 // If we have declared a member function template or static data member
2090 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002091 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2092 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002093 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2094 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00002095 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002096
Richard Smith18f07db2012-08-06 03:25:17 +00002097 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00002098 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00002099 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00002100 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2101 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00002102
Douglas Gregorf2f08062011-03-08 17:10:18 +00002103 if (VS.getLastLocation().isValid()) {
2104 // Update the end location of a method that has a virt-specifiers.
2105 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2106 MD->setRangeEnd(VS.getLastLocation());
2107 }
Richard Smith18f07db2012-08-06 03:25:17 +00002108
Anders Carlssonc87f8612011-01-20 06:29:02 +00002109 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00002110
Douglas Gregor92751d42008-11-17 22:58:34 +00002111 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002112
Daniel Jasper0baec5492012-06-06 08:32:04 +00002113 if (isInstField) {
2114 FieldDecl *FD = cast<FieldDecl>(Member);
2115 FieldCollector->Add(FD);
2116
2117 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2118 FD->getLocation())
2119 != DiagnosticsEngine::Ignored) {
2120 // Remember all explicit private FieldDecls that have a name, no side
2121 // effects and are not part of a dependent type declaration.
2122 if (!FD->isImplicit() && FD->getDeclName() &&
2123 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00002124 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00002125 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00002126 !InitializationHasSideEffects(*FD))
2127 UnusedPrivateFields.insert(FD);
2128 }
2129 }
2130
John McCall48871652010-08-21 09:40:31 +00002131 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002132}
2133
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002134namespace {
2135 class UninitializedFieldVisitor
2136 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2137 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00002138 // List of Decls to generate a warning on. Also remove Decls that become
2139 // initialized.
Richard Trieu406e65c2013-09-20 03:03:06 +00002140 llvm::SmallPtrSet<ValueDecl*, 4> &Decls;
Richard Trieu406e65c2013-09-20 03:03:06 +00002141 // If non-null, add a note to the warning pointing back to the constructor.
2142 const CXXConstructorDecl *Constructor;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002143 public:
2144 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00002145 UninitializedFieldVisitor(Sema &S,
Richard Trieu406e65c2013-09-20 03:03:06 +00002146 llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
Richard Trieu406e65c2013-09-20 03:03:06 +00002147 const CXXConstructorDecl *Constructor)
Richard Trieuef64e942013-10-25 00:56:00 +00002148 : Inherited(S.Context), S(S), Decls(Decls),
2149 Constructor(Constructor) { }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002150
Richard Trieufd687772013-09-16 20:46:50 +00002151 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002152 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2153 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002154
Richard Trieu1bc22c12013-09-13 03:20:53 +00002155 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2156 // or union.
2157 MemberExpr *FieldME = ME;
2158
2159 Expr *Base = ME;
2160 while (isa<MemberExpr>(Base)) {
2161 ME = cast<MemberExpr>(Base);
2162
2163 if (isa<VarDecl>(ME->getMemberDecl()))
2164 return;
2165
2166 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2167 if (!FD->isAnonymousStructOrUnion())
2168 FieldME = ME;
2169
2170 Base = ME->getBase();
2171 }
2172
Richard Trieufd687772013-09-16 20:46:50 +00002173 if (!isa<CXXThisExpr>(Base))
2174 return;
2175
Richard Trieu406e65c2013-09-20 03:03:06 +00002176 ValueDecl* FoundVD = FieldME->getMemberDecl();
2177
Richard Trieuef64e942013-10-25 00:56:00 +00002178 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00002179 return;
2180
Richard Trieuef64e942013-10-25 00:56:00 +00002181 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00002182
Richard Trieuef64e942013-10-25 00:56:00 +00002183 // Prevent double warnings on use of unbounded references.
2184 if (IsReference != CheckReferenceOnly)
2185 return;
2186
2187 unsigned diag = IsReference
2188 ? diag::warn_reference_field_is_uninit
2189 : diag::warn_field_is_uninit;
2190 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2191 if (Constructor)
2192 S.Diag(Constructor->getLocation(),
2193 diag::note_uninit_in_this_constructor)
2194 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2195
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002196 }
2197
2198 void HandleValue(Expr *E) {
2199 E = E->IgnoreParens();
2200
2201 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieufd687772013-09-16 20:46:50 +00002202 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002203 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002204 }
2205
2206 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2207 HandleValue(CO->getTrueExpr());
2208 HandleValue(CO->getFalseExpr());
2209 return;
2210 }
2211
2212 if (BinaryConditionalOperator *BCO =
2213 dyn_cast<BinaryConditionalOperator>(E)) {
2214 HandleValue(BCO->getCommon());
2215 HandleValue(BCO->getFalseExpr());
2216 return;
2217 }
2218
2219 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2220 switch (BO->getOpcode()) {
2221 default:
2222 return;
2223 case(BO_PtrMemD):
2224 case(BO_PtrMemI):
2225 HandleValue(BO->getLHS());
2226 return;
2227 case(BO_Comma):
2228 HandleValue(BO->getRHS());
2229 return;
2230 }
2231 }
2232 }
2233
Richard Trieu1bc22c12013-09-13 03:20:53 +00002234 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00002235 // All uses of unbounded reference fields will warn.
Richard Trieufd687772013-09-16 20:46:50 +00002236 HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002237
2238 Inherited::VisitMemberExpr(ME);
2239 }
2240
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002241 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2242 if (E->getCastKind() == CK_LValueToRValue)
2243 HandleValue(E->getSubExpr());
2244
2245 Inherited::VisitImplicitCastExpr(E);
2246 }
2247
Richard Trieu1bc22c12013-09-13 03:20:53 +00002248 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu406e65c2013-09-20 03:03:06 +00002249 if (E->getConstructor()->isCopyConstructor())
Richard Trieu1bc22c12013-09-13 03:20:53 +00002250 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0)))
2251 if (ICE->getCastKind() == CK_NoOp)
2252 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr()))
Richard Trieufd687772013-09-16 20:46:50 +00002253 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002254
2255 Inherited::VisitCXXConstructExpr(E);
2256 }
2257
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002258 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2259 Expr *Callee = E->getCallee();
2260 if (isa<MemberExpr>(Callee))
2261 HandleValue(Callee);
2262
2263 Inherited::VisitCXXMemberCallExpr(E);
2264 }
Richard Trieu406e65c2013-09-20 03:03:06 +00002265
2266 void VisitBinaryOperator(BinaryOperator *E) {
2267 // If a field assignment is detected, remove the field from the
2268 // uninitiailized field set.
2269 if (E->getOpcode() == BO_Assign)
2270 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2271 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00002272 if (!FD->getType()->isReferenceType())
2273 Decls.erase(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00002274
2275 Inherited::VisitBinaryOperator(E);
2276 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002277 };
Richard Trieu406e65c2013-09-20 03:03:06 +00002278 static void CheckInitExprContainsUninitializedFields(
Richard Trieuef64e942013-10-25 00:56:00 +00002279 Sema &S, Expr *E, llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2280 const CXXConstructorDecl *Constructor) {
2281 if (Decls.size() == 0)
Richard Trieu406e65c2013-09-20 03:03:06 +00002282 return;
2283
Richard Trieuef64e942013-10-25 00:56:00 +00002284 if (!E)
2285 return;
2286
2287 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) {
2288 E = Default->getExpr();
2289 if (!E)
2290 return;
2291 // In class initializers will point to the constructor.
2292 UninitializedFieldVisitor(S, Decls, Constructor).Visit(E);
2293 } else {
2294 UninitializedFieldVisitor(S, Decls, 0).Visit(E);
2295 }
2296 }
2297
2298 // Diagnose value-uses of fields to initialize themselves, e.g.
2299 // foo(foo)
2300 // where foo is not also a parameter to the constructor.
2301 // Also diagnose across field uninitialized use such as
2302 // x(y), y(x)
2303 // TODO: implement -Wuninitialized and fold this into that framework.
2304 static void DiagnoseUninitializedFields(
2305 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2306
2307 if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit,
2308 Constructor->getLocation())
2309 == DiagnosticsEngine::Ignored) {
2310 return;
2311 }
2312
2313 if (Constructor->isInvalidDecl())
2314 return;
2315
2316 const CXXRecordDecl *RD = Constructor->getParent();
2317
2318 // Holds fields that are uninitialized.
2319 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2320
2321 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00002322 for (auto *I : RD->decls()) {
2323 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002324 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00002325 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002326 UninitializedFields.insert(IFD->getAnonField());
2327 }
2328 }
2329
2330 for (CXXConstructorDecl::init_const_iterator FieldInit =
2331 Constructor->init_begin(),
2332 FieldInitEnd = Constructor->init_end();
2333 FieldInit != FieldInitEnd; ++FieldInit) {
2334
2335 Expr *InitExpr = (*FieldInit)->getInit();
2336
2337 CheckInitExprContainsUninitializedFields(
2338 SemaRef, InitExpr, UninitializedFields, Constructor);
2339
2340 if (FieldDecl *Field = (*FieldInit)->getAnyMember())
2341 UninitializedFields.erase(Field);
2342 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002343 }
2344} // namespace
2345
Richard Smith74108172014-01-17 03:11:34 +00002346/// \brief Enter a new C++ default initializer scope. After calling this, the
2347/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2348/// parsing or instantiating the initializer failed.
2349void Sema::ActOnStartCXXInClassMemberInitializer() {
2350 // Create a synthetic function scope to represent the call to the constructor
2351 // that notionally surrounds a use of this initializer.
2352 PushFunctionScope();
2353}
2354
2355/// \brief This is invoked after parsing an in-class initializer for a
2356/// non-static C++ class member, and after instantiating an in-class initializer
2357/// in a class template. Such actions are deferred until the class is complete.
2358void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2359 SourceLocation InitLoc,
2360 Expr *InitExpr) {
2361 // Pop the notional constructor scope we created earlier.
2362 PopFunctionScopeInfo(0, D);
2363
Richard Smith938f40b2011-06-11 17:19:42 +00002364 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smith2b013182012-06-10 03:12:00 +00002365 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2366 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00002367
2368 if (!InitExpr) {
2369 FD->setInvalidDecl();
2370 FD->removeInClassInitializer();
2371 return;
2372 }
2373
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002374 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2375 FD->setInvalidDecl();
2376 FD->removeInClassInitializer();
2377 return;
2378 }
2379
Richard Smith938f40b2011-06-11 17:19:42 +00002380 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00002381 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002382 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00002383 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00002384 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00002385 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002386 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2387 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00002388 if (Init.isInvalid()) {
2389 FD->setInvalidDecl();
2390 return;
2391 }
Richard Smith938f40b2011-06-11 17:19:42 +00002392 }
2393
Richard Smith945f8d32013-01-14 22:39:08 +00002394 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00002395 // The initialization of each base and member constitutes a
2396 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002397 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00002398 if (Init.isInvalid()) {
2399 FD->setInvalidDecl();
2400 return;
2401 }
2402
2403 InitExpr = Init.release();
2404
2405 FD->setInClassInitializer(InitExpr);
2406}
2407
Douglas Gregor15e77a22009-12-31 09:10:24 +00002408/// \brief Find the direct and/or virtual base specifiers that
2409/// correspond to the given base type, for use in base initialization
2410/// within a constructor.
2411static bool FindBaseInitializer(Sema &SemaRef,
2412 CXXRecordDecl *ClassDecl,
2413 QualType BaseType,
2414 const CXXBaseSpecifier *&DirectBaseSpec,
2415 const CXXBaseSpecifier *&VirtualBaseSpec) {
2416 // First, check for a direct base class.
2417 DirectBaseSpec = 0;
2418 for (CXXRecordDecl::base_class_const_iterator Base
2419 = ClassDecl->bases_begin();
2420 Base != ClassDecl->bases_end(); ++Base) {
2421 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2422 // We found a direct base of this type. That's what we're
2423 // initializing.
2424 DirectBaseSpec = &*Base;
2425 break;
2426 }
2427 }
2428
2429 // Check for a virtual base class.
2430 // FIXME: We might be able to short-circuit this if we know in advance that
2431 // there are no virtual bases.
2432 VirtualBaseSpec = 0;
2433 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2434 // We haven't found a base yet; search the class hierarchy for a
2435 // virtual base class.
2436 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2437 /*DetectVirtual=*/false);
2438 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2439 BaseType, Paths)) {
2440 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2441 Path != Paths.end(); ++Path) {
2442 if (Path->back().Base->isVirtual()) {
2443 VirtualBaseSpec = Path->back().Base;
2444 break;
2445 }
2446 }
2447 }
2448 }
2449
2450 return DirectBaseSpec || VirtualBaseSpec;
2451}
2452
Sebastian Redla74948d2011-09-24 17:48:25 +00002453/// \brief Handle a C++ member initializer using braced-init-list syntax.
2454MemInitResult
2455Sema::ActOnMemInitializer(Decl *ConstructorD,
2456 Scope *S,
2457 CXXScopeSpec &SS,
2458 IdentifierInfo *MemberOrBase,
2459 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002460 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002461 SourceLocation IdLoc,
2462 Expr *InitList,
2463 SourceLocation EllipsisLoc) {
2464 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002465 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00002466 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002467}
2468
2469/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00002470MemInitResult
John McCall48871652010-08-21 09:40:31 +00002471Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00002472 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002473 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002474 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00002475 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002476 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002477 SourceLocation IdLoc,
2478 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002479 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002480 SourceLocation RParenLoc,
2481 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00002482 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002483 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002484 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002485 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002486}
2487
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002488namespace {
2489
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00002490// Callback to only accept typo corrections that can be a valid C++ member
2491// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002492class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002493public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002494 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2495 : ClassDecl(ClassDecl) {}
2496
Craig Toppera798a9d2014-03-02 09:32:10 +00002497 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002498 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2499 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2500 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002501 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002502 }
2503 return false;
2504 }
2505
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002506private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002507 CXXRecordDecl *ClassDecl;
2508};
2509
2510}
2511
Sebastian Redla74948d2011-09-24 17:48:25 +00002512/// \brief Handle a C++ member initializer.
2513MemInitResult
2514Sema::BuildMemInitializer(Decl *ConstructorD,
2515 Scope *S,
2516 CXXScopeSpec &SS,
2517 IdentifierInfo *MemberOrBase,
2518 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002519 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002520 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00002521 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002522 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002523 if (!ConstructorD)
2524 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002525
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002526 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00002527
2528 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002529 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00002530 if (!Constructor) {
2531 // The user wrote a constructor initializer on a function that is
2532 // not a C++ constructor. Ignore the error for now, because we may
2533 // have more member initializers coming; we'll diagnose it just
2534 // once in ActOnMemInitializers.
2535 return true;
2536 }
2537
2538 CXXRecordDecl *ClassDecl = Constructor->getParent();
2539
2540 // C++ [class.base.init]p2:
2541 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00002542 // constructor's class and, if not found in that scope, are looked
2543 // up in the scope containing the constructor's definition.
2544 // [Note: if the constructor's class contains a member with the
2545 // same name as a direct or virtual base class of the class, a
2546 // mem-initializer-id naming the member or base class and composed
2547 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00002548 // mem-initializer-id for the hidden base class may be specified
2549 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00002550 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002551 // Look for a member, first.
Mike Stump11289f42009-09-09 15:08:12 +00002552 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002553 = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00002554 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00002555 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00002556 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2557 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00002558 if (EllipsisLoc.isValid())
2559 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00002560 << MemberOrBase
2561 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002562
Sebastian Redla9351792012-02-11 23:51:47 +00002563 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00002564 }
Francois Pichetd583da02010-12-04 09:14:42 +00002565 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002566 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002567 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002568 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00002569 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00002570
2571 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00002572 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00002573 } else if (DS.getTypeSpecType() == TST_decltype) {
2574 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00002575 } else {
2576 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2577 LookupParsedName(R, S, &SS);
2578
2579 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2580 if (!TyD) {
2581 if (R.isAmbiguous()) return true;
2582
John McCallda6841b2010-04-09 19:01:14 +00002583 // We don't want access-control diagnostics here.
2584 R.suppressDiagnostics();
2585
Douglas Gregora3b624a2010-01-19 06:46:48 +00002586 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2587 bool NotUnknownSpecialization = false;
2588 DeclContext *DC = computeDeclContext(SS, false);
2589 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2590 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2591
2592 if (!NotUnknownSpecialization) {
2593 // When the scope specifier can refer to a member of an unknown
2594 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00002595 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2596 SS.getWithLocInContext(Context),
2597 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00002598 if (BaseType.isNull())
2599 return true;
2600
Douglas Gregora3b624a2010-01-19 06:46:48 +00002601 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002602 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002603 }
2604 }
2605
Douglas Gregor15e77a22009-12-31 09:10:24 +00002606 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002607 TypoCorrection Corr;
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002608 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002609 if (R.empty() && BaseType.isNull() &&
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002610 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00002611 Validator, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002612 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002613 // We have found a non-static data member with a similar
2614 // name to what was typed; complain and initialize that
2615 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00002616 diagnoseTypo(Corr,
2617 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2618 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00002619 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002620 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002621 const CXXBaseSpecifier *DirectBaseSpec;
2622 const CXXBaseSpecifier *VirtualBaseSpec;
2623 if (FindBaseInitializer(*this, ClassDecl,
2624 Context.getTypeDeclType(Type),
2625 DirectBaseSpec, VirtualBaseSpec)) {
2626 // We have found a direct or virtual base class with a
2627 // similar name to what was typed; complain and initialize
2628 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00002629 diagnoseTypo(Corr,
2630 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2631 << MemberOrBase << false,
2632 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00002633
Richard Smithf9b15102013-08-17 00:46:16 +00002634 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2635 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002636 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00002637 diag::note_base_class_specified_here)
2638 << BaseSpec->getType()
2639 << BaseSpec->getSourceRange();
2640
Douglas Gregor15e77a22009-12-31 09:10:24 +00002641 TyD = Type;
2642 }
2643 }
2644 }
2645
Douglas Gregora3b624a2010-01-19 06:46:48 +00002646 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002647 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00002648 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00002649 return true;
2650 }
John McCallb5a0d312009-12-21 10:41:20 +00002651 }
2652
Douglas Gregora3b624a2010-01-19 06:46:48 +00002653 if (BaseType.isNull()) {
2654 BaseType = Context.getTypeDeclType(TyD);
Aaron Ballman4a979672014-01-03 13:56:08 +00002655 if (SS.isSet())
Douglas Gregora3b624a2010-01-19 06:46:48 +00002656 // FIXME: preserve source range information
Aaron Ballman4a979672014-01-03 13:56:08 +00002657 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2658 BaseType);
John McCallb5a0d312009-12-21 10:41:20 +00002659 }
2660 }
Mike Stump11289f42009-09-09 15:08:12 +00002661
John McCallbcd03502009-12-07 02:54:59 +00002662 if (!TInfo)
2663 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002664
Sebastian Redla9351792012-02-11 23:51:47 +00002665 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00002666}
2667
Chandler Carruth599deef2011-09-03 01:14:15 +00002668/// Checks a member initializer expression for cases where reference (or
2669/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00002670static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2671 Expr *Init,
2672 SourceLocation IdLoc) {
2673 QualType MemberTy = Member->getType();
2674
2675 // We only handle pointers and references currently.
2676 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2677 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2678 return;
2679
2680 const bool IsPointer = MemberTy->isPointerType();
2681 if (IsPointer) {
2682 if (const UnaryOperator *Op
2683 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2684 // The only case we're worried about with pointers requires taking the
2685 // address.
2686 if (Op->getOpcode() != UO_AddrOf)
2687 return;
2688
2689 Init = Op->getSubExpr();
2690 } else {
2691 // We only handle address-of expression initializers for pointers.
2692 return;
2693 }
2694 }
2695
Richard Smithe3b28bc2013-06-12 21:51:50 +00002696 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002697 // We only warn when referring to a non-reference parameter declaration.
2698 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2699 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00002700 return;
2701
2702 S.Diag(Init->getExprLoc(),
2703 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2704 : diag::warn_bind_ref_member_to_parameter)
2705 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002706 } else {
2707 // Other initializers are fine.
2708 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00002709 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002710
2711 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2712 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00002713}
2714
John McCallfaf5fb42010-08-26 23:41:50 +00002715MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002716Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002717 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002718 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2719 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2720 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00002721 "Member must be a FieldDecl or IndirectFieldDecl");
2722
Sebastian Redla9351792012-02-11 23:51:47 +00002723 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002724 return true;
2725
Douglas Gregor266bb5f2010-11-05 22:21:31 +00002726 if (Member->isInvalidDecl())
2727 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00002728
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002729 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00002730 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002731 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00002732 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002733 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00002734 } else {
2735 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002736 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002737 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00002738
Sebastian Redla9351792012-02-11 23:51:47 +00002739 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002740
Sebastian Redla9351792012-02-11 23:51:47 +00002741 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002742 // Can't check initialization for a member of dependent type or when
2743 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00002744 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00002745 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00002746 bool InitList = false;
2747 if (isa<InitListExpr>(Init)) {
2748 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002749 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002750 }
2751
Chandler Carruthd44c3102010-12-06 09:23:57 +00002752 // Initialize the member.
2753 InitializedEntity MemberEntity =
2754 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2755 : InitializedEntity::InitializeMember(IndirectMember, 0);
2756 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002757 InitList ? InitializationKind::CreateDirectList(IdLoc)
2758 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2759 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00002760
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002761 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2762 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002763 if (MemberInit.isInvalid())
2764 return true;
2765
Richard Smith736a9472013-06-12 20:42:33 +00002766 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2767
Richard Smith945f8d32013-01-14 22:39:08 +00002768 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00002769 // The initialization of each base and member constitutes a
2770 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002771 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002772 if (MemberInit.isInvalid())
2773 return true;
2774
Richard Smithd59b8322012-12-19 01:39:02 +00002775 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002776 }
2777
Chandler Carruthd44c3102010-12-06 09:23:57 +00002778 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00002779 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2780 InitRange.getBegin(), Init,
2781 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002782 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00002783 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2784 InitRange.getBegin(), Init,
2785 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002786 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00002787}
2788
John McCallfaf5fb42010-08-26 23:41:50 +00002789MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002790Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002791 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002792 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002793 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002794 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002795 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002796 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00002797
Sebastian Redl0501c632012-02-12 16:37:36 +00002798 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002799 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002800 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2801 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002802 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00002803 }
2804
Sebastian Redla9351792012-02-11 23:51:47 +00002805 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00002806 // Initialize the object.
2807 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2808 QualType(ClassDecl->getTypeForDecl(), 0));
2809 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002810 InitList ? InitializationKind::CreateDirectList(NameLoc)
2811 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2812 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002813 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00002814 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002815 Args, 0);
Alexis Huntc5575cc2011-02-26 19:13:13 +00002816 if (DelegationInit.isInvalid())
2817 return true;
2818
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00002819 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2820 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00002821
Richard Smith945f8d32013-01-14 22:39:08 +00002822 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00002823 // The initialization of each base and member constitutes a
2824 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002825 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2826 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002827 if (DelegationInit.isInvalid())
2828 return true;
2829
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00002830 // If we are in a dependent context, template instantiation will
2831 // perform this type-checking again. Just save the arguments that we
2832 // received in a ParenListExpr.
2833 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2834 // of the information that we have about the base
2835 // initializer. However, deconstructing the ASTs is a dicey process,
2836 // and this approach is far more likely to get the corner cases right.
2837 if (CurContext->isDependentContext())
2838 DelegationInit = Owned(Init);
2839
Sebastian Redla9351792012-02-11 23:51:47 +00002840 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00002841 DelegationInit.takeAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002842 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002843}
2844
2845MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00002846Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00002847 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002848 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002849 SourceLocation BaseLoc
2850 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00002851
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002852 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2853 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2854 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2855
2856 // C++ [class.base.init]p2:
2857 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00002858 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002859 // of that class, the mem-initializer is ill-formed. A
2860 // mem-initializer-list can initialize a base class using any
2861 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00002862 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002863
Sebastian Redla9351792012-02-11 23:51:47 +00002864 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00002865 if (EllipsisLoc.isValid()) {
2866 // This is a pack expansion.
2867 if (!BaseType->containsUnexpandedParameterPack()) {
2868 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00002869 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002870
Douglas Gregor44e7df62011-01-04 00:32:56 +00002871 EllipsisLoc = SourceLocation();
2872 }
2873 } else {
2874 // Check for any unexpanded parameter packs.
2875 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2876 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00002877
Sebastian Redla9351792012-02-11 23:51:47 +00002878 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00002879 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00002880 }
Sebastian Redla74948d2011-09-24 17:48:25 +00002881
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002882 // Check for direct and virtual base classes.
2883 const CXXBaseSpecifier *DirectBaseSpec = 0;
2884 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2885 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002886 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2887 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00002888 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002889
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002890 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2891 VirtualBaseSpec);
2892
2893 // C++ [base.class.init]p2:
2894 // Unless the mem-initializer-id names a nonstatic data member of the
2895 // constructor's class or a direct or virtual base of that class, the
2896 // mem-initializer is ill-formed.
2897 if (!DirectBaseSpec && !VirtualBaseSpec) {
2898 // If the class has any dependent bases, then it's possible that
2899 // one of those types will resolve to the same type as
2900 // BaseType. Therefore, just treat this as a dependent base
2901 // class initialization. FIXME: Should we try to check the
2902 // initialization anyway? It seems odd.
2903 if (ClassDecl->hasAnyDependentBases())
2904 Dependent = true;
2905 else
2906 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2907 << BaseType << Context.getTypeDeclType(ClassDecl)
2908 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2909 }
2910 }
2911
2912 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00002913 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002914
Sebastian Redla74948d2011-09-24 17:48:25 +00002915 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2916 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00002917 InitRange.getBegin(), Init,
2918 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002919 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002920
2921 // C++ [base.class.init]p2:
2922 // If a mem-initializer-id is ambiguous because it designates both
2923 // a direct non-virtual base class and an inherited virtual base
2924 // class, the mem-initializer is ill-formed.
2925 if (DirectBaseSpec && VirtualBaseSpec)
2926 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002927 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002928
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002929 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002930 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002931 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002932
2933 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00002934 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002935 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002936 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00002937 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002938 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00002939 }
Sebastian Redl0501c632012-02-12 16:37:36 +00002940
2941 InitializedEntity BaseEntity =
2942 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2943 InitializationKind Kind =
2944 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2945 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2946 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002947 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2948 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002949 if (BaseInit.isInvalid())
2950 return true;
John McCallacf0ee52010-10-08 02:01:28 +00002951
Richard Smith945f8d32013-01-14 22:39:08 +00002952 // C++11 [class.base.init]p7:
2953 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002954 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002955 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002956 if (BaseInit.isInvalid())
2957 return true;
2958
2959 // If we are in a dependent context, template instantiation will
2960 // perform this type-checking again. Just save the arguments that we
2961 // received in a ParenListExpr.
2962 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2963 // of the information that we have about the base
2964 // initializer. However, deconstructing the ASTs is a dicey process,
2965 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00002966 if (CurContext->isDependentContext())
Sebastian Redla9351792012-02-11 23:51:47 +00002967 BaseInit = Owned(Init);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002968
Alexis Hunt1d792652011-01-08 20:30:50 +00002969 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002970 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00002971 InitRange.getBegin(),
Sebastian Redla74948d2011-09-24 17:48:25 +00002972 BaseInit.takeAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002973 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002974}
2975
Sebastian Redl22653ba2011-08-30 19:58:05 +00002976// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00002977static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2978 if (T.isNull()) T = E->getType();
2979 QualType TargetType = SemaRef.BuildReferenceType(
2980 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002981 SourceLocation ExprLoc = E->getLocStart();
2982 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2983 TargetType, ExprLoc);
2984
2985 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2986 SourceRange(ExprLoc, ExprLoc),
2987 E->getSourceRange()).take();
2988}
2989
Anders Carlsson1b00e242010-04-23 03:10:23 +00002990/// ImplicitInitializerKind - How an implicit base or member initializer should
2991/// initialize its base or member.
2992enum ImplicitInitializerKind {
2993 IIK_Default,
2994 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00002995 IIK_Move,
2996 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00002997};
2998
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002999static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00003000BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003001 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00003002 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003003 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00003004 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003005 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00003006 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3007 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003008
John McCalldadc5752010-08-24 06:29:42 +00003009 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003010
3011 switch (ImplicitInitKind) {
Richard Smithc2bc61b2013-03-18 21:12:30 +00003012 case IIK_Inherit: {
3013 const CXXRecordDecl *Inherited =
3014 Constructor->getInheritedConstructor()->getParent();
3015 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3016 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3017 // C++11 [class.inhctor]p8:
3018 // Each expression in the expression-list is of the form
3019 // static_cast<T&&>(p), where p is the name of the corresponding
3020 // constructor parameter and T is the declared type of p.
3021 SmallVector<Expr*, 16> Args;
3022 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3023 ParmVarDecl *PD = Constructor->getParamDecl(I);
3024 ExprResult ArgExpr =
3025 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3026 VK_LValue, SourceLocation());
3027 if (ArgExpr.isInvalid())
3028 return true;
3029 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
3030 }
3031
3032 InitializationKind InitKind = InitializationKind::CreateDirect(
3033 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003034 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smithc2bc61b2013-03-18 21:12:30 +00003035 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3036 break;
3037 }
3038 }
3039 // Fall through.
Anders Carlsson1b00e242010-04-23 03:10:23 +00003040 case IIK_Default: {
3041 InitializationKind InitKind
3042 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003043 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3044 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003045 break;
3046 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003047
Sebastian Redl22653ba2011-08-30 19:58:05 +00003048 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00003049 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003050 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003051 ParmVarDecl *Param = Constructor->getParamDecl(0);
3052 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00003053
Anders Carlsson1b00e242010-04-23 03:10:23 +00003054 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003055 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003056 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003057 Constructor->getLocation(), ParamType,
3058 VK_LValue, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003059
Eli Friedmanfa0df832012-02-02 03:46:19 +00003060 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3061
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003062 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00003063 QualType ArgTy =
3064 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3065 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00003066
Sebastian Redl22653ba2011-08-30 19:58:05 +00003067 if (Moving) {
3068 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3069 }
3070
John McCallcf142162010-08-07 06:22:56 +00003071 CXXCastPath BasePath;
3072 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00003073 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3074 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003075 Moving ? VK_XValue : VK_LValue,
Sebastian Redl22653ba2011-08-30 19:58:05 +00003076 &BasePath).take();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003077
Anders Carlsson1b00e242010-04-23 03:10:23 +00003078 InitializationKind InitKind
3079 = InitializationKind::CreateDirect(Constructor->getLocation(),
3080 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003081 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3082 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003083 break;
3084 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00003085 }
John McCallb268a282010-08-23 23:25:46 +00003086
Douglas Gregora40433a2010-12-07 00:41:46 +00003087 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003088 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003089 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003090
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003091 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00003092 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003093 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3094 SourceLocation()),
3095 BaseSpec->isVirtual(),
3096 SourceLocation(),
3097 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003098 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003099 SourceLocation());
3100
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003101 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003102}
3103
Sebastian Redl22653ba2011-08-30 19:58:05 +00003104static bool RefersToRValueRef(Expr *MemRef) {
3105 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3106 return Referenced->getType()->isRValueReferenceType();
3107}
3108
Anders Carlsson3c1db572010-04-23 02:15:47 +00003109static bool
3110BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003111 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00003112 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00003113 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003114 if (Field->isInvalidDecl())
3115 return true;
3116
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003117 SourceLocation Loc = Constructor->getLocation();
3118
Sebastian Redl22653ba2011-08-30 19:58:05 +00003119 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3120 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00003121 ParmVarDecl *Param = Constructor->getParamDecl(0);
3122 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00003123
3124 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00003125 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3126 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003127
Anders Carlsson423f5d82010-04-23 16:04:08 +00003128 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003129 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003130 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003131 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003132
Eli Friedmanfa0df832012-02-02 03:46:19 +00003133 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3134
Sebastian Redl22653ba2011-08-30 19:58:05 +00003135 if (Moving) {
3136 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3137 }
3138
Douglas Gregor94f9a482010-05-05 05:51:00 +00003139 // Build a reference to this field within the parameter.
3140 CXXScopeSpec SS;
3141 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3142 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003143 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3144 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003145 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00003146 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00003147 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003148 ParamType, Loc,
3149 /*IsArrow=*/false,
3150 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003151 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00003152 /*FirstQualifierInScope=*/0,
3153 MemberLookup,
3154 /*TemplateArgs=*/0);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003155 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00003156 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003157
3158 // C++11 [class.copy]p15:
3159 // - if a member m has rvalue reference type T&&, it is direct-initialized
3160 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003161 if (RefersToRValueRef(CtorArg.get())) {
3162 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003163 }
3164
Douglas Gregor94f9a482010-05-05 05:51:00 +00003165 // When the field we are copying is an array, create index variables for
3166 // each dimension of the array. We use these index variables to subscript
3167 // the source array, and other clients (e.g., CodeGen) will perform the
3168 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003169 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003170 QualType BaseType = Field->getType();
3171 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003172 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003173 while (const ConstantArrayType *Array
3174 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003175 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003176 // Create the iteration variable for this array index.
3177 IdentifierInfo *IterationVarName = 0;
3178 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003179 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003180 llvm::raw_svector_ostream OS(Str);
3181 OS << "__i" << IndexVariables.size();
3182 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3183 }
3184 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00003185 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003186 IterationVarName, SizeType,
3187 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003188 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003189 IndexVariables.push_back(IterationVar);
3190
3191 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00003192 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00003193 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003194 assert(!IterationVarRef.isInvalid() &&
3195 "Reference to invented variable cannot fail!");
Eli Friedman844f9452012-01-23 02:35:22 +00003196 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3197 assert(!IterationVarRef.isInvalid() &&
3198 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00003199
Douglas Gregor94f9a482010-05-05 05:51:00 +00003200 // Subscript the array with this iteration variable.
Sebastian Redle9c4e842011-09-04 18:14:28 +00003201 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCallb268a282010-08-23 23:25:46 +00003202 IterationVarRef.take(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00003203 Loc);
3204 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00003205 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003206
Douglas Gregor94f9a482010-05-05 05:51:00 +00003207 BaseType = Array->getElementType();
3208 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00003209
3210 // The array subscript expression is an lvalue, which is wrong for moving.
3211 if (Moving && InitializingArray)
Sebastian Redle9c4e842011-09-04 18:14:28 +00003212 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003213
Douglas Gregor94f9a482010-05-05 05:51:00 +00003214 // Construct the entity that we will be initializing. For an array, this
3215 // will be first element in the array, which may require several levels
3216 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003217 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003218 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00003219 if (Indirect)
3220 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3221 else
3222 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00003223 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3224 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3225 0,
3226 Entities.back()));
3227
3228 // Direct-initialize to use the copy constructor.
3229 InitializationKind InitKind =
3230 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3231
Sebastian Redle9c4e842011-09-04 18:14:28 +00003232 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003233 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003234
John McCalldadc5752010-08-24 06:29:42 +00003235 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00003236 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003237 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00003238 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003239 if (MemberInit.isInvalid())
3240 return true;
3241
Douglas Gregor493627b2011-08-10 15:22:55 +00003242 if (Indirect) {
3243 assert(IndexVariables.size() == 0 &&
3244 "Indirect field improperly initialized");
3245 CXXMemberInit
3246 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3247 Loc, Loc,
3248 MemberInit.takeAs<Expr>(),
3249 Loc);
3250 } else
3251 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3252 Loc, MemberInit.takeAs<Expr>(),
3253 Loc,
3254 IndexVariables.data(),
3255 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00003256 return false;
3257 }
3258
Richard Smithc2bc61b2013-03-18 21:12:30 +00003259 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3260 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00003261
Anders Carlsson3c1db572010-04-23 02:15:47 +00003262 QualType FieldBaseElementType =
3263 SemaRef.Context.getBaseElementType(Field->getType());
3264
Anders Carlsson3c1db572010-04-23 02:15:47 +00003265 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003266 InitializedEntity InitEntity
3267 = Indirect? InitializedEntity::InitializeMember(Indirect)
3268 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00003269 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003270 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003271
3272 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3273 ExprResult MemberInit =
3274 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00003275
Douglas Gregora40433a2010-12-07 00:41:46 +00003276 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003277 if (MemberInit.isInvalid())
3278 return true;
3279
Douglas Gregor493627b2011-08-10 15:22:55 +00003280 if (Indirect)
3281 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3282 Indirect, Loc,
3283 Loc,
3284 MemberInit.get(),
3285 Loc);
3286 else
3287 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3288 Field, Loc, Loc,
3289 MemberInit.get(),
3290 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003291 return false;
3292 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003293
Alexis Hunt8b455182011-05-17 00:19:05 +00003294 if (!Field->getParent()->isUnion()) {
3295 if (FieldBaseElementType->isReferenceType()) {
3296 SemaRef.Diag(Constructor->getLocation(),
3297 diag::err_uninitialized_member_in_ctor)
3298 << (int)Constructor->isImplicit()
3299 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3300 << 0 << Field->getDeclName();
3301 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3302 return true;
3303 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003304
Alexis Hunt8b455182011-05-17 00:19:05 +00003305 if (FieldBaseElementType.isConstQualified()) {
3306 SemaRef.Diag(Constructor->getLocation(),
3307 diag::err_uninitialized_member_in_ctor)
3308 << (int)Constructor->isImplicit()
3309 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3310 << 1 << Field->getDeclName();
3311 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3312 return true;
3313 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003314 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00003315
David Blaikiebbafb8a2012-03-11 07:00:24 +00003316 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003317 FieldBaseElementType->isObjCRetainableType() &&
3318 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3319 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00003320 // ARC:
John McCall31168b02011-06-15 23:02:42 +00003321 // Default-initialize Objective-C pointers to NULL.
3322 CXXMemberInit
3323 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3324 Loc, Loc,
3325 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3326 Loc);
3327 return false;
3328 }
3329
Anders Carlsson3c1db572010-04-23 02:15:47 +00003330 // Nothing to initialize.
3331 CXXMemberInit = 0;
3332 return false;
3333}
John McCallbc83b3f2010-05-20 23:23:51 +00003334
3335namespace {
3336struct BaseAndFieldInfo {
3337 Sema &S;
3338 CXXConstructorDecl *Ctor;
3339 bool AnyErrorsInInits;
3340 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00003341 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003342 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00003343 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00003344
3345 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3346 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003347 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3348 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00003349 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003350 else if (Generated && Ctor->isMoveConstructor())
3351 IIK = IIK_Move;
Richard Smithc2bc61b2013-03-18 21:12:30 +00003352 else if (Ctor->getInheritedConstructor())
3353 IIK = IIK_Inherit;
John McCallbc83b3f2010-05-20 23:23:51 +00003354 else
3355 IIK = IIK_Default;
3356 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00003357
3358 bool isImplicitCopyOrMove() const {
3359 switch (IIK) {
3360 case IIK_Copy:
3361 case IIK_Move:
3362 return true;
3363
3364 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00003365 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00003366 return false;
3367 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003368
3369 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00003370 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00003371
3372 bool addFieldInitializer(CXXCtorInitializer *Init) {
3373 AllToInit.push_back(Init);
3374
3375 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00003376 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003377 S.UnusedPrivateFields.remove(Init->getAnyMember());
3378
3379 return false;
3380 }
John McCallbc83b3f2010-05-20 23:23:51 +00003381
Richard Smithab44d5b2013-12-10 08:25:00 +00003382 bool isInactiveUnionMember(FieldDecl *Field) {
3383 RecordDecl *Record = Field->getParent();
3384 if (!Record->isUnion())
3385 return false;
3386
Richard Smith8d183852013-12-10 20:56:03 +00003387 if (FieldDecl *Active =
3388 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00003389 return Active != Field->getCanonicalDecl();
3390
3391 // In an implicit copy or move constructor, ignore any in-class initializer.
3392 if (isImplicitCopyOrMove())
3393 return true;
3394
3395 // If there's no explicit initialization, the field is active only if it
3396 // has an in-class initializer...
3397 if (Field->hasInClassInitializer())
3398 return false;
3399 // ... or it's an anonymous struct or union whose class has an in-class
3400 // initializer.
3401 if (!Field->isAnonymousStructOrUnion())
3402 return true;
3403 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3404 return !FieldRD->hasInClassInitializer();
3405 }
3406
3407 /// \brief Determine whether the given field is, or is within, a union member
3408 /// that is inactive (because there was an initializer given for a different
3409 /// member of the union, or because the union was not initialized at all).
3410 bool isWithinInactiveUnionMember(FieldDecl *Field,
3411 IndirectFieldDecl *Indirect) {
3412 if (!Indirect)
3413 return isInactiveUnionMember(Field);
3414
Aaron Ballman29c94602014-03-07 18:36:15 +00003415 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003416 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003417 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00003418 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00003419 }
3420 return false;
3421 }
3422};
Richard Smithc94ec842011-09-19 13:34:43 +00003423}
3424
Douglas Gregor10f939c2011-11-02 23:04:16 +00003425/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3426/// array type.
3427static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3428 if (T->isIncompleteArrayType())
3429 return true;
3430
3431 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3432 if (!ArrayT->getSize())
3433 return true;
3434
3435 T = ArrayT->getElementType();
3436 }
3437
3438 return false;
3439}
3440
Richard Smith938f40b2011-06-11 17:19:42 +00003441static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00003442 FieldDecl *Field,
3443 IndirectFieldDecl *Indirect = 0) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003444 if (Field->isInvalidDecl())
3445 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00003446
Chandler Carruth139e9622010-06-30 02:59:29 +00003447 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0a8cfc72012-08-07 21:30:42 +00003448 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3449 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003450
Richard Smithab44d5b2013-12-10 08:25:00 +00003451 // C++11 [class.base.init]p8:
3452 // if the entity is a non-static data member that has a
3453 // brace-or-equal-initializer and either
3454 // -- the constructor's class is a union and no other variant member of that
3455 // union is designated by a mem-initializer-id or
3456 // -- the constructor's class is not a union, and, if the entity is a member
3457 // of an anonymous union, no other member of that union is designated by
3458 // a mem-initializer-id,
3459 // the entity is initialized as specified in [dcl.init].
3460 //
3461 // We also apply the same rules to handle anonymous structs within anonymous
3462 // unions.
3463 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3464 return false;
3465
Douglas Gregor7db3e952011-11-28 20:03:15 +00003466 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smith852c9db2013-04-20 22:23:05 +00003467 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3468 Info.Ctor->getLocation(), Field);
Douglas Gregor493627b2011-08-10 15:22:55 +00003469 CXXCtorInitializer *Init;
3470 if (Indirect)
3471 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3472 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003473 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003474 SourceLocation());
3475 else
3476 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3477 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003478 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003479 SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00003480 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003481 }
3482
Douglas Gregor10f939c2011-11-02 23:04:16 +00003483 // Don't initialize incomplete or zero-length arrays.
3484 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3485 return false;
3486
John McCallbc83b3f2010-05-20 23:23:51 +00003487 // Don't try to build an implicit initializer if there were semantic
3488 // errors in any of the initializers (and therefore we might be
3489 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003490 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00003491 return false;
3492
Alexis Hunt1d792652011-01-08 20:30:50 +00003493 CXXCtorInitializer *Init = 0;
Douglas Gregor493627b2011-08-10 15:22:55 +00003494 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3495 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00003496 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00003497
Richard Smith0a8cfc72012-08-07 21:30:42 +00003498 if (!Init)
3499 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00003500
Richard Smith0a8cfc72012-08-07 21:30:42 +00003501 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003502}
Alexis Hunt61bc1732011-05-01 07:04:31 +00003503
3504bool
3505Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3506 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00003507 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00003508 Constructor->setNumCtorInitializers(1);
3509 CXXCtorInitializer **initializer =
3510 new (Context) CXXCtorInitializer*[1];
3511 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3512 Constructor->setCtorInitializers(initializer);
3513
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003514 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003515 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003516 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3517 }
3518
Alexis Hunte2622992011-05-05 00:05:47 +00003519 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00003520
Alexis Hunt61bc1732011-05-01 07:04:31 +00003521 return false;
3522}
Douglas Gregor493627b2011-08-10 15:22:55 +00003523
David Blaikie3fc2f912013-01-17 05:26:25 +00003524bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3525 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00003526 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003527 // Just store the initializers as written, they will be checked during
3528 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00003529 if (!Initializers.empty()) {
3530 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00003531 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00003532 new (Context) CXXCtorInitializer*[Initializers.size()];
3533 memcpy(baseOrMemberInitializers, Initializers.data(),
3534 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00003535 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003536 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00003537
3538 // Let template instantiation know whether we had errors.
3539 if (AnyErrors)
3540 Constructor->setInvalidDecl();
3541
Anders Carlssondb0a9652010-04-02 06:26:44 +00003542 return false;
3543 }
3544
John McCallbc83b3f2010-05-20 23:23:51 +00003545 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003546
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003547 // We need to build the initializer AST according to order of construction
3548 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003549 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00003550 if (!ClassDecl)
3551 return true;
3552
Eli Friedman9cf6b592009-11-09 19:20:36 +00003553 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00003554
David Blaikie3fc2f912013-01-17 05:26:25 +00003555 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003556 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00003557
Anders Carlssondb0a9652010-04-02 06:26:44 +00003558 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00003559 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003560 else {
Francois Pichetd583da02010-12-04 09:14:42 +00003561 Info.AllBaseFields[Member->getAnyMember()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003562
3563 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00003564 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003565 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003566 if (FD && FD->getParent()->isUnion())
3567 Info.ActiveUnionMember.insert(std::make_pair(
3568 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3569 }
3570 } else if (FieldDecl *FD = Member->getMember()) {
3571 if (FD->getParent()->isUnion())
3572 Info.ActiveUnionMember.insert(std::make_pair(
3573 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3574 }
3575 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00003576 }
3577
Anders Carlsson43c64af2010-04-21 19:52:01 +00003578 // Keep track of the direct virtual bases.
3579 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3580 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3581 E = ClassDecl->bases_end(); I != E; ++I) {
3582 if (I->isVirtual())
3583 DirectVBases.insert(I);
3584 }
3585
Anders Carlssondb0a9652010-04-02 06:26:44 +00003586 // Push virtual bases before others.
3587 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3588 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3589
Alexis Hunt1d792652011-01-08 20:30:50 +00003590 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00003591 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00003592 // [class.base.init]p7, per DR257:
3593 // A mem-initializer where the mem-initializer-id names a virtual base
3594 // class is ignored during execution of a constructor of any class that
3595 // is not the most derived class.
3596 if (ClassDecl->isAbstract()) {
3597 // FIXME: Provide a fixit to remove the base specifier. This requires
3598 // tracking the location of the associated comma for a base specifier.
3599 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3600 << VBase->getType() << ClassDecl;
3601 DiagnoseAbstractType(ClassDecl);
3602 }
3603
John McCallbc83b3f2010-05-20 23:23:51 +00003604 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00003605 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3606 // [class.base.init]p8, per DR257:
3607 // If a given [...] base class is not named by a mem-initializer-id
3608 // [...] and the entity is not a virtual base class of an abstract
3609 // class, then [...] the entity is default-initialized.
Anders Carlsson43c64af2010-04-21 19:52:01 +00003610 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00003611 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003612 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Richard Smithbc46e432013-07-22 02:56:56 +00003613 VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003614 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003615 HadError = true;
3616 continue;
3617 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003618
John McCallbc83b3f2010-05-20 23:23:51 +00003619 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003620 }
3621 }
Mike Stump11289f42009-09-09 15:08:12 +00003622
John McCallbc83b3f2010-05-20 23:23:51 +00003623 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00003624 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3625 E = ClassDecl->bases_end(); Base != E; ++Base) {
3626 // Virtuals are in the virtual base list and already constructed.
3627 if (Base->isVirtual())
3628 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003629
Alexis Hunt1d792652011-01-08 20:30:50 +00003630 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00003631 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3632 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003633 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003634 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003635 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003636 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003637 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003638 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003639 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003640 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00003641
John McCallbc83b3f2010-05-20 23:23:51 +00003642 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003643 }
3644 }
Mike Stump11289f42009-09-09 15:08:12 +00003645
John McCallbc83b3f2010-05-20 23:23:51 +00003646 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00003647 for (auto *Mem : ClassDecl->decls()) {
3648 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003649 // C++ [class.bit]p2:
3650 // A declaration for a bit-field that omits the identifier declares an
3651 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3652 // initialized.
3653 if (F->isUnnamedBitfield())
3654 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003655
Sebastian Redl22653ba2011-08-30 19:58:05 +00003656 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00003657 // handle anonymous struct/union fields based on their individual
3658 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003659 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003660 continue;
3661
3662 if (CollectFieldInitializer(*this, Info, F))
3663 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003664 continue;
3665 }
Douglas Gregor493627b2011-08-10 15:22:55 +00003666
3667 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003668 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003669 continue;
3670
Aaron Ballman629afae2014-03-07 19:56:05 +00003671 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003672 if (F->getType()->isIncompleteArrayType()) {
3673 assert(ClassDecl->hasFlexibleArrayMember() &&
3674 "Incomplete array type is not valid");
3675 continue;
3676 }
3677
Douglas Gregor493627b2011-08-10 15:22:55 +00003678 // Initialize each field of an anonymous struct individually.
3679 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3680 HadError = true;
3681
3682 continue;
3683 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003684 }
Mike Stump11289f42009-09-09 15:08:12 +00003685
David Blaikie3fc2f912013-01-17 05:26:25 +00003686 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003687 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003688 Constructor->setNumCtorInitializers(NumInitializers);
3689 CXXCtorInitializer **baseOrMemberInitializers =
3690 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00003691 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00003692 NumInitializers * sizeof(CXXCtorInitializer*));
3693 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00003694
John McCalla6309952010-03-16 21:39:52 +00003695 // Constructors implicitly reference the base and member
3696 // destructors.
3697 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3698 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003699 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00003700
3701 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003702}
3703
David Blaikieb61b8152013-01-17 08:49:22 +00003704static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003705 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00003706 const RecordDecl *RD = RT->getDecl();
3707 if (RD->isAnonymousStructOrUnion()) {
3708 for (RecordDecl::field_iterator Field = RD->field_begin(),
3709 E = RD->field_end(); Field != E; ++Field)
3710 PopulateKeysForFields(*Field, IdealInits);
3711 return;
3712 }
Eli Friedman952c15d2009-07-21 19:28:10 +00003713 }
David Blaikieb61b8152013-01-17 08:49:22 +00003714 IdealInits.push_back(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00003715}
3716
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003717static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3718 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00003719}
3720
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003721static const void *GetKeyForMember(ASTContext &Context,
3722 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00003723 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003724 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00003725
David Blaikieb61b8152013-01-17 08:49:22 +00003726 return Member->getAnyMember();
Eli Friedman952c15d2009-07-21 19:28:10 +00003727}
3728
David Blaikie3fc2f912013-01-17 05:26:25 +00003729static void DiagnoseBaseOrMemInitializerOrder(
3730 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3731 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00003732 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00003733 return;
Mike Stump11289f42009-09-09 15:08:12 +00003734
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003735 // Don't check initializers order unless the warning is enabled at the
3736 // location of at least one initializer.
3737 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003738 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003739 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003740 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3741 Init->getSourceLocation())
David Blaikie9c902b52011-09-25 23:23:43 +00003742 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003743 ShouldCheckOrder = true;
3744 break;
3745 }
3746 }
3747 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00003748 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003749
John McCallbb7b6582010-04-10 07:37:23 +00003750 // Build the list of bases and members in the order that they'll
3751 // actually be initialized. The explicit initializers should be in
3752 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003753 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00003754
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003755 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3756
John McCallbb7b6582010-04-10 07:37:23 +00003757 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003758 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00003759 ClassDecl->vbases_begin(),
3760 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00003761 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00003762
John McCallbb7b6582010-04-10 07:37:23 +00003763 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003764 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00003765 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00003766 if (Base->isVirtual())
3767 continue;
John McCallbb7b6582010-04-10 07:37:23 +00003768 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00003769 }
Mike Stump11289f42009-09-09 15:08:12 +00003770
John McCallbb7b6582010-04-10 07:37:23 +00003771 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00003772 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregor556e5862011-10-10 17:22:13 +00003773 E = ClassDecl->field_end(); Field != E; ++Field) {
3774 if (Field->isUnnamedBitfield())
3775 continue;
3776
David Blaikieb61b8152013-01-17 08:49:22 +00003777 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00003778 }
3779
John McCallbb7b6582010-04-10 07:37:23 +00003780 unsigned NumIdealInits = IdealInitKeys.size();
3781 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00003782
Alexis Hunt1d792652011-01-08 20:30:50 +00003783 CXXCtorInitializer *PrevInit = 0;
David Blaikie3fc2f912013-01-17 05:26:25 +00003784 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003785 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003786 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00003787
3788 // Scan forward to try to find this initializer in the idealized
3789 // initializers list.
3790 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3791 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003792 break;
John McCallbb7b6582010-04-10 07:37:23 +00003793
3794 // If we didn't find this initializer, it must be because we
3795 // scanned past it on a previous iteration. That can only
3796 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00003797 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00003798 Sema::SemaDiagnosticBuilder D =
3799 SemaRef.Diag(PrevInit->getSourceLocation(),
3800 diag::warn_initializer_out_of_order);
3801
Francois Pichetd583da02010-12-04 09:14:42 +00003802 if (PrevInit->isAnyMemberInitializer())
3803 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003804 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003805 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003806
Francois Pichetd583da02010-12-04 09:14:42 +00003807 if (Init->isAnyMemberInitializer())
3808 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003809 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003810 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003811
3812 // Move back to the initializer's location in the ideal list.
3813 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3814 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003815 break;
John McCallbb7b6582010-04-10 07:37:23 +00003816
3817 assert(IdealIndex != NumIdealInits &&
3818 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003819 }
John McCallbb7b6582010-04-10 07:37:23 +00003820
3821 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003822 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00003823}
3824
John McCall23eebd92010-04-10 09:28:51 +00003825namespace {
3826bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003827 CXXCtorInitializer *Init,
3828 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00003829 if (!PrevInit) {
3830 PrevInit = Init;
3831 return false;
3832 }
3833
Douglas Gregorea306a12013-03-25 23:28:23 +00003834 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00003835 S.Diag(Init->getSourceLocation(),
3836 diag::err_multiple_mem_initialization)
3837 << Field->getDeclName()
3838 << Init->getSourceRange();
3839 else {
John McCall424cec92011-01-19 06:33:43 +00003840 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00003841 assert(BaseClass && "neither field nor base");
3842 S.Diag(Init->getSourceLocation(),
3843 diag::err_multiple_base_initialization)
3844 << QualType(BaseClass, 0)
3845 << Init->getSourceRange();
3846 }
3847 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3848 << 0 << PrevInit->getSourceRange();
3849
3850 return true;
3851}
3852
Alexis Hunt1d792652011-01-08 20:30:50 +00003853typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00003854typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3855
3856bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003857 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00003858 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00003859 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003860 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00003861 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00003862
3863 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00003864 if (Parent->isUnion()) {
3865 UnionEntry &En = Unions[Parent];
3866 if (En.first && En.first != Child) {
3867 S.Diag(Init->getSourceLocation(),
3868 diag::err_multiple_mem_union_initialization)
3869 << Field->getDeclName()
3870 << Init->getSourceRange();
3871 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3872 << 0 << En.second->getSourceRange();
3873 return true;
David Blaikie256ee192011-11-12 20:54:14 +00003874 }
3875 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00003876 En.first = Child;
3877 En.second = Init;
3878 }
David Blaikie0f65d592011-11-17 06:01:57 +00003879 if (!Parent->isAnonymousStructOrUnion())
3880 return false;
John McCall23eebd92010-04-10 09:28:51 +00003881 }
3882
3883 Child = Parent;
3884 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00003885 }
John McCall23eebd92010-04-10 09:28:51 +00003886
3887 return false;
3888}
3889}
3890
Anders Carlssone857b292010-04-02 03:37:03 +00003891/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00003892void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00003893 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00003894 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00003895 bool AnyErrors) {
3896 if (!ConstructorDecl)
3897 return;
3898
3899 AdjustDeclIfTemplate(ConstructorDecl);
3900
3901 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003902 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00003903
3904 if (!Constructor) {
3905 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3906 return;
3907 }
3908
John McCall23eebd92010-04-10 09:28:51 +00003909 // Mapping for the duplicate initializers check.
3910 // For member initializers, this is keyed with a FieldDecl*.
3911 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003912 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00003913
3914 // Mapping for the inconsistent anonymous-union initializers check.
3915 RedundantUnionMap MemberUnions;
3916
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003917 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003918 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003919 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00003920
Abramo Bagnara341d7832010-05-26 18:09:23 +00003921 // Set the source order index.
3922 Init->setSourceOrder(i);
3923
Francois Pichetd583da02010-12-04 09:14:42 +00003924 if (Init->isAnyMemberInitializer()) {
3925 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003926 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3927 CheckRedundantUnionInit(*this, Init, MemberUnions))
3928 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003929 } else if (Init->isBaseInitializer()) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003930 const void *Key =
3931 GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
John McCall23eebd92010-04-10 09:28:51 +00003932 if (CheckRedundantInit(*this, Init, Members[Key]))
3933 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003934 } else {
3935 assert(Init->isDelegatingInitializer());
3936 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00003937 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00003938 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00003939 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00003940 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00003941 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00003942 }
Alexis Hunt6118d662011-05-04 05:57:24 +00003943 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00003944 // Return immediately as the initializer is set.
3945 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003946 }
Anders Carlssone857b292010-04-02 03:37:03 +00003947 }
3948
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003949 if (HadError)
3950 return;
3951
David Blaikie3fc2f912013-01-17 05:26:25 +00003952 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00003953
David Blaikie3fc2f912013-01-17 05:26:25 +00003954 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00003955
Richard Trieuef64e942013-10-25 00:56:00 +00003956 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00003957}
3958
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003959void
John McCalla6309952010-03-16 21:39:52 +00003960Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3961 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00003962 // Ignore dependent contexts. Also ignore unions, since their members never
3963 // have destructors implicitly called.
3964 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00003965 return;
John McCall1064d7e2010-03-16 05:22:47 +00003966
3967 // FIXME: all the access-control diagnostics are positioned on the
3968 // field/base declaration. That's probably good; that said, the
3969 // user might reasonably want to know why the destructor is being
3970 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00003971
Anders Carlssondee9a302009-11-17 04:44:12 +00003972 // Non-static data members.
3973 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3974 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00003975 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00003976 if (Field->isInvalidDecl())
3977 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003978
3979 // Don't destroy incomplete or zero-length arrays.
3980 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3981 continue;
3982
Anders Carlssondee9a302009-11-17 04:44:12 +00003983 QualType FieldType = Context.getBaseElementType(Field->getType());
3984
3985 const RecordType* RT = FieldType->getAs<RecordType>();
3986 if (!RT)
3987 continue;
3988
3989 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003990 if (FieldClassDecl->isInvalidDecl())
3991 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00003992 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00003993 continue;
Richard Smith921bd202012-02-26 09:11:52 +00003994 // The destructor for an implicit anonymous union member is never invoked.
3995 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3996 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00003997
Douglas Gregore71edda2010-07-01 22:47:18 +00003998 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003999 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004000 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004001 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00004002 << Field->getDeclName()
4003 << FieldType);
4004
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004005 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004006 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004007 }
4008
John McCall1064d7e2010-03-16 05:22:47 +00004009 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4010
Anders Carlssondee9a302009-11-17 04:44:12 +00004011 // Bases.
4012 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4013 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00004014 // Bases are always records in a well-formed non-dependent class.
4015 const RecordType *RT = Base->getType()->getAs<RecordType>();
4016
4017 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00004018 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00004019 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00004020
John McCall1064d7e2010-03-16 05:22:47 +00004021 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004022 // If our base class is invalid, we probably can't get its dtor anyway.
4023 if (BaseClassDecl->isInvalidDecl())
4024 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004025 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004026 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004027
Douglas Gregore71edda2010-07-01 22:47:18 +00004028 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004029 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004030
4031 // FIXME: caret should be on the start of the class name
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004032 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004033 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00004034 << Base->getType()
John McCall5dadb652012-04-07 03:04:20 +00004035 << Base->getSourceRange(),
4036 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00004037
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004038 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004039 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004040 }
4041
4042 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004043 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
4044 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00004045
4046 // Bases are always records in a well-formed non-dependent class.
John McCalldd1eca32012-04-09 21:51:56 +00004047 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004048
4049 // Ignore direct virtual bases.
4050 if (DirectVirtualBases.count(RT))
4051 continue;
4052
John McCall1064d7e2010-03-16 05:22:47 +00004053 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004054 // If our base class is invalid, we probably can't get its dtor anyway.
4055 if (BaseClassDecl->isInvalidDecl())
4056 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004057 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004058 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004059
Douglas Gregore71edda2010-07-01 22:47:18 +00004060 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004061 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00004062 if (CheckDestructorAccess(
4063 ClassDecl->getLocation(), Dtor,
4064 PDiag(diag::err_access_dtor_vbase)
4065 << Context.getTypeDeclType(ClassDecl) << VBase->getType(),
4066 Context.getTypeDeclType(ClassDecl)) ==
4067 AR_accessible) {
4068 CheckDerivedToBaseConversion(
4069 Context.getTypeDeclType(ClassDecl), VBase->getType(),
4070 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4071 SourceRange(), DeclarationName(), 0);
4072 }
John McCall1064d7e2010-03-16 05:22:47 +00004073
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004074 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004075 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004076 }
4077}
4078
John McCall48871652010-08-21 09:40:31 +00004079void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00004080 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004081 return;
Mike Stump11289f42009-09-09 15:08:12 +00004082
Mike Stump11289f42009-09-09 15:08:12 +00004083 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00004084 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00004085 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00004086 DiagnoseUninitializedFields(*this, Constructor);
4087 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004088}
4089
Mike Stump11289f42009-09-09 15:08:12 +00004090bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00004091 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregorae298422012-05-04 17:09:59 +00004092 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4093 unsigned DiagID;
4094 AbstractDiagSelID SelID;
4095
4096 public:
4097 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4098 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004099
Craig Toppera798a9d2014-03-02 09:32:10 +00004100 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004101 if (Suppressed) return;
Douglas Gregorae298422012-05-04 17:09:59 +00004102 if (SelID == -1)
4103 S.Diag(Loc, DiagID) << T;
4104 else
4105 S.Diag(Loc, DiagID) << SelID << T;
4106 }
4107 } Diagnoser(DiagID, SelID);
4108
4109 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004110}
4111
Anders Carlssoneabf7702009-08-27 00:13:57 +00004112bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregorae298422012-05-04 17:09:59 +00004113 TypeDiagnoser &Diagnoser) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004114 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004115 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004116
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004117 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregorae298422012-05-04 17:09:59 +00004118 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004119
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004120 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004121 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004122 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004123 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00004124
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004125 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregorae298422012-05-04 17:09:59 +00004126 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004127 }
Mike Stump11289f42009-09-09 15:08:12 +00004128
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004129 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004130 if (!RT)
4131 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004132
John McCall67da35c2010-02-04 22:26:26 +00004133 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004134
John McCall02db245d2010-08-18 09:41:07 +00004135 // We can't answer whether something is abstract until it has a
4136 // definition. If it's currently being defined, we'll walk back
4137 // over all the declarations when we have a full definition.
4138 const CXXRecordDecl *Def = RD->getDefinition();
4139 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00004140 return false;
4141
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004142 if (!RD->isAbstract())
4143 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004144
Douglas Gregorae298422012-05-04 17:09:59 +00004145 Diagnoser.diagnose(*this, Loc, T);
John McCall02db245d2010-08-18 09:41:07 +00004146 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00004147
John McCall02db245d2010-08-18 09:41:07 +00004148 return true;
4149}
4150
4151void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4152 // Check if we've already emitted the list of pure virtual functions
4153 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004154 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00004155 return;
Mike Stump11289f42009-09-09 15:08:12 +00004156
Richard Smithbc46e432013-07-22 02:56:56 +00004157 // If the diagnostic is suppressed, don't emit the notes. We're only
4158 // going to emit them once, so try to attach them to a diagnostic we're
4159 // actually going to show.
4160 if (Diags.isLastDiagnosticIgnored())
4161 return;
4162
Douglas Gregor4165bd62010-03-23 23:47:56 +00004163 CXXFinalOverriderMap FinalOverriders;
4164 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00004165
Anders Carlssona2f74f32010-06-03 01:00:02 +00004166 // Keep a set of seen pure methods so we won't diagnose the same method
4167 // more than once.
4168 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4169
Douglas Gregor4165bd62010-03-23 23:47:56 +00004170 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4171 MEnd = FinalOverriders.end();
4172 M != MEnd;
4173 ++M) {
4174 for (OverridingMethods::iterator SO = M->second.begin(),
4175 SOEnd = M->second.end();
4176 SO != SOEnd; ++SO) {
4177 // C++ [class.abstract]p4:
4178 // A class is abstract if it contains or inherits at least one
4179 // pure virtual function for which the final overrider is pure
4180 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00004181
Douglas Gregor4165bd62010-03-23 23:47:56 +00004182 //
4183 if (SO->second.size() != 1)
4184 continue;
4185
4186 if (!SO->second.front().Method->isPure())
4187 continue;
4188
Anders Carlssona2f74f32010-06-03 01:00:02 +00004189 if (!SeenPureMethods.insert(SO->second.front().Method))
4190 continue;
4191
Douglas Gregor4165bd62010-03-23 23:47:56 +00004192 Diag(SO->second.front().Method->getLocation(),
4193 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00004194 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00004195 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004196 }
4197
4198 if (!PureVirtualClassDiagSet)
4199 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4200 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004201}
4202
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004203namespace {
John McCall02db245d2010-08-18 09:41:07 +00004204struct AbstractUsageInfo {
4205 Sema &S;
4206 CXXRecordDecl *Record;
4207 CanQualType AbstractType;
4208 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00004209
John McCall02db245d2010-08-18 09:41:07 +00004210 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4211 : S(S), Record(Record),
4212 AbstractType(S.Context.getCanonicalType(
4213 S.Context.getTypeDeclType(Record))),
4214 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004215
John McCall02db245d2010-08-18 09:41:07 +00004216 void DiagnoseAbstractType() {
4217 if (Invalid) return;
4218 S.DiagnoseAbstractType(Record);
4219 Invalid = true;
4220 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00004221
John McCall02db245d2010-08-18 09:41:07 +00004222 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4223};
4224
4225struct CheckAbstractUsage {
4226 AbstractUsageInfo &Info;
4227 const NamedDecl *Ctx;
4228
4229 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4230 : Info(Info), Ctx(Ctx) {}
4231
4232 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4233 switch (TL.getTypeLocClass()) {
4234#define ABSTRACT_TYPELOC(CLASS, PARENT)
4235#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00004236 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00004237#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004238 }
John McCall02db245d2010-08-18 09:41:07 +00004239 }
Mike Stump11289f42009-09-09 15:08:12 +00004240
John McCall02db245d2010-08-18 09:41:07 +00004241 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00004242 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004243 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4244 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00004245 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004246
4247 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00004248 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004249 }
John McCall02db245d2010-08-18 09:41:07 +00004250 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004251
John McCall02db245d2010-08-18 09:41:07 +00004252 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4253 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4254 }
Mike Stump11289f42009-09-09 15:08:12 +00004255
John McCall02db245d2010-08-18 09:41:07 +00004256 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4257 // Visit the type parameters from a permissive context.
4258 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4259 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4260 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4261 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4262 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4263 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004264 }
John McCall02db245d2010-08-18 09:41:07 +00004265 }
Mike Stump11289f42009-09-09 15:08:12 +00004266
John McCall02db245d2010-08-18 09:41:07 +00004267 // Visit pointee types from a permissive context.
4268#define CheckPolymorphic(Type) \
4269 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4270 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4271 }
4272 CheckPolymorphic(PointerTypeLoc)
4273 CheckPolymorphic(ReferenceTypeLoc)
4274 CheckPolymorphic(MemberPointerTypeLoc)
4275 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00004276 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00004277
John McCall02db245d2010-08-18 09:41:07 +00004278 /// Handle all the types we haven't given a more specific
4279 /// implementation for above.
4280 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4281 // Every other kind of type that we haven't called out already
4282 // that has an inner type is either (1) sugar or (2) contains that
4283 // inner type in some way as a subobject.
4284 if (TypeLoc Next = TL.getNextTypeLoc())
4285 return Visit(Next, Sel);
4286
4287 // If there's no inner type and we're in a permissive context,
4288 // don't diagnose.
4289 if (Sel == Sema::AbstractNone) return;
4290
4291 // Check whether the type matches the abstract type.
4292 QualType T = TL.getType();
4293 if (T->isArrayType()) {
4294 Sel = Sema::AbstractArrayType;
4295 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004296 }
John McCall02db245d2010-08-18 09:41:07 +00004297 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4298 if (CT != Info.AbstractType) return;
4299
4300 // It matched; do some magic.
4301 if (Sel == Sema::AbstractArrayType) {
4302 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4303 << T << TL.getSourceRange();
4304 } else {
4305 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4306 << Sel << T << TL.getSourceRange();
4307 }
4308 Info.DiagnoseAbstractType();
4309 }
4310};
4311
4312void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4313 Sema::AbstractDiagSelID Sel) {
4314 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4315}
4316
4317}
4318
4319/// Check for invalid uses of an abstract type in a method declaration.
4320static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4321 CXXMethodDecl *MD) {
4322 // No need to do the check on definitions, which require that
4323 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004324 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00004325 return;
4326
4327 // For safety's sake, just ignore it if we don't have type source
4328 // information. This should never happen for non-implicit methods,
4329 // but...
4330 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4331 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4332}
4333
4334/// Check for invalid uses of an abstract type within a class definition.
4335static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4336 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00004337 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00004338 if (D->isImplicit()) continue;
4339
4340 // Methods and method templates.
4341 if (isa<CXXMethodDecl>(D)) {
4342 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4343 } else if (isa<FunctionTemplateDecl>(D)) {
4344 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4345 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4346
4347 // Fields and static variables.
4348 } else if (isa<FieldDecl>(D)) {
4349 FieldDecl *FD = cast<FieldDecl>(D);
4350 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4351 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4352 } else if (isa<VarDecl>(D)) {
4353 VarDecl *VD = cast<VarDecl>(D);
4354 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4355 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4356
4357 // Nested classes and class templates.
4358 } else if (isa<CXXRecordDecl>(D)) {
4359 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4360 } else if (isa<ClassTemplateDecl>(D)) {
4361 CheckAbstractClassUsage(Info,
4362 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4363 }
4364 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004365}
4366
Douglas Gregorc99f1552009-12-03 18:33:45 +00004367/// \brief Perform semantic checks on a class definition that has been
4368/// completing, introducing implicitly-declared members, checking for
4369/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004370void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00004371 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00004372 return;
4373
John McCall02db245d2010-08-18 09:41:07 +00004374 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4375 AbstractUsageInfo Info(*this, Record);
4376 CheckAbstractClassUsage(Info, Record);
4377 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00004378
4379 // If this is not an aggregate type and has no user-declared constructor,
4380 // complain about any non-static data members of reference or const scalar
4381 // type, since they will never get initializers.
4382 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00004383 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4384 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004385 bool Complained = false;
4386 for (RecordDecl::field_iterator F = Record->field_begin(),
4387 FEnd = Record->field_end();
4388 F != FEnd; ++F) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004389 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004390 continue;
4391
Douglas Gregor454a5b62010-04-15 00:00:53 +00004392 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00004393 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004394 if (!Complained) {
4395 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4396 << Record->getTagKind() << Record;
4397 Complained = true;
4398 }
4399
4400 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4401 << F->getType()->isReferenceType()
4402 << F->getDeclName();
4403 }
4404 }
4405 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004406
Anders Carlssone771e762011-01-25 18:08:22 +00004407 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00004408 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00004409
4410 if (Record->getIdentifier()) {
4411 // C++ [class.mem]p13:
4412 // If T is the name of a class, then each of the following shall have a
4413 // name different from T:
4414 // - every member of every anonymous union that is a member of class T.
4415 //
4416 // C++ [class.mem]p14:
4417 // In addition, if class T has a user-declared constructor (12.1), every
4418 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00004419 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4420 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4421 ++I) {
4422 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004423 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4424 isa<IndirectFieldDecl>(D)) {
4425 Diag(D->getLocation(), diag::err_member_name_of_class)
4426 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00004427 break;
4428 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00004429 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00004430 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004431
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004432 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00004433 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004434 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004435 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004436 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4437 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4438 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004439
David Majnemera5433082013-10-18 00:33:31 +00004440 if (Record->isAbstract()) {
4441 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4442 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4443 << FA->isSpelledAsSealed();
4444 DiagnoseAbstractType(Record);
4445 }
David Blaikie348df502012-09-21 03:21:07 +00004446 }
4447
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004448 if (!Record->isDependentType()) {
4449 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4450 MEnd = Record->method_end();
4451 M != MEnd; ++M) {
Richard Smithbd305122012-12-11 01:14:52 +00004452 // See if a method overloads virtual methods in a base
4453 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004454 if (!M->isStatic())
Eli Friedmanaf65120b2013-09-05 23:51:03 +00004455 DiagnoseHiddenVirtualMethods(*M);
Richard Smithbd305122012-12-11 01:14:52 +00004456
4457 // Check whether the explicitly-defaulted special members are valid.
4458 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4459 CheckExplicitlyDefaultedSpecialMember(*M);
4460
4461 // For an explicitly defaulted or deleted special member, we defer
4462 // determining triviality until the class is complete. That time is now!
4463 if (!M->isImplicit() && !M->isUserProvided()) {
4464 CXXSpecialMember CSM = getSpecialMember(*M);
4465 if (CSM != CXXInvalid) {
4466 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4467
4468 // Inform the class that we've finished declaring this member.
4469 Record->finishedDefaultedOrDeletedMember(*M);
4470 }
4471 }
4472 }
4473 }
4474
4475 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4476 // function that is not a constructor declares that member function to be
4477 // const. [...] The class of which that function is a member shall be
4478 // a literal type.
4479 //
4480 // If the class has virtual bases, any constexpr members will already have
4481 // been diagnosed by the checks performed on the member declaration, so
4482 // suppress this (less useful) diagnostic.
4483 //
4484 // We delay this until we know whether an explicitly-defaulted (or deleted)
4485 // destructor for the class is trivial.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004486 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smithbd305122012-12-11 01:14:52 +00004487 !Record->isLiteral() && !Record->getNumVBases()) {
4488 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4489 MEnd = Record->method_end();
4490 M != MEnd; ++M) {
4491 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4492 switch (Record->getTemplateSpecializationKind()) {
4493 case TSK_ImplicitInstantiation:
4494 case TSK_ExplicitInstantiationDeclaration:
4495 case TSK_ExplicitInstantiationDefinition:
4496 // If a template instantiates to a non-literal type, but its members
4497 // instantiate to constexpr functions, the template is technically
4498 // ill-formed, but we allow it for sanity.
4499 continue;
4500
4501 case TSK_Undeclared:
4502 case TSK_ExplicitSpecialization:
4503 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4504 diag::err_constexpr_method_non_literal);
4505 break;
4506 }
4507
4508 // Only produce one error per class.
4509 break;
4510 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004511 }
4512 }
Sebastian Redl08905022011-02-05 19:23:19 +00004513
John McCall95833f32014-02-27 20:30:49 +00004514 // ms_struct is a request to use the same ABI rules as MSVC. Check
4515 // whether this class uses any C++ features that are implemented
4516 // completely differently in MSVC, and if so, emit a diagnostic.
4517 // That diagnostic defaults to an error, but we allow projects to
4518 // map it down to a warning (or ignore it). It's a fairly common
4519 // practice among users of the ms_struct pragma to mass-annotate
4520 // headers, sweeping up a bunch of types that the project doesn't
4521 // really rely on MSVC-compatible layout for. We must therefore
4522 // support "ms_struct except for C++ stuff" as a secondary ABI.
4523 if (Record->isMsStruct(Context) &&
4524 (Record->isPolymorphic() || Record->getNumBases())) {
4525 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00004526 }
4527
Richard Smithc2bc61b2013-03-18 21:12:30 +00004528 // Declare inheriting constructors. We do this eagerly here because:
4529 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redl08905022011-02-05 19:23:19 +00004530 // constructors from different classes.
4531 // - The lazy declaration of the other implicit constructors is so as to not
4532 // waste space and performance on classes that are not meant to be
4533 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smithc2bc61b2013-03-18 21:12:30 +00004534 // have inheriting constructors.
4535 DeclareInheritingConstructors(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004536}
4537
Richard Smith41c35d62013-11-27 03:39:20 +00004538/// Look up the special member function that would be called by a special
4539/// member function for a subobject of class type.
4540///
4541/// \param Class The class type of the subobject.
4542/// \param CSM The kind of special member function.
4543/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4544/// \param ConstRHS True if this is a copy operation with a const object
4545/// on its RHS, that is, if the argument to the outer special member
4546/// function is 'const' and this is not a field marked 'mutable'.
4547static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4548 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4549 unsigned FieldQuals, bool ConstRHS) {
4550 unsigned LHSQuals = 0;
4551 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4552 LHSQuals = FieldQuals;
4553
4554 unsigned RHSQuals = FieldQuals;
4555 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4556 RHSQuals = 0;
4557 else if (ConstRHS)
4558 RHSQuals |= Qualifiers::Const;
4559
4560 return S.LookupSpecialMember(Class, CSM,
4561 RHSQuals & Qualifiers::Const,
4562 RHSQuals & Qualifiers::Volatile,
4563 false,
4564 LHSQuals & Qualifiers::Const,
4565 LHSQuals & Qualifiers::Volatile);
4566}
4567
Richard Smithb5800092012-06-10 05:43:50 +00004568/// Is the special member function which would be selected to perform the
4569/// specified operation on the specified class type a constexpr constructor?
4570static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4571 Sema::CXXSpecialMember CSM,
Richard Smith41c35d62013-11-27 03:39:20 +00004572 unsigned Quals, bool ConstRHS) {
Richard Smithb5800092012-06-10 05:43:50 +00004573 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00004574 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00004575 if (!SMOR || !SMOR->getMethod())
4576 // A constructor we wouldn't select can't be "involved in initializing"
4577 // anything.
4578 return true;
4579 return SMOR->getMethod()->isConstexpr();
4580}
4581
4582/// Determine whether the specified special member function would be constexpr
4583/// if it were implicitly defined.
4584static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4585 Sema::CXXSpecialMember CSM,
4586 bool ConstArg) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004587 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00004588 return false;
4589
4590 // C++11 [dcl.constexpr]p4:
4591 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00004592 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00004593 switch (CSM) {
4594 case Sema::CXXDefaultConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004595 // Since default constructor lookup is essentially trivial (and cannot
4596 // involve, for instance, template instantiation), we compute whether a
4597 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4598 //
4599 // This is important for performance; we need to know whether the default
4600 // constructor is constexpr to determine whether the type is a literal type.
4601 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4602
Richard Smithb5800092012-06-10 05:43:50 +00004603 case Sema::CXXCopyConstructor:
4604 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004605 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00004606 break;
4607
4608 case Sema::CXXCopyAssignment:
4609 case Sema::CXXMoveAssignment:
Richard Smith99005e62013-05-07 03:19:20 +00004610 if (!S.getLangOpts().CPlusPlus1y)
4611 return false;
4612 // In C++1y, we need to perform overload resolution.
4613 Ctor = false;
4614 break;
4615
Richard Smithb5800092012-06-10 05:43:50 +00004616 case Sema::CXXDestructor:
4617 case Sema::CXXInvalid:
4618 return false;
4619 }
4620
4621 // -- if the class is a non-empty union, or for each non-empty anonymous
4622 // union member of a non-union class, exactly one non-static data member
4623 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00004624 //
4625 // If we squint, this is guaranteed, since exactly one non-static data member
4626 // will be initialized (if the constructor isn't deleted), we just don't know
4627 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00004628 if (Ctor && ClassDecl->isUnion())
Richard Smith4086a132012-06-10 07:07:24 +00004629 return true;
Richard Smithb5800092012-06-10 05:43:50 +00004630
4631 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00004632 if (Ctor && ClassDecl->getNumVBases())
4633 return false;
4634
4635 // C++1y [class.copy]p26:
4636 // -- [the class] is a literal type, and
4637 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00004638 return false;
4639
4640 // -- every constructor involved in initializing [...] base class
4641 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00004642 // -- the assignment operator selected to copy/move each direct base
4643 // class is a constexpr function, and
Richard Smithb5800092012-06-10 05:43:50 +00004644 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4645 BEnd = ClassDecl->bases_end();
4646 B != BEnd; ++B) {
4647 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4648 if (!BaseType) continue;
4649
4650 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004651 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smithb5800092012-06-10 05:43:50 +00004652 return false;
4653 }
4654
4655 // -- every constructor involved in initializing non-static data members
4656 // [...] shall be a constexpr constructor;
4657 // -- every non-static data member and base class sub-object shall be
4658 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00004659 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00004660 // thereof), the assignment operator selected to copy/move that member is
4661 // a constexpr function
Richard Smithb5800092012-06-10 05:43:50 +00004662 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4663 FEnd = ClassDecl->field_end();
4664 F != FEnd; ++F) {
4665 if (F->isInvalidDecl())
4666 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00004667 QualType BaseType = S.Context.getBaseElementType(F->getType());
4668 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00004669 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004670 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
4671 BaseType.getCVRQualifiers(),
4672 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00004673 return false;
Richard Smithb5800092012-06-10 05:43:50 +00004674 }
4675 }
4676
4677 // All OK, it's constexpr!
4678 return true;
4679}
4680
Richard Smithd3b5c9082012-07-27 04:22:15 +00004681static Sema::ImplicitExceptionSpecification
4682computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4683 switch (S.getSpecialMember(MD)) {
4684 case Sema::CXXDefaultConstructor:
4685 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4686 case Sema::CXXCopyConstructor:
4687 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4688 case Sema::CXXCopyAssignment:
4689 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4690 case Sema::CXXMoveConstructor:
4691 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4692 case Sema::CXXMoveAssignment:
4693 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4694 case Sema::CXXDestructor:
4695 return S.ComputeDefaultedDtorExceptionSpec(MD);
4696 case Sema::CXXInvalid:
4697 break;
4698 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00004699 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4700 "only special members have implicit exception specs");
4701 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00004702}
4703
Richard Smith7f782272012-07-30 23:48:14 +00004704static void
4705updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4706 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4707 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4708 ExceptSpec.getEPI(EPI);
Alp Toker314cc812014-01-25 16:55:45 +00004709 FD->setType(S.Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004710 FPT->getParamTypes(), EPI));
Richard Smith7f782272012-07-30 23:48:14 +00004711}
4712
Reid Kleckner78af0702013-08-27 23:08:25 +00004713static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4714 CXXMethodDecl *MD) {
4715 FunctionProtoType::ExtProtoInfo EPI;
4716
4717 // Build an exception specification pointing back at this member.
4718 EPI.ExceptionSpecType = EST_Unevaluated;
4719 EPI.ExceptionSpecDecl = MD;
4720
4721 // Set the calling convention to the default for C++ instance methods.
4722 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4723 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4724 /*IsCXXMethod=*/true));
4725 return EPI;
4726}
4727
Richard Smithd3b5c9082012-07-27 04:22:15 +00004728void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4729 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4730 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4731 return;
4732
Richard Smith7f782272012-07-30 23:48:14 +00004733 // Evaluate the exception specification.
4734 ImplicitExceptionSpecification ExceptSpec =
4735 computeImplicitExceptionSpec(*this, Loc, MD);
4736
4737 // Update the type of the special member to use it.
4738 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4739
4740 // A user-provided destructor can be defined outside the class. When that
4741 // happens, be sure to update the exception specification on both
4742 // declarations.
4743 const FunctionProtoType *CanonicalFPT =
4744 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4745 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4746 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4747 CanonicalFPT, ExceptSpec);
Richard Smithd3b5c9082012-07-27 04:22:15 +00004748}
4749
Richard Smithb9e90b12012-05-15 04:39:51 +00004750void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4751 CXXRecordDecl *RD = MD->getParent();
4752 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004753
Richard Smithb9e90b12012-05-15 04:39:51 +00004754 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4755 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00004756
4757 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00004758 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00004759 bool First = MD == MD->getCanonicalDecl();
4760
4761 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004762
4763 // C++11 [dcl.fct.def.default]p1:
4764 // A function that is explicitly defaulted shall
4765 // -- be a special member function (checked elsewhere),
4766 // -- have the same type (except for ref-qualifiers, and except that a
4767 // copy operation can take a non-const reference) as an implicit
4768 // declaration, and
4769 // -- not have default arguments.
4770 unsigned ExpectedParams = 1;
4771 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4772 ExpectedParams = 0;
4773 if (MD->getNumParams() != ExpectedParams) {
4774 // This also checks for default arguments: a copy or move constructor with a
4775 // default argument is classified as a default constructor, and assignment
4776 // operations and destructors can't have default arguments.
4777 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4778 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00004779 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00004780 } else if (MD->isVariadic()) {
4781 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4782 << CSM << MD->getSourceRange();
4783 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00004784 }
4785
Richard Smithb9e90b12012-05-15 04:39:51 +00004786 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00004787
Richard Smithb5800092012-06-10 05:43:50 +00004788 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00004789 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00004790 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00004791 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00004792 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00004793
Richard Smithb9e90b12012-05-15 04:39:51 +00004794 QualType ReturnType = Context.VoidTy;
4795 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4796 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00004797 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00004798 QualType ExpectedReturnType =
4799 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4800 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4801 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4802 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4803 HadError = true;
4804 }
4805
4806 // A defaulted special member cannot have cv-qualifiers.
4807 if (Type->getTypeQuals()) {
4808 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smith99005e62013-05-07 03:19:20 +00004809 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smithb9e90b12012-05-15 04:39:51 +00004810 HadError = true;
4811 }
4812 }
4813
4814 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00004815 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00004816 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004817 if (ExpectedParams && ArgType->isReferenceType()) {
4818 // Argument must be reference to possibly-const T.
4819 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00004820 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00004821
4822 if (ReferentType.isVolatileQualified()) {
4823 Diag(MD->getLocation(),
4824 diag::err_defaulted_special_member_volatile_param) << CSM;
4825 HadError = true;
4826 }
4827
Richard Smithb5800092012-06-10 05:43:50 +00004828 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00004829 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4830 Diag(MD->getLocation(),
4831 diag::err_defaulted_special_member_copy_const_param)
4832 << (CSM == CXXCopyAssignment);
4833 // FIXME: Explain why this special member can't be const.
4834 } else {
4835 Diag(MD->getLocation(),
4836 diag::err_defaulted_special_member_move_const_param)
4837 << (CSM == CXXMoveAssignment);
4838 }
4839 HadError = true;
4840 }
Richard Smithb9e90b12012-05-15 04:39:51 +00004841 } else if (ExpectedParams) {
4842 // A copy assignment operator can take its argument by value, but a
4843 // defaulted one cannot.
4844 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00004845 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00004846 HadError = true;
4847 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00004848
Richard Smithcc36f692011-12-22 02:22:31 +00004849 // C++11 [dcl.fct.def.default]p2:
4850 // An explicitly-defaulted function may be declared constexpr only if it
4851 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00004852 // Do not apply this rule to members of class templates, since core issue 1358
4853 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00004854 // functions which cannot be constexpr (for non-constructors in C++11 and for
4855 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00004856 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4857 HasConstParam);
Richard Smith99005e62013-05-07 03:19:20 +00004858 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4859 : isa<CXXConstructorDecl>(MD)) &&
4860 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00004861 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4862 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00004863 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00004864 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00004865 }
Richard Smithbd305122012-12-11 01:14:52 +00004866
Richard Smithcc36f692011-12-22 02:22:31 +00004867 // and may have an explicit exception-specification only if it is compatible
4868 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00004869 if (Type->hasExceptionSpec()) {
4870 // Delay the check if this is the first declaration of the special member,
4871 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00004872 if (First) {
4873 // If the exception specification needs to be instantiated, do so now,
4874 // before we clobber it with an EST_Unevaluated specification below.
4875 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4876 InstantiateExceptionSpec(MD->getLocStart(), MD);
4877 Type = MD->getType()->getAs<FunctionProtoType>();
4878 }
Richard Smithbd305122012-12-11 01:14:52 +00004879 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00004880 } else
Richard Smithbd305122012-12-11 01:14:52 +00004881 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4882 }
Richard Smithcc36f692011-12-22 02:22:31 +00004883
4884 // If a function is explicitly defaulted on its first declaration,
4885 if (First) {
4886 // -- it is implicitly considered to be constexpr if the implicit
4887 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00004888 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00004889
Richard Smithb9e90b12012-05-15 04:39:51 +00004890 // -- it is implicitly considered to have the same exception-specification
4891 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00004892 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4893 EPI.ExceptionSpecType = EST_Unevaluated;
4894 EPI.ExceptionSpecDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00004895 MD->setType(Context.getFunctionType(ReturnType,
4896 ArrayRef<QualType>(&ArgType,
4897 ExpectedParams),
4898 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00004899 }
4900
Richard Smithb9e90b12012-05-15 04:39:51 +00004901 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004902 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00004903 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004904 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00004905 // C++11 [dcl.fct.def.default]p4:
4906 // [For a] user-provided explicitly-defaulted function [...] if such a
4907 // function is implicitly defined as deleted, the program is ill-formed.
4908 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith566184a2014-01-22 20:09:10 +00004909 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00004910 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004911 }
4912 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00004913
Richard Smithb9e90b12012-05-15 04:39:51 +00004914 if (HadError)
4915 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00004916}
4917
Richard Smithbd305122012-12-11 01:14:52 +00004918/// Check whether the exception specification provided for an
4919/// explicitly-defaulted special member matches the exception specification
4920/// that would have been generated for an implicit special member, per
4921/// C++11 [dcl.fct.def.default]p2.
4922void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4923 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4924 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00004925 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4926 /*IsCXXMethod=*/true);
4927 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smithbd305122012-12-11 01:14:52 +00004928 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4929 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004930 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00004931
4932 // Ensure that it matches.
4933 CheckEquivalentExceptionSpec(
4934 PDiag(diag::err_incorrect_defaulted_exception_spec)
4935 << getSpecialMember(MD), PDiag(),
4936 ImplicitType, SourceLocation(),
4937 SpecifiedType, MD->getLocation());
4938}
4939
Alp Tokerae3a9442013-10-18 05:54:19 +00004940void Sema::CheckDelayedMemberExceptionSpecs() {
4941 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
4942 2> Checks;
4943 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
Richard Smithbd305122012-12-11 01:14:52 +00004944
Alp Tokerae3a9442013-10-18 05:54:19 +00004945 std::swap(Checks, DelayedDestructorExceptionSpecChecks);
4946 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
4947
4948 // Perform any deferred checking of exception specifications for virtual
4949 // destructors.
4950 for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
4951 const CXXDestructorDecl *Dtor = Checks[i].first;
4952 assert(!Dtor->getParent()->isDependentType() &&
4953 "Should not ever add destructors of templates into the list.");
4954 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
4955 }
4956
4957 // Check that any explicitly-defaulted methods have exception specifications
4958 // compatible with their implicit exception specifications.
4959 for (unsigned I = 0, N = Specs.size(); I != N; ++I)
4960 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
4961 Specs[I].second);
Richard Smithbd305122012-12-11 01:14:52 +00004962}
4963
Richard Smithd951a1d2012-02-18 02:02:13 +00004964namespace {
4965struct SpecialMemberDeletionInfo {
4966 Sema &S;
4967 CXXMethodDecl *MD;
4968 Sema::CXXSpecialMember CSM;
Richard Smith852265f2012-03-30 20:53:28 +00004969 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00004970
4971 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00004972 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00004973 SourceLocation Loc;
4974
4975 bool AllFieldsAreConst;
4976
4977 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith852265f2012-03-30 20:53:28 +00004978 Sema::CXXSpecialMember CSM, bool Diagnose)
4979 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smithd951a1d2012-02-18 02:02:13 +00004980 IsConstructor(false), IsAssignment(false), IsMove(false),
Richard Smith41c35d62013-11-27 03:39:20 +00004981 ConstArg(false), Loc(MD->getLocation()),
Richard Smithd951a1d2012-02-18 02:02:13 +00004982 AllFieldsAreConst(true) {
4983 switch (CSM) {
4984 case Sema::CXXDefaultConstructor:
4985 case Sema::CXXCopyConstructor:
4986 IsConstructor = true;
4987 break;
4988 case Sema::CXXMoveConstructor:
4989 IsConstructor = true;
4990 IsMove = true;
4991 break;
4992 case Sema::CXXCopyAssignment:
4993 IsAssignment = true;
4994 break;
4995 case Sema::CXXMoveAssignment:
4996 IsAssignment = true;
4997 IsMove = true;
4998 break;
4999 case Sema::CXXDestructor:
5000 break;
5001 case Sema::CXXInvalid:
5002 llvm_unreachable("invalid special member kind");
5003 }
5004
5005 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00005006 if (const ReferenceType *RT =
5007 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5008 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00005009 }
5010 }
5011
5012 bool inUnion() const { return MD->getParent()->isUnion(); }
5013
5014 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00005015 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00005016 unsigned Quals, bool IsMutable) {
5017 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5018 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00005019 }
5020
Richard Smith852265f2012-03-30 20:53:28 +00005021 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00005022
Richard Smith852265f2012-03-30 20:53:28 +00005023 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00005024 bool shouldDeleteForField(FieldDecl *FD);
5025 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00005026
Richard Smithaf136f82012-07-18 03:51:16 +00005027 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5028 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00005029 bool shouldDeleteForSubobjectCall(Subobject Subobj,
5030 Sema::SpecialMemberOverloadResult *SMOR,
5031 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00005032
5033 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00005034};
5035}
5036
John McCalld4274212012-04-09 20:53:23 +00005037/// Is the given special member inaccessible when used on the given
5038/// sub-object.
5039bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5040 CXXMethodDecl *target) {
5041 /// If we're operating on a base class, the object type is the
5042 /// type of this special member.
5043 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005044 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00005045 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5046 objectTy = S.Context.getTypeDeclType(MD->getParent());
5047 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5048
5049 // If we're operating on a field, the object type is the type of the field.
5050 } else {
5051 objectTy = S.Context.getTypeDeclType(target->getParent());
5052 }
5053
5054 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5055}
5056
Richard Smith852265f2012-03-30 20:53:28 +00005057/// Check whether we should delete a special member due to the implicit
5058/// definition containing a call to a special member of a subobject.
5059bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5060 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5061 bool IsDtorCallInCtor) {
5062 CXXMethodDecl *Decl = SMOR->getMethod();
5063 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5064
5065 int DiagKind = -1;
5066
5067 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5068 DiagKind = !Decl ? 0 : 1;
5069 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5070 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00005071 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00005072 DiagKind = 3;
5073 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5074 !Decl->isTrivial()) {
5075 // A member of a union must have a trivial corresponding special member.
5076 // As a weird special case, a destructor call from a union's constructor
5077 // must be accessible and non-deleted, but need not be trivial. Such a
5078 // destructor is never actually called, but is semantically checked as
5079 // if it were.
5080 DiagKind = 4;
5081 }
5082
5083 if (DiagKind == -1)
5084 return false;
5085
5086 if (Diagnose) {
5087 if (Field) {
5088 S.Diag(Field->getLocation(),
5089 diag::note_deleted_special_member_class_subobject)
5090 << CSM << MD->getParent() << /*IsField*/true
5091 << Field << DiagKind << IsDtorCallInCtor;
5092 } else {
5093 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5094 S.Diag(Base->getLocStart(),
5095 diag::note_deleted_special_member_class_subobject)
5096 << CSM << MD->getParent() << /*IsField*/false
5097 << Base->getType() << DiagKind << IsDtorCallInCtor;
5098 }
5099
5100 if (DiagKind == 1)
5101 S.NoteDeletedFunction(Decl);
5102 // FIXME: Explain inaccessibility if DiagKind == 3.
5103 }
5104
5105 return true;
5106}
5107
Richard Smith921bd202012-02-26 09:11:52 +00005108/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00005109/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00005110bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00005111 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00005112 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00005113 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00005114
5115 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00005116 // -- any direct or virtual base class, or non-static data member with no
5117 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00005118 // either M has no default constructor or overload resolution as applied
5119 // to M's default constructor results in an ambiguity or in a function
5120 // that is deleted or inaccessible
5121 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5122 // -- a direct or virtual base class B that cannot be copied/moved because
5123 // overload resolution, as applied to B's corresponding special member,
5124 // results in an ambiguity or a function that is deleted or inaccessible
5125 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00005126 // C++11 [class.dtor]p5:
5127 // -- any direct or virtual base class [...] has a type with a destructor
5128 // that is deleted or inaccessible
5129 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005130 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00005131 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5132 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005133 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005134
Richard Smith852265f2012-03-30 20:53:28 +00005135 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5136 // -- any direct or virtual base class or non-static data member has a
5137 // type with a destructor that is deleted or inaccessible
5138 if (IsConstructor) {
5139 Sema::SpecialMemberOverloadResult *SMOR =
5140 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5141 false, false, false, false, false);
5142 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5143 return true;
5144 }
5145
Richard Smith921bd202012-02-26 09:11:52 +00005146 return false;
5147}
5148
5149/// Check whether we should delete a special member function due to the class
5150/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00005151bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005152 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smithaf136f82012-07-18 03:51:16 +00005153 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00005154}
5155
5156/// Check whether we should delete a special member function due to the class
5157/// having a particular non-static data member.
5158bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5159 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5160 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5161
5162 if (CSM == Sema::CXXDefaultConstructor) {
5163 // For a default constructor, all references must be initialized in-class
5164 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00005165 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5166 if (Diagnose)
5167 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5168 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005169 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005170 }
Richard Smith619ecdc2012-02-27 06:07:25 +00005171 // C++11 [class.ctor]p5: any non-variant non-static data member of
5172 // const-qualified type (or array thereof) with no
5173 // brace-or-equal-initializer does not have a user-provided default
5174 // constructor.
5175 if (!inUnion() && FieldType.isConstQualified() &&
5176 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00005177 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5178 if (Diagnose)
5179 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005180 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00005181 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005182 }
5183
5184 if (inUnion() && !FieldType.isConstQualified())
5185 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005186 } else if (CSM == Sema::CXXCopyConstructor) {
5187 // For a copy constructor, data members must not be of rvalue reference
5188 // type.
Richard Smith852265f2012-03-30 20:53:28 +00005189 if (FieldType->isRValueReferenceType()) {
5190 if (Diagnose)
5191 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5192 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00005193 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005194 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005195 } else if (IsAssignment) {
5196 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00005197 if (FieldType->isReferenceType()) {
5198 if (Diagnose)
5199 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5200 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005201 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005202 }
5203 if (!FieldRecord && FieldType.isConstQualified()) {
5204 // C++11 [class.copy]p23:
5205 // -- a non-static data member of const non-class type (or array thereof)
5206 if (Diagnose)
5207 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005208 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00005209 return true;
5210 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005211 }
5212
5213 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005214 // Some additional restrictions exist on the variant members.
5215 if (!inUnion() && FieldRecord->isUnion() &&
5216 FieldRecord->isAnonymousStructOrUnion()) {
5217 bool AllVariantFieldsAreConst = true;
5218
Richard Smith5704fe82012-03-29 19:00:10 +00005219 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smithd951a1d2012-02-18 02:02:13 +00005220 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
5221 UE = FieldRecord->field_end();
5222 UI != UE; ++UI) {
5223 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00005224
5225 if (!UnionFieldType.isConstQualified())
5226 AllVariantFieldsAreConst = false;
5227
Richard Smith921bd202012-02-26 09:11:52 +00005228 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5229 if (UnionFieldRecord &&
Richard Smithaf136f82012-07-18 03:51:16 +00005230 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
5231 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00005232 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005233 }
5234
5235 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00005236 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith852265f2012-03-30 20:53:28 +00005237 FieldRecord->field_begin() != FieldRecord->field_end()) {
5238 if (Diagnose)
5239 S.Diag(FieldRecord->getLocation(),
5240 diag::note_deleted_default_ctor_all_const)
5241 << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00005242 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005243 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005244
Richard Smith5704fe82012-03-29 19:00:10 +00005245 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00005246 // This is technically non-conformant, but sanity demands it.
5247 return false;
5248 }
5249
Richard Smithaf136f82012-07-18 03:51:16 +00005250 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5251 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00005252 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005253 }
5254
5255 return false;
5256}
5257
5258/// C++11 [class.ctor] p5:
5259/// A defaulted default constructor for a class X is defined as deleted if
5260/// X is a union and all of its variant members are of const-qualified type.
5261bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00005262 // This is a silly definition, because it gives an empty union a deleted
5263 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00005264 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5265 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
5266 if (Diagnose)
5267 S.Diag(MD->getParent()->getLocation(),
5268 diag::note_deleted_default_ctor_all_const)
5269 << MD->getParent() << /*not anonymous union*/0;
5270 return true;
5271 }
5272 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005273}
5274
5275/// Determine whether a defaulted special member function should be defined as
5276/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5277/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00005278bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5279 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00005280 if (MD->isInvalidDecl())
5281 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00005282 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00005283 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005284 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00005285 return false;
5286
Richard Smithd951a1d2012-02-18 02:02:13 +00005287 // C++11 [expr.lambda.prim]p19:
5288 // The closure type associated with a lambda-expression has a
5289 // deleted (8.4.3) default constructor and a deleted copy
5290 // assignment operator.
5291 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00005292 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5293 if (Diagnose)
5294 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00005295 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005296 }
5297
Richard Smith6f1e2c62012-04-02 20:59:25 +00005298 // For an anonymous struct or union, the copy and assignment special members
5299 // will never be used, so skip the check. For an anonymous union declared at
5300 // namespace scope, the constructor and destructor are used.
5301 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5302 RD->isAnonymousStructOrUnion())
5303 return false;
5304
Richard Smith852265f2012-03-30 20:53:28 +00005305 // C++11 [class.copy]p7, p18:
5306 // If the class definition declares a move constructor or move assignment
5307 // operator, an implicitly declared copy constructor or copy assignment
5308 // operator is defined as deleted.
5309 if (MD->isImplicit() &&
5310 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5311 CXXMethodDecl *UserDeclaredMove = 0;
5312
5313 // In Microsoft mode, a user-declared move only causes the deletion of the
5314 // corresponding copy operation, not both copy operations.
5315 if (RD->hasUserDeclaredMoveConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005316 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00005317 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005318
5319 // Find any user-declared move constructor.
5320 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
5321 E = RD->ctor_end(); I != E; ++I) {
5322 if (I->isMoveConstructor()) {
5323 UserDeclaredMove = *I;
5324 break;
5325 }
5326 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005327 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005328 } else if (RD->hasUserDeclaredMoveAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005329 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00005330 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005331
5332 // Find any user-declared move assignment operator.
5333 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
5334 E = RD->method_end(); I != E; ++I) {
5335 if (I->isMoveAssignmentOperator()) {
5336 UserDeclaredMove = *I;
5337 break;
5338 }
5339 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005340 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005341 }
5342
5343 if (UserDeclaredMove) {
5344 Diag(UserDeclaredMove->getLocation(),
5345 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00005346 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00005347 << UserDeclaredMove->isMoveAssignmentOperator();
5348 return true;
5349 }
5350 }
Alexis Huntd6da8762011-10-10 06:18:57 +00005351
Richard Smith6f1e2c62012-04-02 20:59:25 +00005352 // Do access control from the special member function
5353 ContextRAII MethodContext(*this, MD);
5354
Richard Smith921bd202012-02-26 09:11:52 +00005355 // C++11 [class.dtor]p5:
5356 // -- for a virtual destructor, lookup of the non-array deallocation function
5357 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00005358 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith921bd202012-02-26 09:11:52 +00005359 FunctionDecl *OperatorDelete = 0;
5360 DeclarationName Name =
5361 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5362 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00005363 OperatorDelete, false)) {
5364 if (Diagnose)
5365 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00005366 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005367 }
Richard Smith921bd202012-02-26 09:11:52 +00005368 }
5369
Richard Smith852265f2012-03-30 20:53:28 +00005370 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00005371
Alexis Huntea6f0322011-05-11 22:34:38 +00005372 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smithd951a1d2012-02-18 02:02:13 +00005373 BE = RD->bases_end(); BI != BE; ++BI)
5374 if (!BI->isVirtual() &&
Richard Smith852265f2012-03-30 20:53:28 +00005375 SMI.shouldDeleteForBase(BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005376 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005377
Richard Smithd1627032013-07-22 18:06:23 +00005378 // Per DR1611, do not consider virtual bases of constructors of abstract
5379 // classes, since we are not going to construct them.
Richard Smithbc46e432013-07-22 02:56:56 +00005380 if (!RD->isAbstract() || !SMI.IsConstructor) {
5381 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
5382 BE = RD->vbases_end();
5383 BI != BE; ++BI)
5384 if (SMI.shouldDeleteForBase(BI))
5385 return true;
5386 }
Alexis Huntea6f0322011-05-11 22:34:38 +00005387
5388 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smithd951a1d2012-02-18 02:02:13 +00005389 FE = RD->field_end(); FI != FE; ++FI)
5390 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie40ed2972012-06-06 20:45:41 +00005391 SMI.shouldDeleteForField(*FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00005392 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005393
Richard Smithd951a1d2012-02-18 02:02:13 +00005394 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00005395 return true;
5396
5397 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005398}
5399
Richard Smith92f241f2012-12-08 02:53:02 +00005400/// Perform lookup for a special member of the specified kind, and determine
5401/// whether it is trivial. If the triviality can be determined without the
5402/// lookup, skip it. This is intended for use when determining whether a
5403/// special member of a containing object is trivial, and thus does not ever
5404/// perform overload resolution for default constructors.
5405///
5406/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5407/// member that was most likely to be intended to be trivial, if any.
5408static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5409 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00005410 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00005411 if (Selected)
5412 *Selected = 0;
5413
5414 switch (CSM) {
5415 case Sema::CXXInvalid:
5416 llvm_unreachable("not a special member");
5417
5418 case Sema::CXXDefaultConstructor:
5419 // C++11 [class.ctor]p5:
5420 // A default constructor is trivial if:
5421 // - all the [direct subobjects] have trivial default constructors
5422 //
5423 // Note, no overload resolution is performed in this case.
5424 if (RD->hasTrivialDefaultConstructor())
5425 return true;
5426
5427 if (Selected) {
5428 // If there's a default constructor which could have been trivial, dig it
5429 // out. Otherwise, if there's any user-provided default constructor, point
5430 // to that as an example of why there's not a trivial one.
5431 CXXConstructorDecl *DefCtor = 0;
5432 if (RD->needsImplicitDefaultConstructor())
5433 S.DeclareImplicitDefaultConstructor(RD);
5434 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5435 CE = RD->ctor_end(); CI != CE; ++CI) {
5436 if (!CI->isDefaultConstructor())
5437 continue;
5438 DefCtor = *CI;
5439 if (!DefCtor->isUserProvided())
5440 break;
5441 }
5442
5443 *Selected = DefCtor;
5444 }
5445
5446 return false;
5447
5448 case Sema::CXXDestructor:
5449 // C++11 [class.dtor]p5:
5450 // A destructor is trivial if:
5451 // - all the direct [subobjects] have trivial destructors
5452 if (RD->hasTrivialDestructor())
5453 return true;
5454
5455 if (Selected) {
5456 if (RD->needsImplicitDestructor())
5457 S.DeclareImplicitDestructor(RD);
5458 *Selected = RD->getDestructor();
5459 }
5460
5461 return false;
5462
5463 case Sema::CXXCopyConstructor:
5464 // C++11 [class.copy]p12:
5465 // A copy constructor is trivial if:
5466 // - the constructor selected to copy each direct [subobject] is trivial
5467 if (RD->hasTrivialCopyConstructor()) {
5468 if (Quals == Qualifiers::Const)
5469 // We must either select the trivial copy constructor or reach an
5470 // ambiguity; no need to actually perform overload resolution.
5471 return true;
5472 } else if (!Selected) {
5473 return false;
5474 }
5475 // In C++98, we are not supposed to perform overload resolution here, but we
5476 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5477 // cases like B as having a non-trivial copy constructor:
5478 // struct A { template<typename T> A(T&); };
5479 // struct B { mutable A a; };
5480 goto NeedOverloadResolution;
5481
5482 case Sema::CXXCopyAssignment:
5483 // C++11 [class.copy]p25:
5484 // A copy assignment operator is trivial if:
5485 // - the assignment operator selected to copy each direct [subobject] is
5486 // trivial
5487 if (RD->hasTrivialCopyAssignment()) {
5488 if (Quals == Qualifiers::Const)
5489 return true;
5490 } else if (!Selected) {
5491 return false;
5492 }
5493 // In C++98, we are not supposed to perform overload resolution here, but we
5494 // treat that as a language defect.
5495 goto NeedOverloadResolution;
5496
5497 case Sema::CXXMoveConstructor:
5498 case Sema::CXXMoveAssignment:
5499 NeedOverloadResolution:
5500 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005501 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00005502
5503 // The standard doesn't describe how to behave if the lookup is ambiguous.
5504 // We treat it as not making the member non-trivial, just like the standard
5505 // mandates for the default constructor. This should rarely matter, because
5506 // the member will also be deleted.
5507 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5508 return true;
5509
5510 if (!SMOR->getMethod()) {
5511 assert(SMOR->getKind() ==
5512 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5513 return false;
5514 }
5515
5516 // We deliberately don't check if we found a deleted special member. We're
5517 // not supposed to!
5518 if (Selected)
5519 *Selected = SMOR->getMethod();
5520 return SMOR->getMethod()->isTrivial();
5521 }
5522
5523 llvm_unreachable("unknown special method kind");
5524}
5525
Benjamin Kramer3e350262013-02-15 12:30:38 +00005526static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smith92f241f2012-12-08 02:53:02 +00005527 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5528 CI != CE; ++CI)
5529 if (!CI->isImplicit())
5530 return *CI;
5531
5532 // Look for constructor templates.
5533 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5534 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5535 if (CXXConstructorDecl *CD =
5536 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5537 return CD;
5538 }
5539
5540 return 0;
5541}
5542
5543/// The kind of subobject we are checking for triviality. The values of this
5544/// enumeration are used in diagnostics.
5545enum TrivialSubobjectKind {
5546 /// The subobject is a base class.
5547 TSK_BaseClass,
5548 /// The subobject is a non-static data member.
5549 TSK_Field,
5550 /// The object is actually the complete object.
5551 TSK_CompleteObject
5552};
5553
5554/// Check whether the special member selected for a given type would be trivial.
5555static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00005556 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00005557 Sema::CXXSpecialMember CSM,
5558 TrivialSubobjectKind Kind,
5559 bool Diagnose) {
5560 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5561 if (!SubRD)
5562 return true;
5563
5564 CXXMethodDecl *Selected;
5565 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Richard Smith41c35d62013-11-27 03:39:20 +00005566 ConstRHS, Diagnose ? &Selected : 0))
Richard Smith92f241f2012-12-08 02:53:02 +00005567 return true;
5568
5569 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00005570 if (ConstRHS)
5571 SubType.addConst();
5572
Richard Smith92f241f2012-12-08 02:53:02 +00005573 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5574 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5575 << Kind << SubType.getUnqualifiedType();
5576 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5577 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5578 } else if (!Selected)
5579 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5580 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5581 else if (Selected->isUserProvided()) {
5582 if (Kind == TSK_CompleteObject)
5583 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5584 << Kind << SubType.getUnqualifiedType() << CSM;
5585 else {
5586 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5587 << Kind << SubType.getUnqualifiedType() << CSM;
5588 S.Diag(Selected->getLocation(), diag::note_declared_at);
5589 }
5590 } else {
5591 if (Kind != TSK_CompleteObject)
5592 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5593 << Kind << SubType.getUnqualifiedType() << CSM;
5594
5595 // Explain why the defaulted or deleted special member isn't trivial.
5596 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5597 }
5598 }
5599
5600 return false;
5601}
5602
5603/// Check whether the members of a class type allow a special member to be
5604/// trivial.
5605static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5606 Sema::CXXSpecialMember CSM,
5607 bool ConstArg, bool Diagnose) {
5608 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5609 FE = RD->field_end(); FI != FE; ++FI) {
5610 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5611 continue;
5612
5613 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5614
5615 // Pretend anonymous struct or union members are members of this class.
5616 if (FI->isAnonymousStructOrUnion()) {
5617 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5618 CSM, ConstArg, Diagnose))
5619 return false;
5620 continue;
5621 }
5622
5623 // C++11 [class.ctor]p5:
5624 // A default constructor is trivial if [...]
5625 // -- no non-static data member of its class has a
5626 // brace-or-equal-initializer
5627 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5628 if (Diagnose)
5629 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5630 return false;
5631 }
5632
5633 // Objective C ARC 4.3.5:
5634 // [...] nontrivally ownership-qualified types are [...] not trivially
5635 // default constructible, copy constructible, move constructible, copy
5636 // assignable, move assignable, or destructible [...]
5637 if (S.getLangOpts().ObjCAutoRefCount &&
5638 FieldType.hasNonTrivialObjCLifetime()) {
5639 if (Diagnose)
5640 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5641 << RD << FieldType.getObjCLifetime();
5642 return false;
5643 }
5644
Richard Smith41c35d62013-11-27 03:39:20 +00005645 bool ConstRHS = ConstArg && !FI->isMutable();
5646 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
5647 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005648 return false;
5649 }
5650
5651 return true;
5652}
5653
5654/// Diagnose why the specified class does not have a trivial special member of
5655/// the given kind.
5656void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5657 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00005658
Richard Smith41c35d62013-11-27 03:39:20 +00005659 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
5660 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00005661 TSK_CompleteObject, /*Diagnose*/true);
5662}
5663
5664/// Determine whether a defaulted or deleted special member function is trivial,
5665/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5666/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5667bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5668 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00005669 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5670
5671 CXXRecordDecl *RD = MD->getParent();
5672
5673 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00005674
Richard Smith2002bfe2013-11-04 02:02:27 +00005675 // C++11 [class.copy]p12, p25: [DR1593]
5676 // A [special member] is trivial if [...] its parameter-type-list is
5677 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00005678 switch (CSM) {
5679 case CXXDefaultConstructor:
5680 case CXXDestructor:
5681 // Trivial default constructors and destructors cannot have parameters.
5682 break;
5683
5684 case CXXCopyConstructor:
5685 case CXXCopyAssignment: {
5686 // Trivial copy operations always have const, non-volatile parameter types.
5687 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00005688 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005689 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5690 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5691 if (Diagnose)
5692 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5693 << Param0->getSourceRange() << Param0->getType()
5694 << Context.getLValueReferenceType(
5695 Context.getRecordType(RD).withConst());
5696 return false;
5697 }
5698 break;
5699 }
5700
5701 case CXXMoveConstructor:
5702 case CXXMoveAssignment: {
5703 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00005704 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005705 const RValueReferenceType *RT =
5706 Param0->getType()->getAs<RValueReferenceType>();
5707 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5708 if (Diagnose)
5709 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5710 << Param0->getSourceRange() << Param0->getType()
5711 << Context.getRValueReferenceType(Context.getRecordType(RD));
5712 return false;
5713 }
5714 break;
5715 }
5716
5717 case CXXInvalid:
5718 llvm_unreachable("not a special member");
5719 }
5720
Richard Smith92f241f2012-12-08 02:53:02 +00005721 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5722 if (Diagnose)
5723 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5724 diag::note_nontrivial_default_arg)
5725 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5726 return false;
5727 }
5728 if (MD->isVariadic()) {
5729 if (Diagnose)
5730 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5731 return false;
5732 }
5733
5734 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5735 // A copy/move [constructor or assignment operator] is trivial if
5736 // -- the [member] selected to copy/move each direct base class subobject
5737 // is trivial
5738 //
5739 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5740 // A [default constructor or destructor] is trivial if
5741 // -- all the direct base classes have trivial [default constructors or
5742 // destructors]
5743 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5744 BE = RD->bases_end(); BI != BE; ++BI)
Richard Smith41c35d62013-11-27 03:39:20 +00005745 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(), BI->getType(),
5746 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005747 return false;
5748
5749 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5750 // A copy/move [constructor or assignment operator] for a class X is
5751 // trivial if
5752 // -- for each non-static data member of X that is of class type (or array
5753 // thereof), the constructor selected to copy/move that member is
5754 // trivial
5755 //
5756 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5757 // A [default constructor or destructor] is trivial if
5758 // -- for all of the non-static data members of its class that are of class
5759 // type (or array thereof), each such class has a trivial [default
5760 // constructor or destructor]
5761 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5762 return false;
5763
5764 // C++11 [class.dtor]p5:
5765 // A destructor is trivial if [...]
5766 // -- the destructor is not virtual
5767 if (CSM == CXXDestructor && MD->isVirtual()) {
5768 if (Diagnose)
5769 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5770 return false;
5771 }
5772
5773 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5774 // A [special member] for class X is trivial if [...]
5775 // -- class X has no virtual functions and no virtual base classes
5776 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5777 if (!Diagnose)
5778 return false;
5779
5780 if (RD->getNumVBases()) {
5781 // Check for virtual bases. We already know that the corresponding
5782 // member in all bases is trivial, so vbases must all be direct.
5783 CXXBaseSpecifier &BS = *RD->vbases_begin();
5784 assert(BS.isVirtual());
5785 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5786 return false;
5787 }
5788
5789 // Must have a virtual method.
5790 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5791 ME = RD->method_end(); MI != ME; ++MI) {
5792 if (MI->isVirtual()) {
5793 SourceLocation MLoc = MI->getLocStart();
5794 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5795 return false;
5796 }
5797 }
5798
5799 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5800 }
5801
5802 // Looks like it's trivial!
5803 return true;
5804}
5805
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005806/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00005807namespace {
5808 struct FindHiddenVirtualMethodData {
5809 Sema *S;
5810 CXXMethodDecl *Method;
5811 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005812 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00005813 };
5814}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005815
David Blaikie282c92a2012-10-19 00:53:08 +00005816/// \brief Check whether any most overriden method from MD in Methods
5817static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5818 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5819 if (MD->size_overridden_methods() == 0)
5820 return Methods.count(MD->getCanonicalDecl());
5821 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5822 E = MD->end_overridden_methods();
5823 I != E; ++I)
5824 if (CheckMostOverridenMethods(*I, Methods))
5825 return true;
5826 return false;
5827}
5828
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005829/// \brief Member lookup function that determines whether a given C++
5830/// method overloads virtual methods in a base class without overriding any,
5831/// to be used with CXXRecordDecl::lookupInBases().
5832static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5833 CXXBasePath &Path,
5834 void *UserData) {
5835 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5836
5837 FindHiddenVirtualMethodData &Data
5838 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5839
5840 DeclarationName Name = Data.Method->getDeclName();
5841 assert(Name.getNameKind() == DeclarationName::Identifier);
5842
5843 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005844 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005845 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00005846 !Path.Decls.empty();
5847 Path.Decls = Path.Decls.slice(1)) {
5848 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005849 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00005850 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005851 foundSameNameMethod = true;
5852 // Interested only in hidden virtual methods.
5853 if (!MD->isVirtual())
5854 continue;
5855 // If the method we are checking overrides a method from its base
5856 // don't warn about the other overloaded methods.
5857 if (!Data.S->IsOverload(Data.Method, MD, false))
5858 return true;
5859 // Collect the overload only if its hidden.
David Blaikie282c92a2012-10-19 00:53:08 +00005860 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005861 overloadedMethods.push_back(MD);
5862 }
5863 }
5864
5865 if (foundSameNameMethod)
5866 Data.OverloadedMethods.append(overloadedMethods.begin(),
5867 overloadedMethods.end());
5868 return foundSameNameMethod;
5869}
5870
David Blaikie282c92a2012-10-19 00:53:08 +00005871/// \brief Add the most overriden methods from MD to Methods
5872static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5873 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5874 if (MD->size_overridden_methods() == 0)
5875 Methods.insert(MD->getCanonicalDecl());
5876 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5877 E = MD->end_overridden_methods();
5878 I != E; ++I)
5879 AddMostOverridenMethods(*I, Methods);
5880}
5881
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005882/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005883/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005884void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5885 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00005886 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005887 return;
5888
5889 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5890 /*bool RecordPaths=*/false,
5891 /*bool DetectVirtual=*/false);
5892 FindHiddenVirtualMethodData Data;
5893 Data.Method = MD;
5894 Data.S = this;
5895
5896 // Keep the base methods that were overriden or introduced in the subclass
5897 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005898 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00005899 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5900 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5901 NamedDecl *ND = *I;
5902 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00005903 ND = shad->getTargetDecl();
5904 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5905 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005906 }
5907
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005908 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5909 OverloadedMethods = Data.OverloadedMethods;
5910}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005911
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005912void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
5913 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5914 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
5915 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
5916 PartialDiagnostic PD = PDiag(
5917 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5918 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5919 Diag(overloadedMD->getLocation(), PD);
5920 }
5921}
5922
5923/// \brief Diagnose methods which overload virtual methods in a base class
5924/// without overriding any.
5925void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
5926 if (MD->isInvalidDecl())
5927 return;
5928
5929 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5930 MD->getLocation()) == DiagnosticsEngine::Ignored)
5931 return;
5932
5933 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5934 FindHiddenVirtualMethods(MD, OverloadedMethods);
5935 if (!OverloadedMethods.empty()) {
5936 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5937 << MD << (OverloadedMethods.size() > 1);
5938
5939 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005940 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00005941}
5942
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005943void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00005944 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005945 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00005946 SourceLocation RBrac,
5947 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005948 if (!TagDecl)
5949 return;
Mike Stump11289f42009-09-09 15:08:12 +00005950
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005951 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00005952
Rafael Espindola06e1b132012-07-12 04:32:30 +00005953 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5954 if (l->getKind() != AttributeList::AT_Visibility)
5955 continue;
5956 l->setInvalid();
5957 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5958 l->getName();
5959 }
5960
David Blaikie751c5582011-09-22 02:58:26 +00005961 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00005962 // strict aliasing violation!
5963 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00005964 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00005965
Douglas Gregor0be31a22010-07-02 17:43:08 +00005966 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00005967 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005968}
5969
Douglas Gregor05379422008-11-03 17:51:48 +00005970/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5971/// special functions, such as the default constructor, copy
5972/// constructor, or destructor, to the given C++ class (C++
5973/// [special]p1). This routine can only be executed just before the
5974/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00005975void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005976 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00005977 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005978
Richard Smith6b02d462012-12-08 08:32:28 +00005979 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005980 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005981
Richard Smith6b02d462012-12-08 08:32:28 +00005982 // If the properties or semantics of the copy constructor couldn't be
5983 // determined while the class was being declared, force a declaration
5984 // of it now.
5985 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5986 DeclareImplicitCopyConstructor(ClassDecl);
5987 }
5988
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005989 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00005990 ++ASTContext::NumImplicitMoveConstructors;
5991
Richard Smith6b02d462012-12-08 08:32:28 +00005992 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5993 DeclareImplicitMoveConstructor(ClassDecl);
5994 }
5995
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005996 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5997 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00005998
5999 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006000 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00006001 // it shows up in the right place in the vtable and that we diagnose
6002 // problems with the implicit exception specification.
6003 if (ClassDecl->isDynamicClass() ||
6004 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006005 DeclareImplicitCopyAssignment(ClassDecl);
6006 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006007
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006008 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006009 ++ASTContext::NumImplicitMoveAssignmentOperators;
6010
6011 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00006012 if (ClassDecl->isDynamicClass() ||
6013 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00006014 DeclareImplicitMoveAssignment(ClassDecl);
6015 }
6016
Douglas Gregor7454c562010-07-02 20:37:36 +00006017 if (!ClassDecl->hasUserDeclaredDestructor()) {
6018 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00006019
6020 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00006021 // have to declare the destructor immediately. This ensures that, e.g., it
6022 // shows up in the right place in the vtable and that we diagnose problems
6023 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00006024 if (ClassDecl->isDynamicClass() ||
6025 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00006026 DeclareImplicitDestructor(ClassDecl);
6027 }
Douglas Gregor05379422008-11-03 17:51:48 +00006028}
6029
Francois Pichet1c229c02011-04-22 22:18:13 +00006030void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
6031 if (!D)
6032 return;
6033
6034 int NumParamList = D->getNumTemplateParameterLists();
6035 for (int i = 0; i < NumParamList; i++) {
6036 TemplateParameterList* Params = D->getTemplateParameterList(i);
6037 for (TemplateParameterList::iterator Param = Params->begin(),
6038 ParamEnd = Params->end();
6039 Param != ParamEnd; ++Param) {
6040 NamedDecl *Named = cast<NamedDecl>(*Param);
6041 if (Named->getDeclName()) {
6042 S->AddDecl(Named);
6043 IdResolver.AddDecl(Named);
6044 }
6045 }
6046 }
6047}
6048
John McCall48871652010-08-21 09:40:31 +00006049void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00006050 if (!D)
6051 return;
6052
6053 TemplateParameterList *Params = 0;
6054 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
6055 Params = Template->getTemplateParameters();
6056 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
6057 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6058 Params = PartialSpec->getTemplateParameters();
6059 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006060 return;
6061
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006062 for (TemplateParameterList::iterator Param = Params->begin(),
6063 ParamEnd = Params->end();
6064 Param != ParamEnd; ++Param) {
6065 NamedDecl *Named = cast<NamedDecl>(*Param);
6066 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00006067 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006068 IdResolver.AddDecl(Named);
6069 }
6070 }
6071}
6072
John McCall48871652010-08-21 09:40:31 +00006073void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006074 if (!RecordD) return;
6075 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00006076 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00006077 PushDeclContext(S, Record);
6078}
6079
John McCall48871652010-08-21 09:40:31 +00006080void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006081 if (!RecordD) return;
6082 PopDeclContext();
6083}
6084
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006085/// This is used to implement the constant expression evaluation part of the
6086/// attribute enable_if extension. There is nothing in standard C++ which would
6087/// require reentering parameters.
6088void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6089 if (!Param)
6090 return;
6091
6092 S->AddDecl(Param);
6093 if (Param->getDeclName())
6094 IdResolver.AddDecl(Param);
6095}
6096
Douglas Gregor4d87df52008-12-16 21:30:33 +00006097/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6098/// parsing a top-level (non-nested) C++ class, and we are now
6099/// parsing those parts of the given Method declaration that could
6100/// not be parsed earlier (C++ [class.mem]p2), such as default
6101/// arguments. This action should enter the scope of the given
6102/// Method declaration as if we had just parsed the qualified method
6103/// name. However, it should not bring the parameters into scope;
6104/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00006105void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006106}
6107
6108/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6109/// C++ method declaration. We're (re-)introducing the given
6110/// function parameter into scope for use in parsing later parts of
6111/// the method declaration. For example, we could see an
6112/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00006113void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006114 if (!ParamD)
6115 return;
Mike Stump11289f42009-09-09 15:08:12 +00006116
John McCall48871652010-08-21 09:40:31 +00006117 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00006118
6119 // If this parameter has an unparsed default argument, clear it out
6120 // to make way for the parsed default argument.
6121 if (Param->hasUnparsedDefaultArg())
6122 Param->setDefaultArg(0);
6123
John McCall48871652010-08-21 09:40:31 +00006124 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006125 if (Param->getDeclName())
6126 IdResolver.AddDecl(Param);
6127}
6128
6129/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6130/// processing the delayed method declaration for Method. The method
6131/// declaration is now considered finished. There may be a separate
6132/// ActOnStartOfFunctionDef action later (not necessarily
6133/// immediately!) for this method, if it was also defined inside the
6134/// class body.
John McCall48871652010-08-21 09:40:31 +00006135void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006136 if (!MethodD)
6137 return;
Mike Stump11289f42009-09-09 15:08:12 +00006138
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006139 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00006140
John McCall48871652010-08-21 09:40:31 +00006141 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006142
6143 // Now that we have our default arguments, check the constructor
6144 // again. It could produce additional diagnostics or affect whether
6145 // the class has implicitly-declared destructors, among other
6146 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006147 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6148 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006149
6150 // Check the default arguments, which we may have added.
6151 if (!Method->isInvalidDecl())
6152 CheckCXXDefaultArguments(Method);
6153}
6154
Douglas Gregor831c93f2008-11-05 20:51:48 +00006155/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00006156/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00006157/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006158/// emit diagnostics and set the invalid bit to true. In any case, the type
6159/// will be updated to reflect a well-formed type for the constructor and
6160/// returned.
6161QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006162 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006163 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006164
6165 // C++ [class.ctor]p3:
6166 // A constructor shall not be virtual (10.3) or static (9.4). A
6167 // constructor can be invoked for a const, volatile or const
6168 // volatile object. A constructor shall not be declared const,
6169 // volatile, or const volatile (9.3.2).
6170 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006171 if (!D.isInvalidType())
6172 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6173 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6174 << SourceRange(D.getIdentifierLoc());
6175 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006176 }
John McCall8e7d6562010-08-26 03:08:43 +00006177 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006178 if (!D.isInvalidType())
6179 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6180 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6181 << SourceRange(D.getIdentifierLoc());
6182 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006183 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006184 }
Mike Stump11289f42009-09-09 15:08:12 +00006185
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006186 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006187 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00006188 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006189 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6190 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006191 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006192 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6193 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006194 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006195 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6196 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00006197 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006198 }
Mike Stump11289f42009-09-09 15:08:12 +00006199
Douglas Gregordb9d6642011-01-26 05:01:58 +00006200 // C++0x [class.ctor]p4:
6201 // A constructor shall not be declared with a ref-qualifier.
6202 if (FTI.hasRefQualifier()) {
6203 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6204 << FTI.RefQualifierIsLValueRef
6205 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6206 D.setInvalidType();
6207 }
6208
Douglas Gregor831c93f2008-11-05 20:51:48 +00006209 // Rebuild the function type "R" without any type qualifiers (in
6210 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00006211 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00006212 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006213 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00006214 return R;
6215
6216 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6217 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006218 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00006219
6220 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006221}
6222
Douglas Gregor4d87df52008-12-16 21:30:33 +00006223/// CheckConstructor - Checks a fully-formed constructor for
6224/// well-formedness, issuing any diagnostics required. Returns true if
6225/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006226void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00006227 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006228 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6229 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006230 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006231
6232 // C++ [class.copy]p3:
6233 // A declaration of a constructor for a class X is ill-formed if
6234 // its first parameter is of type (optionally cv-qualified) X and
6235 // either there are no other parameters or else all other
6236 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006237 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00006238 ((Constructor->getNumParams() == 1) ||
6239 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00006240 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6241 Constructor->getTemplateSpecializationKind()
6242 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006243 QualType ParamType = Constructor->getParamDecl(0)->getType();
6244 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6245 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00006246 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00006247 const char *ConstRef
6248 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6249 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00006250 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00006251 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00006252
6253 // FIXME: Rather that making the constructor invalid, we should endeavor
6254 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006255 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006256 }
6257 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00006258}
6259
John McCalldeb646e2010-08-04 01:04:25 +00006260/// CheckDestructor - Checks a fully-formed destructor definition for
6261/// well-formedness, issuing any diagnostics required. Returns true
6262/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00006263bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006264 CXXRecordDecl *RD = Destructor->getParent();
6265
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006266 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006267 SourceLocation Loc;
6268
6269 if (!Destructor->isImplicit())
6270 Loc = Destructor->getLocation();
6271 else
6272 Loc = RD->getLocation();
6273
6274 // If we have a virtual destructor, look up the deallocation function
6275 FunctionDecl *OperatorDelete = 0;
6276 DeclarationName Name =
6277 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006278 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00006279 return true;
Richard Smithf03bd302013-12-05 08:30:59 +00006280 // If there's no class-specific operator delete, look up the global
6281 // non-array delete.
6282 if (!OperatorDelete)
6283 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall1e5d75d2010-07-03 18:33:00 +00006284
Eli Friedmanfa0df832012-02-02 03:46:19 +00006285 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00006286
6287 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006288 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00006289
6290 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006291}
6292
Mike Stump11289f42009-09-09 15:08:12 +00006293static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00006294FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
Alp Tokerc5350722014-02-26 22:27:52 +00006295 return (FTI.NumParams == 1 && !FTI.isVariadic && FTI.Params[0].Ident == 0 &&
6296 FTI.Params[0].Param &&
6297 cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00006298}
6299
Douglas Gregor831c93f2008-11-05 20:51:48 +00006300/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6301/// the well-formednes of the destructor declarator @p D with type @p
6302/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006303/// emit diagnostics and set the declarator to invalid. Even if this happens,
6304/// will be updated to reflect a well-formed type for the destructor and
6305/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00006306QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006307 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006308 // C++ [class.dtor]p1:
6309 // [...] A typedef-name that names a class is a class-name
6310 // (7.1.3); however, a typedef-name that names a class shall not
6311 // be used as the identifier in the declarator for a destructor
6312 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00006313 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00006314 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00006315 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00006316 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00006317 else if (const TemplateSpecializationType *TST =
6318 DeclaratorType->getAs<TemplateSpecializationType>())
6319 if (TST->isTypeAlias())
6320 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6321 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006322
6323 // C++ [class.dtor]p2:
6324 // A destructor is used to destroy objects of its class type. A
6325 // destructor takes no parameters, and no return type can be
6326 // specified for it (not even void). The address of a destructor
6327 // shall not be taken. A destructor shall not be static. A
6328 // destructor can be invoked for a const, volatile or const
6329 // volatile object. A destructor shall not be declared const,
6330 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00006331 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006332 if (!D.isInvalidType())
6333 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6334 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00006335 << SourceRange(D.getIdentifierLoc())
6336 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6337
John McCall8e7d6562010-08-26 03:08:43 +00006338 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006339 }
Chris Lattner38378bf2009-04-25 08:28:21 +00006340 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006341 // Destructors don't have return types, but the parser will
6342 // happily parse something like:
6343 //
6344 // class X {
6345 // float ~X();
6346 // };
6347 //
6348 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00006349 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6350 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6351 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00006352 }
Mike Stump11289f42009-09-09 15:08:12 +00006353
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006354 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006355 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006356 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006357 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6358 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006359 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006360 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6361 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006362 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006363 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6364 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00006365 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006366 }
6367
Douglas Gregordb9d6642011-01-26 05:01:58 +00006368 // C++0x [class.dtor]p2:
6369 // A destructor shall not be declared with a ref-qualifier.
6370 if (FTI.hasRefQualifier()) {
6371 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6372 << FTI.RefQualifierIsLValueRef
6373 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6374 D.setInvalidType();
6375 }
6376
Douglas Gregor831c93f2008-11-05 20:51:48 +00006377 // Make sure we don't have any parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006378 if (FTI.NumParams > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006379 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6380
6381 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006382 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00006383 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006384 }
6385
Mike Stump11289f42009-09-09 15:08:12 +00006386 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00006387 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006388 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00006389 D.setInvalidType();
6390 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006391
6392 // Rebuild the function type "R" without any type qualifiers or
6393 // parameters (in case any of the errors above fired) and with
6394 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00006395 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00006396 if (!D.isInvalidType())
6397 return R;
6398
Douglas Gregor95755162010-07-01 05:10:53 +00006399 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006400 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6401 EPI.Variadic = false;
6402 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006403 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006404 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006405}
6406
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006407/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6408/// well-formednes of the conversion function declarator @p D with
6409/// type @p R. If there are any errors in the declarator, this routine
6410/// will emit diagnostics and return true. Otherwise, it will return
6411/// false. Either way, the type @p R will be updated to reflect a
6412/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006413void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00006414 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006415 // C++ [class.conv.fct]p1:
6416 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00006417 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00006418 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00006419 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006420 if (!D.isInvalidType())
6421 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00006422 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6423 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006424 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006425 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006426 }
John McCall212fa2e2010-04-13 00:04:31 +00006427
6428 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6429
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006430 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006431 // Conversion functions don't have return types, but the parser will
6432 // happily parse something like:
6433 //
6434 // class X {
6435 // float operator bool();
6436 // };
6437 //
6438 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00006439 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6440 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6441 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00006442 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006443 }
6444
John McCall212fa2e2010-04-13 00:04:31 +00006445 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6446
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006447 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00006448 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006449 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6450
6451 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006452 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006453 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00006454 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006455 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006456 D.setInvalidType();
6457 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006458
John McCall212fa2e2010-04-13 00:04:31 +00006459 // Diagnose "&operator bool()" and other such nonsense. This
6460 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00006461 if (Proto->getReturnType() != ConvType) {
John McCall212fa2e2010-04-13 00:04:31 +00006462 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
Alp Toker314cc812014-01-25 16:55:45 +00006463 << Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006464 D.setInvalidType();
Alp Toker314cc812014-01-25 16:55:45 +00006465 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006466 }
6467
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006468 // C++ [class.conv.fct]p4:
6469 // The conversion-type-id shall not represent a function type nor
6470 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006471 if (ConvType->isArrayType()) {
6472 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6473 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006474 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006475 } else if (ConvType->isFunctionType()) {
6476 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6477 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006478 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006479 }
6480
6481 // Rebuild the function type "R" without any parameters (in case any
6482 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00006483 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00006484 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006485 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006486
Douglas Gregor5fb53972009-01-14 15:45:31 +00006487 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006488 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00006489 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006490 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006491 diag::warn_cxx98_compat_explicit_conversion_functions :
6492 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00006493 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006494}
6495
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006496/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6497/// the declaration of the given C++ conversion function. This routine
6498/// is responsible for recording the conversion function in the C++
6499/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00006500Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006501 assert(Conversion && "Expected to receive a conversion function declaration");
6502
Douglas Gregor4287b372008-12-12 08:25:50 +00006503 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006504
6505 // Make sure we aren't redeclaring the conversion function.
6506 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006507
6508 // C++ [class.conv.fct]p1:
6509 // [...] A conversion function is never used to convert a
6510 // (possibly cv-qualified) object to the (possibly cv-qualified)
6511 // same object type (or a reference to it), to a (possibly
6512 // cv-qualified) base class of that type (or a reference to it),
6513 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00006514 // FIXME: Suppress this warning if the conversion function ends up being a
6515 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00006516 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006517 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006518 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006519 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006520 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6521 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00006522 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006523 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006524 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6525 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006526 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006527 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006528 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006529 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006530 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006531 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006532 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006533 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006534 }
6535
Douglas Gregor457104e2010-09-29 04:25:11 +00006536 if (FunctionTemplateDecl *ConversionTemplate
6537 = Conversion->getDescribedFunctionTemplate())
6538 return ConversionTemplate;
6539
John McCall48871652010-08-21 09:40:31 +00006540 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006541}
6542
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006543//===----------------------------------------------------------------------===//
6544// Namespace Handling
6545//===----------------------------------------------------------------------===//
6546
Richard Smith45bb8852012-10-04 22:13:39 +00006547/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6548/// reopened.
6549static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6550 SourceLocation Loc,
6551 IdentifierInfo *II, bool *IsInline,
6552 NamespaceDecl *PrevNS) {
6553 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00006554
Richard Smithf501cc32012-10-05 01:46:25 +00006555 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6556 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6557 // inline namespaces, with the intention of bringing names into namespace std.
6558 //
6559 // We support this just well enough to get that case working; this is not
6560 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00006561 if (*IsInline && II && II->getName().startswith("__atomic") &&
6562 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00006563 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00006564 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6565 NS = NS->getPreviousDecl())
6566 NS->setInline(*IsInline);
6567 // Patch up the lookup table for the containing namespace. This isn't really
6568 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00006569 for (auto *I : PrevNS->decls())
6570 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00006571 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6572 return;
6573 }
6574
6575 if (PrevNS->isInline())
6576 // The user probably just forgot the 'inline', so suggest that it
6577 // be added back.
6578 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6579 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6580 else
6581 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6582 << IsInline;
6583
6584 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6585 *IsInline = PrevNS->isInline();
6586}
John McCallb1be5232010-08-26 09:15:37 +00006587
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006588/// ActOnStartNamespaceDef - This is called at the start of a namespace
6589/// definition.
John McCall48871652010-08-21 09:40:31 +00006590Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00006591 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006592 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00006593 SourceLocation IdentLoc,
6594 IdentifierInfo *II,
6595 SourceLocation LBrace,
6596 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006597 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6598 // For anonymous namespace, take the location of the left brace.
6599 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00006600 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00006601 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00006602 bool IsStd = false;
6603 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006604 Scope *DeclRegionScope = NamespcScope->getParent();
6605
Douglas Gregore57e7522012-01-07 09:11:48 +00006606 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006607 if (II) {
6608 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00006609 // The identifier in an original-namespace-definition shall not
6610 // have been previously defined in the declarative region in
6611 // which the original-namespace-definition appears. The
6612 // identifier in an original-namespace-definition is the name of
6613 // the namespace. Subsequently in that declarative region, it is
6614 // treated as an original-namespace-name.
6615 //
6616 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006617 // look through using directives, just look for any ordinary names.
6618
6619 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00006620 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6621 Decl::IDNS_Namespace;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006622 NamedDecl *PrevDecl = 0;
David Blaikieff7d47a2012-12-19 00:45:41 +00006623 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6624 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6625 ++I) {
6626 if ((*I)->getIdentifierNamespace() & IDNS) {
6627 PrevDecl = *I;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006628 break;
6629 }
6630 }
6631
Douglas Gregore57e7522012-01-07 09:11:48 +00006632 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6633
6634 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00006635 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00006636 if (IsInline != PrevNS->isInline())
6637 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6638 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00006639 } else if (PrevDecl) {
6640 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006641 Diag(Loc, diag::err_redefinition_different_kind)
6642 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00006643 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006644 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00006645 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00006646 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00006647 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00006648 // This is the first "real" definition of the namespace "std", so update
6649 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006650 PrevNS = getStdNamespace();
6651 IsStd = true;
6652 AddToKnown = !IsInline;
6653 } else {
6654 // We've seen this namespace for the first time.
6655 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00006656 }
Douglas Gregor91f84212008-12-11 16:49:14 +00006657 } else {
John McCall4fa53422009-10-01 00:25:31 +00006658 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00006659
6660 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00006661 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00006662 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00006663 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006664 } else {
6665 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00006666 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006667 }
6668
Richard Smith45bb8852012-10-04 22:13:39 +00006669 if (PrevNS && IsInline != PrevNS->isInline())
6670 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6671 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00006672 }
6673
6674 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6675 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006676 if (IsInvalid)
6677 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00006678
6679 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00006680
Douglas Gregore57e7522012-01-07 09:11:48 +00006681 // FIXME: Should we be merging attributes?
6682 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006683 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00006684
6685 if (IsStd)
6686 StdNamespace = Namespc;
6687 if (AddToKnown)
6688 KnownNamespaces[Namespc] = false;
6689
6690 if (II) {
6691 PushOnScopeChains(Namespc, DeclRegionScope);
6692 } else {
6693 // Link the anonymous namespace into its parent.
6694 DeclContext *Parent = CurContext->getRedeclContext();
6695 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6696 TU->setAnonymousNamespace(Namespc);
6697 } else {
6698 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00006699 }
John McCall4fa53422009-10-01 00:25:31 +00006700
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00006701 CurContext->addDecl(Namespc);
6702
John McCall4fa53422009-10-01 00:25:31 +00006703 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6704 // behaves as if it were replaced by
6705 // namespace unique { /* empty body */ }
6706 // using namespace unique;
6707 // namespace unique { namespace-body }
6708 // where all occurrences of 'unique' in a translation unit are
6709 // replaced by the same identifier and this identifier differs
6710 // from all other identifiers in the entire program.
6711
6712 // We just create the namespace with an empty name and then add an
6713 // implicit using declaration, just like the standard suggests.
6714 //
6715 // CodeGen enforces the "universally unique" aspect by giving all
6716 // declarations semantically contained within an anonymous
6717 // namespace internal linkage.
6718
Douglas Gregore57e7522012-01-07 09:11:48 +00006719 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00006720 UsingDirectiveDecl* UD
Nick Lewycky38115822012-11-04 20:21:54 +00006721 = UsingDirectiveDecl::Create(Context, Parent,
John McCall0db42252009-12-16 02:06:49 +00006722 /* 'using' */ LBrace,
6723 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00006724 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00006725 /* identifier */ SourceLocation(),
6726 Namespc,
Nick Lewycky38115822012-11-04 20:21:54 +00006727 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00006728 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00006729 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00006730 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006731 }
6732
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00006733 ActOnDocumentableDecl(Namespc);
6734
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006735 // Although we could have an invalid decl (i.e. the namespace name is a
6736 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00006737 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6738 // for the namespace has the declarations that showed up in that particular
6739 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00006740 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00006741 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006742}
6743
Sebastian Redla6602e92009-11-23 15:34:23 +00006744/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6745/// is a namespace alias, returns the namespace it points to.
6746static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6747 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6748 return AD->getNamespace();
6749 return dyn_cast_or_null<NamespaceDecl>(D);
6750}
6751
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006752/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6753/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00006754void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006755 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6756 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006757 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006758 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00006759 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006760 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006761}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006762
John McCall28a0cf72010-08-25 07:42:41 +00006763CXXRecordDecl *Sema::getStdBadAlloc() const {
6764 return cast_or_null<CXXRecordDecl>(
6765 StdBadAlloc.get(Context.getExternalSource()));
6766}
6767
6768NamespaceDecl *Sema::getStdNamespace() const {
6769 return cast_or_null<NamespaceDecl>(
6770 StdNamespace.get(Context.getExternalSource()));
6771}
6772
Douglas Gregorcdf87022010-06-29 17:53:46 +00006773/// \brief Retrieve the special "std" namespace, which may require us to
6774/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006775NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00006776 if (!StdNamespace) {
6777 // The "std" namespace has not yet been defined, so build one implicitly.
6778 StdNamespace = NamespaceDecl::Create(Context,
6779 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006780 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006781 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006782 &PP.getIdentifierTable().get("std"),
6783 /*PrevDecl=*/0);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006784 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006785 }
6786
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006787 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006788}
6789
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006790bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006791 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006792 "Looking for std::initializer_list outside of C++.");
6793
6794 // We're looking for implicit instantiations of
6795 // template <typename E> class std::initializer_list.
6796
6797 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6798 return false;
6799
Sebastian Redl43144e72012-01-17 22:49:58 +00006800 ClassTemplateDecl *Template = 0;
6801 const TemplateArgument *Arguments = 0;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006802
Sebastian Redl43144e72012-01-17 22:49:58 +00006803 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006804
Sebastian Redl43144e72012-01-17 22:49:58 +00006805 ClassTemplateSpecializationDecl *Specialization =
6806 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6807 if (!Specialization)
6808 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006809
Sebastian Redl43144e72012-01-17 22:49:58 +00006810 Template = Specialization->getSpecializedTemplate();
6811 Arguments = Specialization->getTemplateArgs().data();
6812 } else if (const TemplateSpecializationType *TST =
6813 Ty->getAs<TemplateSpecializationType>()) {
6814 Template = dyn_cast_or_null<ClassTemplateDecl>(
6815 TST->getTemplateName().getAsTemplateDecl());
6816 Arguments = TST->getArgs();
6817 }
6818 if (!Template)
6819 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006820
6821 if (!StdInitializerList) {
6822 // Haven't recognized std::initializer_list yet, maybe this is it.
6823 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6824 if (TemplateClass->getIdentifier() !=
6825 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00006826 !getStdNamespace()->InEnclosingNamespaceSetOf(
6827 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006828 return false;
6829 // This is a template called std::initializer_list, but is it the right
6830 // template?
6831 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006832 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006833 return false;
6834 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6835 return false;
6836
6837 // It's the right template.
6838 StdInitializerList = Template;
6839 }
6840
6841 if (Template != StdInitializerList)
6842 return false;
6843
6844 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00006845 if (Element)
6846 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006847 return true;
6848}
6849
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006850static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6851 NamespaceDecl *Std = S.getStdNamespace();
6852 if (!Std) {
6853 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6854 return 0;
6855 }
6856
6857 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6858 Loc, Sema::LookupOrdinaryName);
6859 if (!S.LookupQualifiedName(Result, Std)) {
6860 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6861 return 0;
6862 }
6863 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6864 if (!Template) {
6865 Result.suppressDiagnostics();
6866 // We found something weird. Complain about the first thing we found.
6867 NamedDecl *Found = *Result.begin();
6868 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6869 return 0;
6870 }
6871
6872 // We found some template called std::initializer_list. Now verify that it's
6873 // correct.
6874 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006875 if (Params->getMinRequiredArguments() != 1 ||
6876 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006877 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6878 return 0;
6879 }
6880
6881 return Template;
6882}
6883
6884QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6885 if (!StdInitializerList) {
6886 StdInitializerList = LookupStdInitializerList(*this, Loc);
6887 if (!StdInitializerList)
6888 return QualType();
6889 }
6890
6891 TemplateArgumentListInfo Args(Loc, Loc);
6892 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6893 Context.getTrivialTypeSourceInfo(Element,
6894 Loc)));
6895 return Context.getCanonicalType(
6896 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6897}
6898
Sebastian Redlbe24ec22012-01-17 22:50:14 +00006899bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6900 // C++ [dcl.init.list]p2:
6901 // A constructor is an initializer-list constructor if its first parameter
6902 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6903 // std::initializer_list<E> for some type E, and either there are no other
6904 // parameters or else all other parameters have default arguments.
6905 if (Ctor->getNumParams() < 1 ||
6906 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6907 return false;
6908
6909 QualType ArgType = Ctor->getParamDecl(0)->getType();
6910 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6911 ArgType = RT->getPointeeType().getUnqualifiedType();
6912
6913 return isStdInitializerList(ArgType, 0);
6914}
6915
Douglas Gregora172e082011-03-26 22:25:30 +00006916/// \brief Determine whether a using statement is in a context where it will be
6917/// apply in all contexts.
6918static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6919 switch (CurContext->getDeclKind()) {
6920 case Decl::TranslationUnit:
6921 return true;
6922 case Decl::LinkageSpec:
6923 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6924 default:
6925 return false;
6926 }
6927}
6928
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006929namespace {
6930
6931// Callback to only accept typo corrections that are namespaces.
6932class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00006933public:
Craig Toppera798a9d2014-03-02 09:32:10 +00006934 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00006935 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006936 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006937 return false;
6938 }
6939};
6940
6941}
6942
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006943static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6944 CXXScopeSpec &SS,
6945 SourceLocation IdentLoc,
6946 IdentifierInfo *Ident) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006947 NamespaceValidatorCCC Validator;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006948 R.clear();
6949 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006950 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00006951 Validator)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006952 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00006953 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6954 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006955 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00006956 S.diagnoseTypo(Corrected,
6957 S.PDiag(diag::err_using_directive_member_suggest)
6958 << Ident << DC << DroppedSpecifier << SS.getRange(),
6959 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006960 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00006961 S.diagnoseTypo(Corrected,
6962 S.PDiag(diag::err_using_directive_suggest) << Ident,
6963 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006964 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006965 R.addDecl(Corrected.getCorrectionDecl());
6966 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006967 }
6968 return false;
6969}
6970
John McCall48871652010-08-21 09:40:31 +00006971Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00006972 SourceLocation UsingLoc,
6973 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00006974 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00006975 SourceLocation IdentLoc,
6976 IdentifierInfo *NamespcName,
6977 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00006978 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6979 assert(NamespcName && "Invalid NamespcName.");
6980 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00006981
6982 // This can only happen along a recovery path.
6983 while (S->getFlags() & Scope::TemplateParamScope)
6984 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00006985 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00006986
Douglas Gregor889ceb72009-02-03 19:21:40 +00006987 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00006988 NestedNameSpecifier *Qualifier = 0;
6989 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00006990 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006991
Douglas Gregor34074322009-01-14 22:20:51 +00006992 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00006993 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6994 LookupParsedName(R, S, &SS);
6995 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00006996 return 0;
John McCall27b18f82009-11-17 02:14:36 +00006997
Douglas Gregorcdf87022010-06-29 17:53:46 +00006998 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006999 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007000 // Allow "using namespace std;" or "using namespace ::std;" even if
7001 // "std" hasn't been defined yet, for GCC compatibility.
7002 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7003 NamespcName->isStr("std")) {
7004 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007005 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00007006 R.resolveKind();
7007 }
7008 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007009 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007010 }
7011
John McCall9f3059a2009-10-09 21:13:30 +00007012 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00007013 NamedDecl *Named = R.getFoundDecl();
7014 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7015 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00007016 // C++ [namespace.udir]p1:
7017 // A using-directive specifies that the names in the nominated
7018 // namespace can be used in the scope in which the
7019 // using-directive appears after the using-directive. During
7020 // unqualified name lookup (3.4.1), the names appear as if they
7021 // were declared in the nearest enclosing namespace which
7022 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00007023 // namespace. [Note: in this context, "contains" means "contains
7024 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00007025
7026 // Find enclosing context containing both using-directive and
7027 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00007028 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007029 DeclContext *CommonAncestor = cast<DeclContext>(NS);
7030 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7031 CommonAncestor = CommonAncestor->getParent();
7032
Sebastian Redla6602e92009-11-23 15:34:23 +00007033 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00007034 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00007035 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007036
Douglas Gregora172e082011-03-26 22:25:30 +00007037 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00007038 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007039 Diag(IdentLoc, diag::warn_using_directive_in_header);
7040 }
7041
Douglas Gregor889ceb72009-02-03 19:21:40 +00007042 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007043 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00007044 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00007045 }
7046
Richard Smith54ecd982013-02-20 19:22:51 +00007047 if (UDir)
7048 ProcessDeclAttributeList(S, UDir, AttrList);
7049
John McCall48871652010-08-21 09:40:31 +00007050 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00007051}
7052
7053void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00007054 // If the scope has an associated entity and the using directive is at
7055 // namespace or translation unit scope, add the UsingDirectiveDecl into
7056 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007057 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00007058 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007059 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007060 else
Richard Smith05afe5e2012-03-13 03:12:56 +00007061 // Otherwise, it is at block sope. The using-directives will affect lookup
7062 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00007063 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007064}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007065
Douglas Gregorfec52632009-06-20 00:51:54 +00007066
John McCall48871652010-08-21 09:40:31 +00007067Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00007068 AccessSpecifier AS,
7069 bool HasUsingKeyword,
7070 SourceLocation UsingLoc,
7071 CXXScopeSpec &SS,
7072 UnqualifiedId &Name,
7073 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007074 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00007075 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00007076 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00007077
Douglas Gregor220f4272009-11-04 16:30:06 +00007078 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00007079 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00007080 case UnqualifiedId::IK_Identifier:
7081 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00007082 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00007083 case UnqualifiedId::IK_ConversionFunctionId:
7084 break;
7085
7086 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00007087 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00007088 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007089 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007090 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00007091 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00007092 diag::err_using_decl_constructor)
7093 << SS.getRange();
7094
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007095 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00007096
John McCall48871652010-08-21 09:40:31 +00007097 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007098
7099 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007100 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00007101 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00007102 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007103
7104 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007105 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00007106 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00007107 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007108 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007109
7110 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7111 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00007112 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00007113 return 0;
John McCall3969e302009-12-08 07:46:18 +00007114
Richard Smithc2bc61b2013-03-18 21:12:30 +00007115 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00007116 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00007117 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00007118 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7119 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00007120 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00007121 }
7122
Douglas Gregorc4356532010-12-16 00:46:58 +00007123 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7124 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7125 return 0;
7126
John McCall3f746822009-11-17 05:59:44 +00007127 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007128 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007129 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007130 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00007131 if (UD)
7132 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00007133
John McCall48871652010-08-21 09:40:31 +00007134 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00007135}
7136
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007137/// \brief Determine whether a using declaration considers the given
7138/// declarations as "equivalent", e.g., if they are redeclarations of
7139/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00007140static bool
7141IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7142 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007143 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007144
Richard Smithdda56e42011-04-15 14:24:37 +00007145 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00007146 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007147 return Context.hasSameType(TD1->getUnderlyingType(),
7148 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007149
7150 return false;
7151}
7152
7153
John McCall84d87672009-12-10 09:41:52 +00007154/// Determines whether to create a using shadow decl for a particular
7155/// decl, given the set of decls existing prior to this using lookup.
7156bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00007157 const LookupResult &Previous,
7158 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00007159 // Diagnose finding a decl which is not from a base class of the
7160 // current class. We do this now because there are cases where this
7161 // function will silently decide not to build a shadow decl, which
7162 // will pre-empt further diagnostics.
7163 //
7164 // We don't need to do this in C++0x because we do the check once on
7165 // the qualifier.
7166 //
7167 // FIXME: diagnose the following if we care enough:
7168 // struct A { int foo; };
7169 // struct B : A { using A::foo; };
7170 // template <class T> struct C : A {};
7171 // template <class T> struct D : C<T> { using B::foo; } // <---
7172 // This is invalid (during instantiation) in C++03 because B::foo
7173 // resolves to the using decl in B, which is not a base class of D<T>.
7174 // We can't diagnose it immediately because C<T> is an unknown
7175 // specialization. The UsingShadowDecl in D<T> then points directly
7176 // to A::foo, which will look well-formed when we instantiate.
7177 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007178 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00007179 DeclContext *OrigDC = Orig->getDeclContext();
7180
7181 // Handle enums and anonymous structs.
7182 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7183 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7184 while (OrigRec->isAnonymousStructOrUnion())
7185 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7186
7187 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7188 if (OrigDC == CurContext) {
7189 Diag(Using->getLocation(),
7190 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007191 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007192 Diag(Orig->getLocation(), diag::note_using_decl_target);
7193 return true;
7194 }
7195
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007196 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00007197 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007198 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00007199 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007200 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007201 Diag(Orig->getLocation(), diag::note_using_decl_target);
7202 return true;
7203 }
7204 }
7205
7206 if (Previous.empty()) return false;
7207
7208 NamedDecl *Target = Orig;
7209 if (isa<UsingShadowDecl>(Target))
7210 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7211
John McCalla17e83e2009-12-11 02:33:26 +00007212 // If the target happens to be one of the previous declarations, we
7213 // don't have a conflict.
7214 //
7215 // FIXME: but we might be increasing its access, in which case we
7216 // should redeclare it.
7217 NamedDecl *NonTag = 0, *Tag = 0;
Richard Smithfd8634a2013-10-23 02:17:46 +00007218 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00007219 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7220 I != E; ++I) {
7221 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007222 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7223 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7224 PrevShadow = Shadow;
7225 FoundEquivalentDecl = true;
7226 }
John McCalla17e83e2009-12-11 02:33:26 +00007227
7228 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7229 }
7230
Richard Smithfd8634a2013-10-23 02:17:46 +00007231 if (FoundEquivalentDecl)
7232 return false;
7233
Alp Tokera2794f92014-01-22 07:29:52 +00007234 if (FunctionDecl *FD = Target->getAsFunction()) {
John McCall84d87672009-12-10 09:41:52 +00007235 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00007236 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00007237 case Ovl_Overload:
7238 return false;
7239
7240 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00007241 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007242 break;
Richard Smith18819302014-02-06 01:31:33 +00007243
John McCall84d87672009-12-10 09:41:52 +00007244 // We found a decl with the exact signature.
7245 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007246 // If we're in a record, we want to hide the target, so we
7247 // return true (without a diagnostic) to tell the caller not to
7248 // build a shadow decl.
7249 if (CurContext->isRecord())
7250 return true;
7251
7252 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00007253 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007254 break;
7255 }
7256
7257 Diag(Target->getLocation(), diag::note_using_decl_target);
7258 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7259 return true;
7260 }
7261
7262 // Target is not a function.
7263
John McCall84d87672009-12-10 09:41:52 +00007264 if (isa<TagDecl>(Target)) {
7265 // No conflict between a tag and a non-tag.
7266 if (!Tag) return false;
7267
John McCalle29c5cd2009-12-10 19:51:03 +00007268 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007269 Diag(Target->getLocation(), diag::note_using_decl_target);
7270 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7271 return true;
7272 }
7273
7274 // No conflict between a tag and a non-tag.
7275 if (!NonTag) return false;
7276
John McCalle29c5cd2009-12-10 19:51:03 +00007277 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007278 Diag(Target->getLocation(), diag::note_using_decl_target);
7279 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7280 return true;
7281}
7282
John McCall3f746822009-11-17 05:59:44 +00007283/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00007284UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00007285 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00007286 NamedDecl *Orig,
7287 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00007288
7289 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00007290 NamedDecl *Target = Orig;
7291 if (isa<UsingShadowDecl>(Target)) {
7292 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7293 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00007294 }
Richard Smithfd8634a2013-10-23 02:17:46 +00007295
John McCall3f746822009-11-17 05:59:44 +00007296 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00007297 = UsingShadowDecl::Create(Context, CurContext,
7298 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00007299 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00007300
Douglas Gregor457104e2010-09-29 04:25:11 +00007301 Shadow->setAccess(UD->getAccess());
7302 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7303 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007304
7305 Shadow->setPreviousDecl(PrevDecl);
7306
John McCall3f746822009-11-17 05:59:44 +00007307 if (S)
John McCall3969e302009-12-08 07:46:18 +00007308 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00007309 else
John McCall3969e302009-12-08 07:46:18 +00007310 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00007311
John McCall3969e302009-12-08 07:46:18 +00007312
John McCall84d87672009-12-10 09:41:52 +00007313 return Shadow;
7314}
John McCall3969e302009-12-08 07:46:18 +00007315
John McCall84d87672009-12-10 09:41:52 +00007316/// Hides a using shadow declaration. This is required by the current
7317/// using-decl implementation when a resolvable using declaration in a
7318/// class is followed by a declaration which would hide or override
7319/// one or more of the using decl's targets; for example:
7320///
7321/// struct Base { void foo(int); };
7322/// struct Derived : Base {
7323/// using Base::foo;
7324/// void foo(int);
7325/// };
7326///
7327/// The governing language is C++03 [namespace.udecl]p12:
7328///
7329/// When a using-declaration brings names from a base class into a
7330/// derived class scope, member functions in the derived class
7331/// override and/or hide member functions with the same name and
7332/// parameter types in a base class (rather than conflicting).
7333///
7334/// There are two ways to implement this:
7335/// (1) optimistically create shadow decls when they're not hidden
7336/// by existing declarations, or
7337/// (2) don't create any shadow decls (or at least don't make them
7338/// visible) until we've fully parsed/instantiated the class.
7339/// The problem with (1) is that we might have to retroactively remove
7340/// a shadow decl, which requires several O(n) operations because the
7341/// decl structures are (very reasonably) not designed for removal.
7342/// (2) avoids this but is very fiddly and phase-dependent.
7343void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00007344 if (Shadow->getDeclName().getNameKind() ==
7345 DeclarationName::CXXConversionFunctionName)
7346 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7347
John McCall84d87672009-12-10 09:41:52 +00007348 // Remove it from the DeclContext...
7349 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007350
John McCall84d87672009-12-10 09:41:52 +00007351 // ...and the scope, if applicable...
7352 if (S) {
John McCall48871652010-08-21 09:40:31 +00007353 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00007354 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007355 }
7356
John McCall84d87672009-12-10 09:41:52 +00007357 // ...and the using decl.
7358 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7359
7360 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00007361 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00007362}
7363
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007364namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007365class UsingValidatorCCC : public CorrectionCandidateCallback {
7366public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007367 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7368 bool RequireMember)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007369 : HasTypenameKeyword(HasTypenameKeyword),
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007370 IsInstantiation(IsInstantiation), RequireMember(RequireMember) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007371
Craig Toppera798a9d2014-03-02 09:32:10 +00007372 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007373 NamedDecl *ND = Candidate.getCorrectionDecl();
7374
7375 // Keywords are not valid here.
7376 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007377 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007378
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007379 if (RequireMember && !isa<FieldDecl>(ND) && !isa<CXXMethodDecl>(ND) &&
7380 !isa<TypeDecl>(ND))
7381 return false;
7382
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007383 // Completely unqualified names are invalid for a 'using' declaration.
7384 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7385 return false;
7386
7387 if (isa<TypeDecl>(ND))
7388 return HasTypenameKeyword || !IsInstantiation;
7389
7390 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007391 }
7392
7393private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007394 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007395 bool IsInstantiation;
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007396 bool RequireMember;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007397};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007398} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007399
John McCalle61f2ba2009-11-18 02:36:19 +00007400/// Builds a using declaration.
7401///
7402/// \param IsInstantiation - Whether this call arises from an
7403/// instantiation of an unresolved using declaration. We treat
7404/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00007405NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7406 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007407 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007408 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00007409 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007410 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007411 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00007412 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00007413 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007414 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00007415 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00007416
Anders Carlssonf038fc22009-08-28 05:49:21 +00007417 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00007418
Anders Carlsson59140b32009-08-28 03:16:11 +00007419 if (SS.isEmpty()) {
7420 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00007421 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00007422 }
Mike Stump11289f42009-09-09 15:08:12 +00007423
John McCall84d87672009-12-10 09:41:52 +00007424 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007425 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00007426 ForRedeclaration);
7427 Previous.setHideTags(false);
7428 if (S) {
7429 LookupName(Previous, S);
7430
7431 // It is really dumb that we have to do this.
7432 LookupResult::Filter F = Previous.makeFilter();
7433 while (F.hasNext()) {
7434 NamedDecl *D = F.next();
7435 if (!isDeclInScope(D, CurContext, S))
7436 F.erase();
7437 }
7438 F.done();
7439 } else {
7440 assert(IsInstantiation && "no scope in non-instantiation");
7441 assert(CurContext->isRecord() && "scope not record in instantiation");
7442 LookupQualifiedName(Previous, CurContext);
7443 }
7444
John McCall84d87672009-12-10 09:41:52 +00007445 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007446 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7447 SS, IdentLoc, Previous))
John McCall84d87672009-12-10 09:41:52 +00007448 return 0;
7449
7450 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00007451 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7452 return 0;
7453
John McCall84c16cf2009-11-12 03:15:40 +00007454 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007455 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007456 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00007457 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007458 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00007459 // FIXME: not all declaration name kinds are legal here
7460 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7461 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007462 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007463 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00007464 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007465 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7466 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00007467 }
John McCallb96ec562009-12-04 22:46:56 +00007468 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007469 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007470 NameInfo, HasTypenameKeyword);
Anders Carlssonf038fc22009-08-28 05:49:21 +00007471 }
John McCallb96ec562009-12-04 22:46:56 +00007472 D->setAccess(AS);
7473 CurContext->addDecl(D);
7474
7475 if (!LookupContext) return D;
7476 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00007477
John McCall0b66eb32010-05-01 00:40:08 +00007478 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00007479 UD->setInvalidDecl();
7480 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00007481 }
7482
Richard Smith23d55872012-04-02 01:30:27 +00007483 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redl08905022011-02-05 19:23:19 +00007484 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smith23d55872012-04-02 01:30:27 +00007485 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlc1f8e492011-03-12 13:44:32 +00007486 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00007487 return UD;
7488 }
7489
7490 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00007491
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007492 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00007493
John McCall3969e302009-12-08 07:46:18 +00007494 // Unlike most lookups, we don't always want to hide tag
7495 // declarations: tag names are visible through the using declaration
7496 // even if hidden by ordinary names, *except* in a dependent context
7497 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00007498 if (!IsInstantiation)
7499 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00007500
John McCall5dadb652012-04-07 03:04:20 +00007501 // For the purposes of this lookup, we have a base object type
7502 // equal to that of the current context.
7503 if (CurContext->isRecord()) {
7504 R.setBaseObjectType(
7505 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7506 }
7507
John McCall27b18f82009-11-17 02:14:36 +00007508 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00007509
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007510 // Try to correct typos if possible.
John McCall9f3059a2009-10-09 21:13:30 +00007511 if (R.empty()) {
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007512 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation,
7513 CurContext->isRecord());
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007514 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7515 R.getLookupKind(), S, &SS, CCC)){
7516 // We reject any correction for which ND would be NULL.
7517 NamedDecl *ND = Corrected.getCorrectionDecl();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007518 R.setLookupName(Corrected.getCorrection());
7519 R.addDecl(ND);
Richard Smithf9b15102013-08-17 00:46:16 +00007520 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007521 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00007522 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7523 << NameInfo.getName() << LookupContext << 0
7524 << SS.getRange());
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007525 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007526 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007527 << NameInfo.getName() << LookupContext << SS.getRange();
7528 UD->setInvalidDecl();
7529 return UD;
7530 }
Douglas Gregorfec52632009-06-20 00:51:54 +00007531 }
7532
John McCallb96ec562009-12-04 22:46:56 +00007533 if (R.isAmbiguous()) {
7534 UD->setInvalidDecl();
7535 return UD;
7536 }
Mike Stump11289f42009-09-09 15:08:12 +00007537
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007538 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00007539 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00007540 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007541 Diag(IdentLoc, diag::err_using_typename_non_type);
7542 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7543 Diag((*I)->getUnderlyingDecl()->getLocation(),
7544 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00007545 UD->setInvalidDecl();
7546 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00007547 }
7548 } else {
7549 // If we asked for a non-typename and we got a type, error out,
7550 // but only if this is an instantiation of an unresolved using
7551 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00007552 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007553 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7554 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00007555 UD->setInvalidDecl();
7556 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00007557 }
Anders Carlsson59140b32009-08-28 03:16:11 +00007558 }
7559
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007560 // C++0x N2914 [namespace.udecl]p6:
7561 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00007562 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007563 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7564 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00007565 UD->setInvalidDecl();
7566 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007567 }
Mike Stump11289f42009-09-09 15:08:12 +00007568
John McCall84d87672009-12-10 09:41:52 +00007569 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithfd8634a2013-10-23 02:17:46 +00007570 UsingShadowDecl *PrevDecl = 0;
7571 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7572 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00007573 }
John McCall3f746822009-11-17 05:59:44 +00007574
7575 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00007576}
7577
Sebastian Redl08905022011-02-05 19:23:19 +00007578/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00007579bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007580 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00007581
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007582 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00007583 assert(SourceType &&
7584 "Using decl naming constructor doesn't have type in scope spec.");
7585 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7586
7587 // Check whether the named type is a direct base class.
7588 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7589 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7590 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7591 BaseIt != BaseE; ++BaseIt) {
7592 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7593 if (CanonicalSourceType == BaseType)
7594 break;
Richard Smith23d55872012-04-02 01:30:27 +00007595 if (BaseIt->getType()->isDependentType())
7596 break;
Sebastian Redl08905022011-02-05 19:23:19 +00007597 }
7598
7599 if (BaseIt == BaseE) {
7600 // Did not find SourceType in the bases.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007601 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00007602 diag::err_using_decl_constructor_not_in_direct_base)
7603 << UD->getNameInfo().getSourceRange()
7604 << QualType(SourceType, 0) << TargetClass;
7605 return true;
7606 }
7607
Richard Smith23d55872012-04-02 01:30:27 +00007608 if (!CurContext->isDependentContext())
7609 BaseIt->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00007610
7611 return false;
7612}
7613
John McCall84d87672009-12-10 09:41:52 +00007614/// Checks that the given using declaration is not an invalid
7615/// redeclaration. Note that this is checking only for the using decl
7616/// itself, not for any ill-formedness among the UsingShadowDecls.
7617bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007618 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00007619 const CXXScopeSpec &SS,
7620 SourceLocation NameLoc,
7621 const LookupResult &Prev) {
7622 // C++03 [namespace.udecl]p8:
7623 // C++0x [namespace.udecl]p10:
7624 // A using-declaration is a declaration and can therefore be used
7625 // repeatedly where (and only where) multiple declarations are
7626 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00007627 //
John McCall032092f2010-11-29 18:01:58 +00007628 // That's in non-member contexts.
7629 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00007630 return false;
7631
Aaron Ballman4a979672014-01-03 13:56:08 +00007632 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall84d87672009-12-10 09:41:52 +00007633
7634 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7635 NamedDecl *D = *I;
7636
7637 bool DTypename;
7638 NestedNameSpecifier *DQual;
7639 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007640 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007641 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007642 } else if (UnresolvedUsingValueDecl *UD
7643 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7644 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007645 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007646 } else if (UnresolvedUsingTypenameDecl *UD
7647 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7648 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007649 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007650 } else continue;
7651
7652 // using decls differ if one says 'typename' and the other doesn't.
7653 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007654 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00007655
7656 // using decls differ if they name different scopes (but note that
7657 // template instantiation can cause this check to trigger when it
7658 // didn't before instantiation).
7659 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7660 Context.getCanonicalNestedNameSpecifier(DQual))
7661 continue;
7662
7663 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00007664 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00007665 return true;
7666 }
7667
7668 return false;
7669}
7670
John McCall3969e302009-12-08 07:46:18 +00007671
John McCallb96ec562009-12-04 22:46:56 +00007672/// Checks that the given nested-name qualifier used in a using decl
7673/// in the current context is appropriately related to the current
7674/// scope. If an error is found, diagnoses it and returns true.
7675bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7676 const CXXScopeSpec &SS,
7677 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00007678 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007679
John McCall3969e302009-12-08 07:46:18 +00007680 if (!CurContext->isRecord()) {
7681 // C++03 [namespace.udecl]p3:
7682 // C++0x [namespace.udecl]p8:
7683 // A using-declaration for a class member shall be a member-declaration.
7684
7685 // If we weren't able to compute a valid scope, it must be a
7686 // dependent class scope.
7687 if (!NamedContext || NamedContext->isRecord()) {
7688 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7689 << SS.getRange();
7690 return true;
7691 }
7692
7693 // Otherwise, everything is known to be fine.
7694 return false;
7695 }
7696
7697 // The current scope is a record.
7698
7699 // If the named context is dependent, we can't decide much.
7700 if (!NamedContext) {
7701 // FIXME: in C++0x, we can diagnose if we can prove that the
7702 // nested-name-specifier does not refer to a base class, which is
7703 // still possible in some cases.
7704
7705 // Otherwise we have to conservatively report that things might be
7706 // okay.
7707 return false;
7708 }
7709
7710 if (!NamedContext->isRecord()) {
7711 // Ideally this would point at the last name in the specifier,
7712 // but we don't have that level of source info.
7713 Diag(SS.getRange().getBegin(),
7714 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00007715 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00007716 return true;
7717 }
7718
Douglas Gregor7c842292010-12-21 07:41:49 +00007719 if (!NamedContext->isDependentContext() &&
7720 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7721 return true;
7722
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007723 if (getLangOpts().CPlusPlus11) {
John McCall3969e302009-12-08 07:46:18 +00007724 // C++0x [namespace.udecl]p3:
7725 // In a using-declaration used as a member-declaration, the
7726 // nested-name-specifier shall name a base class of the class
7727 // being defined.
7728
7729 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7730 cast<CXXRecordDecl>(NamedContext))) {
7731 if (CurContext == NamedContext) {
7732 Diag(NameLoc,
7733 diag::err_using_decl_nested_name_specifier_is_current_class)
7734 << SS.getRange();
7735 return true;
7736 }
7737
7738 Diag(SS.getRange().getBegin(),
7739 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00007740 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00007741 << cast<CXXRecordDecl>(CurContext)
7742 << SS.getRange();
7743 return true;
7744 }
7745
7746 return false;
7747 }
7748
7749 // C++03 [namespace.udecl]p4:
7750 // A using-declaration used as a member-declaration shall refer
7751 // to a member of a base class of the class being defined [etc.].
7752
7753 // Salient point: SS doesn't have to name a base class as long as
7754 // lookup only finds members from base classes. Therefore we can
7755 // diagnose here only if we can prove that that can't happen,
7756 // i.e. if the class hierarchies provably don't intersect.
7757
7758 // TODO: it would be nice if "definitely valid" results were cached
7759 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7760 // need to be repeated.
7761
7762 struct UserData {
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00007763 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall3969e302009-12-08 07:46:18 +00007764
7765 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7766 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7767 Data->Bases.insert(Base);
7768 return true;
7769 }
7770
7771 bool hasDependentBases(const CXXRecordDecl *Class) {
7772 return !Class->forallBases(collect, this);
7773 }
7774
7775 /// Returns true if the base is dependent or is one of the
7776 /// accumulated base classes.
7777 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7778 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7779 return !Data->Bases.count(Base);
7780 }
7781
7782 bool mightShareBases(const CXXRecordDecl *Class) {
7783 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7784 }
7785 };
7786
7787 UserData Data;
7788
7789 // Returns false if we find a dependent base.
7790 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7791 return false;
7792
7793 // Returns false if the class has a dependent base or if it or one
7794 // of its bases is present in the base set of the current context.
7795 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7796 return false;
7797
7798 Diag(SS.getRange().getBegin(),
7799 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00007800 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00007801 << cast<CXXRecordDecl>(CurContext)
7802 << SS.getRange();
7803
7804 return true;
John McCallb96ec562009-12-04 22:46:56 +00007805}
7806
Richard Smithdda56e42011-04-15 14:24:37 +00007807Decl *Sema::ActOnAliasDeclaration(Scope *S,
7808 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00007809 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00007810 SourceLocation UsingLoc,
7811 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00007812 AttributeList *AttrList,
Richard Smithdda56e42011-04-15 14:24:37 +00007813 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00007814 // Skip up to the relevant declaration scope.
7815 while (S->getFlags() & Scope::TemplateParamScope)
7816 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00007817 assert((S->getFlags() & Scope::DeclScope) &&
7818 "got alias-declaration outside of declaration scope");
7819
7820 if (Type.isInvalid())
7821 return 0;
7822
7823 bool Invalid = false;
7824 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7825 TypeSourceInfo *TInfo = 0;
Nick Lewycky82e47802011-05-02 01:07:19 +00007826 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00007827
7828 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7829 return 0;
7830
7831 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00007832 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00007833 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00007834 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7835 TInfo->getTypeLoc().getBeginLoc());
7836 }
Richard Smithdda56e42011-04-15 14:24:37 +00007837
7838 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7839 LookupName(Previous, S);
7840
7841 // Warn about shadowing the name of a template parameter.
7842 if (Previous.isSingleResult() &&
7843 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00007844 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00007845 Previous.clear();
7846 }
7847
7848 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7849 "name in alias declaration must be an identifier");
7850 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7851 Name.StartLocation,
7852 Name.Identifier, TInfo);
7853
7854 NewTD->setAccess(AS);
7855
7856 if (Invalid)
7857 NewTD->setInvalidDecl();
7858
Richard Smith54ecd982013-02-20 19:22:51 +00007859 ProcessDeclAttributeList(S, NewTD, AttrList);
7860
Richard Smith3f1b5d02011-05-05 21:57:07 +00007861 CheckTypedefForVariablyModifiedType(S, NewTD);
7862 Invalid |= NewTD->isInvalidDecl();
7863
Richard Smithdda56e42011-04-15 14:24:37 +00007864 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00007865
7866 NamedDecl *NewND;
7867 if (TemplateParamLists.size()) {
7868 TypeAliasTemplateDecl *OldDecl = 0;
7869 TemplateParameterList *OldTemplateParams = 0;
7870
7871 if (TemplateParamLists.size() != 1) {
7872 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007873 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7874 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00007875 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007876 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00007877
7878 // Only consider previous declarations in the same scope.
7879 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7880 /*ExplicitInstantiationOrSpecialization*/false);
7881 if (!Previous.empty()) {
7882 Redeclaration = true;
7883
7884 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7885 if (!OldDecl && !Invalid) {
7886 Diag(UsingLoc, diag::err_redefinition_different_kind)
7887 << Name.Identifier;
7888
7889 NamedDecl *OldD = Previous.getRepresentativeDecl();
7890 if (OldD->getLocation().isValid())
7891 Diag(OldD->getLocation(), diag::note_previous_definition);
7892
7893 Invalid = true;
7894 }
7895
7896 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7897 if (TemplateParameterListsAreEqual(TemplateParams,
7898 OldDecl->getTemplateParameters(),
7899 /*Complain=*/true,
7900 TPL_TemplateMatch))
7901 OldTemplateParams = OldDecl->getTemplateParameters();
7902 else
7903 Invalid = true;
7904
7905 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7906 if (!Invalid &&
7907 !Context.hasSameType(OldTD->getUnderlyingType(),
7908 NewTD->getUnderlyingType())) {
7909 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7910 // but we can't reasonably accept it.
7911 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7912 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7913 if (OldTD->getLocation().isValid())
7914 Diag(OldTD->getLocation(), diag::note_previous_definition);
7915 Invalid = true;
7916 }
7917 }
7918 }
7919
7920 // Merge any previous default template arguments into our parameters,
7921 // and check the parameter list.
7922 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7923 TPC_TypeAliasTemplate))
7924 return 0;
7925
7926 TypeAliasTemplateDecl *NewDecl =
7927 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7928 Name.Identifier, TemplateParams,
7929 NewTD);
7930
7931 NewDecl->setAccess(AS);
7932
7933 if (Invalid)
7934 NewDecl->setInvalidDecl();
7935 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00007936 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00007937
7938 NewND = NewDecl;
7939 } else {
7940 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7941 NewND = NewTD;
7942 }
Richard Smithdda56e42011-04-15 14:24:37 +00007943
7944 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00007945 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00007946
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00007947 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00007948 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00007949}
7950
John McCall48871652010-08-21 09:40:31 +00007951Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00007952 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00007953 SourceLocation AliasLoc,
7954 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007955 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00007956 SourceLocation IdentLoc,
7957 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00007958
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007959 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00007960 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7961 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007962
Anders Carlssondca83c42009-03-28 06:23:46 +00007963 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00007964 NamedDecl *PrevDecl
7965 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7966 ForRedeclaration);
7967 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7968 PrevDecl = 0;
7969
7970 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007971 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00007972 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007973 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00007974 // FIXME: At some point, we'll want to create the (redundant)
7975 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00007976 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00007977 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00007978 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007979 }
Mike Stump11289f42009-09-09 15:08:12 +00007980
Anders Carlssondca83c42009-03-28 06:23:46 +00007981 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7982 diag::err_redefinition_different_kind;
7983 Diag(AliasLoc, DiagID) << Alias;
7984 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00007985 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00007986 }
7987
John McCall27b18f82009-11-17 02:14:36 +00007988 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00007989 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00007990
John McCall9f3059a2009-10-09 21:13:30 +00007991 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007992 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00007993 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00007994 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00007995 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00007996 }
Mike Stump11289f42009-09-09 15:08:12 +00007997
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00007998 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00007999 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00008000 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00008001 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00008002
John McCalld8d0d432010-02-16 06:53:13 +00008003 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00008004 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00008005}
8006
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008007Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008008Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8009 CXXMethodDecl *MD) {
8010 CXXRecordDecl *ClassDecl = MD->getParent();
8011
Douglas Gregor6d880b12010-07-01 22:31:05 +00008012 // C++ [except.spec]p14:
8013 // An implicitly declared special member function (Clause 12) shall have an
8014 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00008015 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008016 if (ClassDecl->isInvalidDecl())
8017 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00008018
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008019 // Direct base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00008020 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8021 BEnd = ClassDecl->bases_end();
8022 B != BEnd; ++B) {
8023 if (B->isVirtual()) // Handled below.
8024 continue;
8025
Douglas Gregor9672f922010-07-03 00:47:00 +00008026 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8027 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008028 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8029 // If this is a deleted function, add it anyway. This might be conformant
8030 // with the standard. This might not. I'm not sure. It might not matter.
8031 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008032 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008033 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008034 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008035
8036 // Virtual base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00008037 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8038 BEnd = ClassDecl->vbases_end();
8039 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008040 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8041 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008042 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8043 // If this is a deleted function, add it anyway. This might be conformant
8044 // with the standard. This might not. I'm not sure. It might not matter.
8045 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008046 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008047 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008048 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008049
8050 // Field constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00008051 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8052 FEnd = ClassDecl->field_end();
8053 F != FEnd; ++F) {
Richard Smith938f40b2011-06-11 17:19:42 +00008054 if (F->hasInClassInitializer()) {
8055 if (Expr *E = F->getInClassInitializer())
8056 ExceptSpec.CalledExpr(E);
8057 else if (!F->isInvalidDecl())
Richard Smithd3b5c9082012-07-27 04:22:15 +00008058 // DR1351:
8059 // If the brace-or-equal-initializer of a non-static data member
8060 // invokes a defaulted default constructor of its class or of an
8061 // enclosing class in a potentially evaluated subexpression, the
8062 // program is ill-formed.
8063 //
8064 // This resolution is unworkable: the exception specification of the
8065 // default constructor can be needed in an unevaluated context, in
8066 // particular, in the operand of a noexcept-expression, and we can be
8067 // unable to compute an exception specification for an enclosed class.
8068 //
8069 // We do not allow an in-class initializer to require the evaluation
8070 // of the exception specification for any in-class initializer whose
8071 // definition is not lexically complete.
8072 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith938f40b2011-06-11 17:19:42 +00008073 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00008074 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00008075 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8076 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8077 // If this is a deleted function, add it anyway. This might be conformant
8078 // with the standard. This might not. I'm not sure. It might not matter.
8079 // In particular, the problem is that this function never gets called. It
8080 // might just be ill-formed because this function attempts to refer to
8081 // a deleted function here.
8082 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008083 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008084 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008085 }
John McCalldb40c7f2010-12-14 08:05:40 +00008086
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008087 return ExceptSpec;
8088}
8089
Richard Smithc2bc61b2013-03-18 21:12:30 +00008090Sema::ImplicitExceptionSpecification
Richard Smithb7151b92013-04-10 06:11:48 +00008091Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8092 CXXRecordDecl *ClassDecl = CD->getParent();
8093
8094 // C++ [except.spec]p14:
8095 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00008096 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00008097 if (ClassDecl->isInvalidDecl())
8098 return ExceptSpec;
8099
8100 // Inherited constructor.
8101 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8102 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8103 // FIXME: Copying or moving the parameters could add extra exceptions to the
8104 // set, as could the default arguments for the inherited constructor. This
8105 // will be addressed when we implement the resolution of core issue 1351.
8106 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8107
8108 // Direct base-class constructors.
8109 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8110 BEnd = ClassDecl->bases_end();
8111 B != BEnd; ++B) {
8112 if (B->isVirtual()) // Handled below.
8113 continue;
8114
8115 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8116 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8117 if (BaseClassDecl == InheritedDecl)
8118 continue;
8119 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8120 if (Constructor)
8121 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8122 }
8123 }
8124
8125 // Virtual base-class constructors.
8126 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8127 BEnd = ClassDecl->vbases_end();
8128 B != BEnd; ++B) {
8129 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8130 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8131 if (BaseClassDecl == InheritedDecl)
8132 continue;
8133 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8134 if (Constructor)
8135 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8136 }
8137 }
8138
8139 // Field constructors.
8140 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8141 FEnd = ClassDecl->field_end();
8142 F != FEnd; ++F) {
8143 if (F->hasInClassInitializer()) {
8144 if (Expr *E = F->getInClassInitializer())
8145 ExceptSpec.CalledExpr(E);
8146 else if (!F->isInvalidDecl())
8147 Diag(CD->getLocation(),
8148 diag::err_in_class_initializer_references_def_ctor) << CD;
8149 } else if (const RecordType *RecordTy
8150 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8151 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8152 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8153 if (Constructor)
8154 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8155 }
8156 }
8157
Richard Smithc2bc61b2013-03-18 21:12:30 +00008158 return ExceptSpec;
8159}
8160
Richard Smith8bf22e52012-11-29 01:34:07 +00008161namespace {
8162/// RAII object to register a special member as being currently declared.
8163struct DeclaringSpecialMember {
8164 Sema &S;
8165 Sema::SpecialMemberDecl D;
8166 bool WasAlreadyBeingDeclared;
8167
8168 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8169 : S(S), D(RD, CSM) {
8170 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8171 if (WasAlreadyBeingDeclared)
8172 // This almost never happens, but if it does, ensure that our cache
8173 // doesn't contain a stale result.
8174 S.SpecialMemberCache.clear();
8175
8176 // FIXME: Register a note to be produced if we encounter an error while
8177 // declaring the special member.
8178 }
8179 ~DeclaringSpecialMember() {
8180 if (!WasAlreadyBeingDeclared)
8181 S.SpecialMembersBeingDeclared.erase(D);
8182 }
8183
8184 /// \brief Are we already trying to declare this special member?
8185 bool isAlreadyBeingDeclared() const {
8186 return WasAlreadyBeingDeclared;
8187 }
8188};
8189}
8190
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008191CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8192 CXXRecordDecl *ClassDecl) {
8193 // C++ [class.ctor]p5:
8194 // A default constructor for a class X is a constructor of class X
8195 // that can be called without an argument. If there is no
8196 // user-declared constructor for class X, a default constructor is
8197 // implicitly declared. An implicitly-declared default constructor
8198 // is an inline public member of its class.
Richard Smith7d125a12012-11-27 21:20:31 +00008199 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008200 "Should not build implicit default constructor!");
8201
Richard Smith8bf22e52012-11-29 01:34:07 +00008202 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8203 if (DSM.isAlreadyBeingDeclared())
8204 return 0;
8205
Richard Smithb5800092012-06-10 05:43:50 +00008206 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8207 CXXDefaultConstructor,
8208 false);
8209
Douglas Gregor6d880b12010-07-01 22:31:05 +00008210 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008211 CanQualType ClassType
8212 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008213 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008214 DeclarationName Name
8215 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008216 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00008217 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +00008218 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +00008219 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +00008220 Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008221 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00008222 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008223 DefaultCon->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008224
8225 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008226 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008227 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008228
Richard Smith6b02d462012-12-08 08:32:28 +00008229 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8230 // constructors is easy to compute.
8231 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8232
8233 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008234 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008235
Douglas Gregor9672f922010-07-03 00:47:00 +00008236 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00008237 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00008238
Douglas Gregor0be31a22010-07-02 17:43:08 +00008239 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00008240 PushOnScopeChains(DefaultCon, S, false);
8241 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008242
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008243 return DefaultCon;
8244}
8245
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008246void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8247 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008248 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008249 !Constructor->doesThisDeclarationHaveABody() &&
8250 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008251 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008252
Anders Carlsson423f5d82010-04-23 16:04:08 +00008253 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00008254 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00008255
Eli Friedmaneaf34142012-10-18 20:14:08 +00008256 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008257 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00008258 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008259 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008260 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008261 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00008262 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00008263 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00008264 }
Douglas Gregor73193272010-09-20 16:48:21 +00008265
8266 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008267 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +00008268
Eli Friedman276dd182013-09-05 00:02:25 +00008269 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +00008270 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008271
8272 if (ASTMutationListener *L = getASTMutationListener()) {
8273 L->CompletedImplicitDefinition(Constructor);
8274 }
Richard Trieuef64e942013-10-25 00:56:00 +00008275
8276 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008277}
8278
Richard Smith938f40b2011-06-11 17:19:42 +00008279void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008280 // Perform any delayed checks on exception specifications.
8281 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +00008282}
8283
Richard Smith185be182013-04-10 05:48:59 +00008284namespace {
8285/// Information on inheriting constructors to declare.
8286class InheritingConstructorInfo {
8287public:
8288 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8289 : SemaRef(SemaRef), Derived(Derived) {
8290 // Mark the constructors that we already have in the derived class.
8291 //
8292 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8293 // unless there is a user-declared constructor with the same signature in
8294 // the class where the using-declaration appears.
8295 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8296 }
8297
8298 void inheritAll(CXXRecordDecl *RD) {
8299 visitAll(RD, &InheritingConstructorInfo::inherit);
8300 }
8301
8302private:
8303 /// Information about an inheriting constructor.
8304 struct InheritingConstructor {
8305 InheritingConstructor()
8306 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
8307
8308 /// If \c true, a constructor with this signature is already declared
8309 /// in the derived class.
8310 bool DeclaredInDerived;
8311
8312 /// The constructor which is inherited.
8313 const CXXConstructorDecl *BaseCtor;
8314
8315 /// The derived constructor we declared.
8316 CXXConstructorDecl *DerivedCtor;
8317 };
8318
8319 /// Inheriting constructors with a given canonical type. There can be at
8320 /// most one such non-template constructor, and any number of templated
8321 /// constructors.
8322 struct InheritingConstructorsForType {
8323 InheritingConstructor NonTemplate;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008324 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8325 Templates;
Richard Smith185be182013-04-10 05:48:59 +00008326
8327 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8328 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8329 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8330 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8331 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8332 false, S.TPL_TemplateMatch))
8333 return Templates[I].second;
8334 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8335 return Templates.back().second;
Sebastian Redl08905022011-02-05 19:23:19 +00008336 }
Richard Smith185be182013-04-10 05:48:59 +00008337
8338 return NonTemplate;
8339 }
8340 };
8341
8342 /// Get or create the inheriting constructor record for a constructor.
8343 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8344 QualType CtorType) {
8345 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8346 .getEntry(SemaRef, Ctor);
8347 }
8348
8349 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8350
8351 /// Process all constructors for a class.
8352 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8353 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
8354 CtorE = RD->ctor_end();
8355 CtorIt != CtorE; ++CtorIt)
8356 (this->*Callback)(*CtorIt);
8357 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8358 I(RD->decls_begin()), E(RD->decls_end());
8359 I != E; ++I) {
8360 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8361 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8362 (this->*Callback)(CD);
Sebastian Redl08905022011-02-05 19:23:19 +00008363 }
8364 }
Richard Smith185be182013-04-10 05:48:59 +00008365
8366 /// Note that a constructor (or constructor template) was declared in Derived.
8367 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8368 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8369 }
8370
8371 /// Inherit a single constructor.
8372 void inherit(const CXXConstructorDecl *Ctor) {
8373 const FunctionProtoType *CtorType =
8374 Ctor->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00008375 ArrayRef<QualType> ArgTypes(CtorType->getParamTypes());
Richard Smith185be182013-04-10 05:48:59 +00008376 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8377
8378 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8379
8380 // Core issue (no number yet): the ellipsis is always discarded.
8381 if (EPI.Variadic) {
8382 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8383 SemaRef.Diag(Ctor->getLocation(),
8384 diag::note_using_decl_constructor_ellipsis);
8385 EPI.Variadic = false;
8386 }
8387
8388 // Declare a constructor for each number of parameters.
8389 //
8390 // C++11 [class.inhctor]p1:
8391 // The candidate set of inherited constructors from the class X named in
8392 // the using-declaration consists of [... modulo defects ...] for each
8393 // constructor or constructor template of X, the set of constructors or
8394 // constructor templates that results from omitting any ellipsis parameter
8395 // specification and successively omitting parameters with a default
8396 // argument from the end of the parameter-type-list
Richard Smith3c626ed2013-04-17 19:00:52 +00008397 unsigned MinParams = minParamsToInherit(Ctor);
8398 unsigned Params = Ctor->getNumParams();
8399 if (Params >= MinParams) {
8400 do
8401 declareCtor(UsingLoc, Ctor,
8402 SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00008403 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
Richard Smith3c626ed2013-04-17 19:00:52 +00008404 while (Params > MinParams &&
8405 Ctor->getParamDecl(--Params)->hasDefaultArg());
8406 }
Richard Smith185be182013-04-10 05:48:59 +00008407 }
8408
8409 /// Find the using-declaration which specified that we should inherit the
8410 /// constructors of \p Base.
8411 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8412 // No fancy lookup required; just look for the base constructor name
8413 // directly within the derived class.
8414 ASTContext &Context = SemaRef.Context;
8415 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8416 Context.getCanonicalType(Context.getRecordType(Base)));
8417 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8418 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8419 }
8420
8421 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8422 // C++11 [class.inhctor]p3:
8423 // [F]or each constructor template in the candidate set of inherited
8424 // constructors, a constructor template is implicitly declared
8425 if (Ctor->getDescribedFunctionTemplate())
8426 return 0;
8427
8428 // For each non-template constructor in the candidate set of inherited
8429 // constructors other than a constructor having no parameters or a
8430 // copy/move constructor having a single parameter, a constructor is
8431 // implicitly declared [...]
8432 if (Ctor->getNumParams() == 0)
8433 return 1;
8434 if (Ctor->isCopyOrMoveConstructor())
8435 return 2;
8436
8437 // Per discussion on core reflector, never inherit a constructor which
8438 // would become a default, copy, or move constructor of Derived either.
8439 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8440 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8441 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8442 }
8443
8444 /// Declare a single inheriting constructor, inheriting the specified
8445 /// constructor, with the given type.
8446 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8447 QualType DerivedType) {
8448 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8449
8450 // C++11 [class.inhctor]p3:
8451 // ... a constructor is implicitly declared with the same constructor
8452 // characteristics unless there is a user-declared constructor with
8453 // the same signature in the class where the using-declaration appears
8454 if (Entry.DeclaredInDerived)
8455 return;
8456
8457 // C++11 [class.inhctor]p7:
8458 // If two using-declarations declare inheriting constructors with the
8459 // same signature, the program is ill-formed
8460 if (Entry.DerivedCtor) {
8461 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8462 // Only diagnose this once per constructor.
8463 if (Entry.DerivedCtor->isInvalidDecl())
8464 return;
8465 Entry.DerivedCtor->setInvalidDecl();
8466
8467 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8468 SemaRef.Diag(BaseCtor->getLocation(),
8469 diag::note_using_decl_constructor_conflict_current_ctor);
8470 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8471 diag::note_using_decl_constructor_conflict_previous_ctor);
8472 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8473 diag::note_using_decl_constructor_conflict_previous_using);
8474 } else {
8475 // Core issue (no number): if the same inheriting constructor is
8476 // produced by multiple base class constructors from the same base
8477 // class, the inheriting constructor is defined as deleted.
8478 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8479 }
8480
8481 return;
8482 }
8483
8484 ASTContext &Context = SemaRef.Context;
8485 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8486 Context.getCanonicalType(Context.getRecordType(Derived)));
8487 DeclarationNameInfo NameInfo(Name, UsingLoc);
8488
8489 TemplateParameterList *TemplateParams = 0;
8490 if (const FunctionTemplateDecl *FTD =
8491 BaseCtor->getDescribedFunctionTemplate()) {
8492 TemplateParams = FTD->getTemplateParameters();
8493 // We're reusing template parameters from a different DeclContext. This
8494 // is questionable at best, but works out because the template depth in
8495 // both places is guaranteed to be 0.
8496 // FIXME: Rebuild the template parameters in the new context, and
8497 // transform the function type to refer to them.
8498 }
8499
8500 // Build type source info pointing at the using-declaration. This is
8501 // required by template instantiation.
8502 TypeSourceInfo *TInfo =
8503 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8504 FunctionProtoTypeLoc ProtoLoc =
8505 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8506
8507 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8508 Context, Derived, UsingLoc, NameInfo, DerivedType,
8509 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8510 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8511
8512 // Build an unevaluated exception specification for this constructor.
8513 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8514 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8515 EPI.ExceptionSpecType = EST_Unevaluated;
8516 EPI.ExceptionSpecDecl = DerivedCtor;
Alp Toker314cc812014-01-25 16:55:45 +00008517 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00008518 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +00008519
8520 // Build the parameter declarations.
8521 SmallVector<ParmVarDecl *, 16> ParamDecls;
Alp Toker9cacbab2014-01-20 20:26:09 +00008522 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +00008523 TypeSourceInfo *TInfo =
Alp Toker9cacbab2014-01-20 20:26:09 +00008524 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
Richard Smith185be182013-04-10 05:48:59 +00008525 ParmVarDecl *PD = ParmVarDecl::Create(
8526 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
Alp Toker9cacbab2014-01-20 20:26:09 +00008527 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/0);
Richard Smith185be182013-04-10 05:48:59 +00008528 PD->setScopeInfo(0, I);
8529 PD->setImplicit();
8530 ParamDecls.push_back(PD);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00008531 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +00008532 }
8533
8534 // Set up the new constructor.
8535 DerivedCtor->setAccess(BaseCtor->getAccess());
8536 DerivedCtor->setParams(ParamDecls);
8537 DerivedCtor->setInheritedConstructor(BaseCtor);
8538 if (BaseCtor->isDeleted())
8539 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8540
8541 // If this is a constructor template, build the template declaration.
8542 if (TemplateParams) {
8543 FunctionTemplateDecl *DerivedTemplate =
8544 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8545 TemplateParams, DerivedCtor);
8546 DerivedTemplate->setAccess(BaseCtor->getAccess());
8547 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8548 Derived->addDecl(DerivedTemplate);
8549 } else {
8550 Derived->addDecl(DerivedCtor);
8551 }
8552
8553 Entry.BaseCtor = BaseCtor;
8554 Entry.DerivedCtor = DerivedCtor;
8555 }
8556
8557 Sema &SemaRef;
8558 CXXRecordDecl *Derived;
8559 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8560 MapType Map;
8561};
8562}
8563
8564void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8565 // Defer declaring the inheriting constructors until the class is
8566 // instantiated.
8567 if (ClassDecl->isDependentContext())
Sebastian Redl08905022011-02-05 19:23:19 +00008568 return;
8569
Richard Smith185be182013-04-10 05:48:59 +00008570 // Find base classes from which we might inherit constructors.
8571 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8572 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8573 BaseE = ClassDecl->bases_end();
8574 BaseIt != BaseE; ++BaseIt)
8575 if (BaseIt->getInheritConstructors())
8576 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smithc2bc61b2013-03-18 21:12:30 +00008577
Richard Smith185be182013-04-10 05:48:59 +00008578 // Go no further if we're not inheriting any constructors.
8579 if (InheritedBases.empty())
8580 return;
Sebastian Redl08905022011-02-05 19:23:19 +00008581
Richard Smith185be182013-04-10 05:48:59 +00008582 // Declare the inherited constructors.
8583 InheritingConstructorInfo ICI(*this, ClassDecl);
8584 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8585 ICI.inheritAll(InheritedBases[I]);
Sebastian Redl08905022011-02-05 19:23:19 +00008586}
8587
Richard Smithc2bc61b2013-03-18 21:12:30 +00008588void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8589 CXXConstructorDecl *Constructor) {
8590 CXXRecordDecl *ClassDecl = Constructor->getParent();
8591 assert(Constructor->getInheritedConstructor() &&
8592 !Constructor->doesThisDeclarationHaveABody() &&
8593 !Constructor->isDeleted());
8594
8595 SynthesizedFunctionScope Scope(*this, Constructor);
8596 DiagnosticErrorTrap Trap(Diags);
8597 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8598 Trap.hasErrorOccurred()) {
8599 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8600 << Context.getTagDeclType(ClassDecl);
8601 Constructor->setInvalidDecl();
8602 return;
8603 }
8604
8605 SourceLocation Loc = Constructor->getLocation();
8606 Constructor->setBody(new (Context) CompoundStmt(Loc));
8607
Eli Friedman276dd182013-09-05 00:02:25 +00008608 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +00008609 MarkVTableUsed(CurrentLocation, ClassDecl);
8610
8611 if (ASTMutationListener *L = getASTMutationListener()) {
8612 L->CompletedImplicitDefinition(Constructor);
8613 }
8614}
8615
8616
Alexis Huntf91729462011-05-12 22:46:25 +00008617Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008618Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8619 CXXRecordDecl *ClassDecl = MD->getParent();
8620
Douglas Gregorf1203042010-07-01 19:09:28 +00008621 // C++ [except.spec]p14:
8622 // An implicitly declared special member function (Clause 12) shall have
8623 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +00008624 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008625 if (ClassDecl->isInvalidDecl())
8626 return ExceptSpec;
8627
Douglas Gregorf1203042010-07-01 19:09:28 +00008628 // Direct base-class destructors.
8629 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8630 BEnd = ClassDecl->bases_end();
8631 B != BEnd; ++B) {
8632 if (B->isVirtual()) // Handled below.
8633 continue;
8634
8635 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00008636 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008637 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008638 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008639
Douglas Gregorf1203042010-07-01 19:09:28 +00008640 // Virtual base-class destructors.
8641 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8642 BEnd = ClassDecl->vbases_end();
8643 B != BEnd; ++B) {
8644 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00008645 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008646 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008647 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008648
Douglas Gregorf1203042010-07-01 19:09:28 +00008649 // Field destructors.
8650 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8651 FEnd = ClassDecl->field_end();
8652 F != FEnd; ++F) {
8653 if (const RecordType *RecordTy
8654 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00008655 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008656 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008657 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008658
Alexis Huntf91729462011-05-12 22:46:25 +00008659 return ExceptSpec;
8660}
8661
8662CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8663 // C++ [class.dtor]p2:
8664 // If a class has no user-declared destructor, a destructor is
8665 // declared implicitly. An implicitly-declared destructor is an
8666 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +00008667 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +00008668
Richard Smith8bf22e52012-11-29 01:34:07 +00008669 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8670 if (DSM.isAlreadyBeingDeclared())
8671 return 0;
8672
Douglas Gregor7454c562010-07-02 20:37:36 +00008673 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00008674 CanQualType ClassType
8675 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008676 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00008677 DeclarationName Name
8678 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008679 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00008680 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +00008681 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8682 QualType(), 0, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008683 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00008684 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00008685 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00008686 Destructor->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008687
8688 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008689 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008690 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008691
Richard Smith6b02d462012-12-08 08:32:28 +00008692 AddOverriddenMethods(ClassDecl, Destructor);
8693
8694 // We don't need to use SpecialMemberIsTrivial here; triviality for
8695 // destructors is easy to compute.
8696 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8697
8698 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008699 SetDeclDeleted(Destructor, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008700
Douglas Gregor7454c562010-07-02 20:37:36 +00008701 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00008702 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +00008703
Douglas Gregor7454c562010-07-02 20:37:36 +00008704 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00008705 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00008706 PushOnScopeChains(Destructor, S, false);
8707 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +00008708
Douglas Gregorf1203042010-07-01 19:09:28 +00008709 return Destructor;
8710}
8711
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008712void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00008713 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008714 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +00008715 !Destructor->doesThisDeclarationHaveABody() &&
8716 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008717 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00008718 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008719 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008720
Douglas Gregor54818f02010-05-12 16:39:35 +00008721 if (Destructor->isInvalidDecl())
8722 return;
8723
Eli Friedmaneaf34142012-10-18 20:14:08 +00008724 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008725
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008726 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00008727 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8728 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00008729
Douglas Gregor54818f02010-05-12 16:39:35 +00008730 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008731 Diag(CurrentLocation, diag::note_member_synthesized_at)
8732 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8733
8734 Destructor->setInvalidDecl();
8735 return;
8736 }
8737
Douglas Gregor73193272010-09-20 16:48:21 +00008738 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008739 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +00008740 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008741 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008742
8743 if (ASTMutationListener *L = getASTMutationListener()) {
8744 L->CompletedImplicitDefinition(Destructor);
8745 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008746}
8747
Richard Smith84973e52012-04-21 18:42:51 +00008748/// \brief Perform any semantic analysis which needs to be delayed until all
8749/// pending class member declarations have been parsed.
8750void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00008751 // If the context is an invalid C++ class, just suppress these checks.
8752 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8753 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008754 DelayedDefaultedMemberExceptionSpecs.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00008755 DelayedDestructorExceptionSpecChecks.clear();
8756 return;
8757 }
8758 }
Richard Smith84973e52012-04-21 18:42:51 +00008759}
8760
Richard Smithd3b5c9082012-07-27 04:22:15 +00008761void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8762 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008763 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00008764 "adjusting dtor exception specs was introduced in c++11");
8765
Sebastian Redl623ea822011-05-19 05:13:44 +00008766 // C++11 [class.dtor]p3:
8767 // A declaration of a destructor that does not have an exception-
8768 // specification is implicitly considered to have the same exception-
8769 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008770 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +00008771 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008772 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +00008773 return;
8774
Chandler Carruth9a797572011-09-20 04:55:26 +00008775 // Replace the destructor's type, building off the existing one. Fortunately,
8776 // the only thing of interest in the destructor type is its extended info.
8777 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008778 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8779 EPI.ExceptionSpecType = EST_Unevaluated;
8780 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008781 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +00008782
Sebastian Redl623ea822011-05-19 05:13:44 +00008783 // FIXME: If the destructor has a body that could throw, and the newly created
8784 // spec doesn't allow exceptions, we should emit a warning, because this
8785 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008786 // However, we don't have a body or an exception specification yet, so it
8787 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +00008788}
8789
Pavel Labath58934982013-08-30 08:52:28 +00008790namespace {
8791/// \brief An abstract base class for all helper classes used in building the
8792// copy/move operators. These classes serve as factory functions and help us
8793// avoid using the same Expr* in the AST twice.
8794class ExprBuilder {
8795 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8796 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8797
8798protected:
8799 static Expr *assertNotNull(Expr *E) {
8800 assert(E && "Expression construction must not fail.");
8801 return E;
8802 }
8803
8804public:
8805 ExprBuilder() {}
8806 virtual ~ExprBuilder() {}
8807
8808 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8809};
8810
8811class RefBuilder: public ExprBuilder {
8812 VarDecl *Var;
8813 QualType VarType;
8814
8815public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008816 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008817 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take());
8818 }
8819
8820 RefBuilder(VarDecl *Var, QualType VarType)
8821 : Var(Var), VarType(VarType) {}
8822};
8823
8824class ThisBuilder: public ExprBuilder {
8825public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008826 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008827 return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>());
8828 }
8829};
8830
8831class CastBuilder: public ExprBuilder {
8832 const ExprBuilder &Builder;
8833 QualType Type;
8834 ExprValueKind Kind;
8835 const CXXCastPath &Path;
8836
8837public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008838 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008839 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8840 CK_UncheckedDerivedToBase, Kind,
8841 &Path).take());
8842 }
8843
8844 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8845 const CXXCastPath &Path)
8846 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8847};
8848
8849class DerefBuilder: public ExprBuilder {
8850 const ExprBuilder &Builder;
8851
8852public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008853 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008854 return assertNotNull(
8855 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take());
8856 }
8857
8858 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8859};
8860
8861class MemberBuilder: public ExprBuilder {
8862 const ExprBuilder &Builder;
8863 QualType Type;
8864 CXXScopeSpec SS;
8865 bool IsArrow;
8866 LookupResult &MemberLookup;
8867
8868public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008869 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008870 return assertNotNull(S.BuildMemberReferenceExpr(
8871 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0,
8872 MemberLookup, 0).take());
8873 }
8874
8875 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
8876 LookupResult &MemberLookup)
8877 : Builder(Builder), Type(Type), IsArrow(IsArrow),
8878 MemberLookup(MemberLookup) {}
8879};
8880
8881class MoveCastBuilder: public ExprBuilder {
8882 const ExprBuilder &Builder;
8883
8884public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008885 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008886 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
8887 }
8888
8889 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8890};
8891
8892class LvalueConvBuilder: public ExprBuilder {
8893 const ExprBuilder &Builder;
8894
8895public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008896 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008897 return assertNotNull(
8898 S.DefaultLvalueConversion(Builder.build(S, Loc)).take());
8899 }
8900
8901 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8902};
8903
8904class SubscriptBuilder: public ExprBuilder {
8905 const ExprBuilder &Base;
8906 const ExprBuilder &Index;
8907
8908public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008909 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00008910 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
8911 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take());
8912 }
8913
8914 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
8915 : Base(Base), Index(Index) {}
8916};
8917
8918} // end anonymous namespace
8919
Richard Smith41ae3282012-11-14 00:50:40 +00008920/// When generating a defaulted copy or move assignment operator, if a field
8921/// should be copied with __builtin_memcpy rather than via explicit assignments,
8922/// do so. This optimization only applies for arrays of scalars, and for arrays
8923/// of class type where the selected copy/move-assignment operator is trivial.
8924static StmtResult
8925buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00008926 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +00008927 // Compute the size of the memory buffer to be copied.
8928 QualType SizeType = S.Context.getSizeType();
8929 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8930 S.Context.getTypeSizeInChars(T).getQuantity());
8931
8932 // Take the address of the field references for "from" and "to". We
8933 // directly construct UnaryOperators here because semantic analysis
8934 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +00008935 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00008936 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8937 S.Context.getPointerType(From->getType()),
8938 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +00008939 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00008940 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8941 S.Context.getPointerType(To->getType()),
8942 VK_RValue, OK_Ordinary, Loc);
8943
8944 const Type *E = T->getBaseElementTypeUnsafe();
8945 bool NeedsCollectableMemCpy =
8946 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8947
8948 // Create a reference to the __builtin_objc_memmove_collectable function
8949 StringRef MemCpyName = NeedsCollectableMemCpy ?
8950 "__builtin_objc_memmove_collectable" :
8951 "__builtin_memcpy";
8952 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8953 Sema::LookupOrdinaryName);
8954 S.LookupName(R, S.TUScope, true);
8955
8956 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8957 if (!MemCpy)
8958 // Something went horribly wrong earlier, and we will have complained
8959 // about it.
8960 return StmtError();
8961
8962 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8963 VK_RValue, Loc, 0);
8964 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8965
8966 Expr *CallArgs[] = {
8967 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8968 };
8969 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8970 Loc, CallArgs, Loc);
8971
8972 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8973 return S.Owned(Call.takeAs<Stmt>());
8974}
8975
Sebastian Redl22653ba2011-08-30 19:58:05 +00008976/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00008977/// \c To.
8978///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008979/// This routine is used to copy/move the members of a class with an
8980/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00008981/// copied are arrays, this routine builds for loops to copy them.
8982///
8983/// \param S The Sema object used for type-checking.
8984///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008985/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008986///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008987/// \param T The type of the expressions being copied/moved. Both expressions
8988/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008989///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008990/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008991///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008992/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008993///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008994/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00008995/// Otherwise, it's a non-static member subobject.
8996///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008997/// \param Copying Whether we're copying or moving.
8998///
Douglas Gregorb139cd52010-05-01 20:49:11 +00008999/// \param Depth Internal parameter recording the depth of the recursion.
9000///
Richard Smith41ae3282012-11-14 00:50:40 +00009001/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9002/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +00009003static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +00009004buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009005 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009006 bool CopyingBaseSubobject, bool Copying,
9007 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +00009008 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00009009 // Each subobject is assigned in the manner appropriate to its type:
9010 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00009011 // - if the subobject is of class type, as if by a call to operator= with
9012 // the subobject as the object expression and the corresponding
9013 // subobject of x as a single function argument (as if by explicit
9014 // qualification; that is, ignoring any possible virtual overriding
9015 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +00009016 //
9017 // C++03 [class.copy]p13:
9018 // - if the subobject is of class type, the copy assignment operator for
9019 // the class is used (as if by explicit qualification; that is,
9020 // ignoring any possible virtual overriding functions in more derived
9021 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009022 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9023 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +00009024
Douglas Gregorb139cd52010-05-01 20:49:11 +00009025 // Look for operator=.
9026 DeclarationName Name
9027 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9028 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9029 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009030
Richard Smith52c0b582012-11-13 00:54:12 +00009031 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9032 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009033 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +00009034 LookupResult::Filter F = OpLookup.makeFilter();
9035 while (F.hasNext()) {
9036 NamedDecl *D = F.next();
9037 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9038 if (Method->isCopyAssignmentOperator() ||
9039 (!Copying && Method->isMoveAssignmentOperator()))
9040 continue;
9041
9042 F.erase();
9043 }
9044 F.done();
John McCallab8c2732010-03-16 06:11:48 +00009045 }
Richard Smith52c0b582012-11-13 00:54:12 +00009046
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009047 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +00009048 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009049 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +00009050 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009051 // ambiguities), we need to cast "this" to that subobject type; to
9052 // ensure that we don't go through the virtual call mechanism, we need
9053 // to qualify the operator= name with the base class (see below). However,
9054 // this means that if the base class has a protected copy assignment
9055 // operator, the protected member access check will fail. So, we
9056 // rewrite "protected" access to "public" access in this case, since we
9057 // know by construction that we're calling from a derived class.
9058 if (CopyingBaseSubobject) {
9059 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9060 L != LEnd; ++L) {
9061 if (L.getAccess() == AS_protected)
9062 L.setAccess(AS_public);
9063 }
9064 }
Richard Smith52c0b582012-11-13 00:54:12 +00009065
Douglas Gregorb139cd52010-05-01 20:49:11 +00009066 // Create the nested-name-specifier that will be used to qualify the
9067 // reference to operator=; this is required to suppress the virtual
9068 // call mechanism.
9069 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00009070 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +00009071 SS.MakeTrivial(S.Context,
9072 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00009073 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00009074 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009075
Douglas Gregorb139cd52010-05-01 20:49:11 +00009076 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00009077 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +00009078 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9079 SS, /*TemplateKWLoc=*/SourceLocation(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00009080 /*FirstQualifierInScope=*/0,
9081 OpLookup,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009082 /*TemplateArgs=*/0,
9083 /*SuppressQualifierCheck=*/true);
9084 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009085 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009086
Douglas Gregorb139cd52010-05-01 20:49:11 +00009087 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00009088
Pavel Labath58934982013-08-30 08:52:28 +00009089 Expr *FromInst = From.build(S, Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009090 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00009091 OpEqualRef.takeAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +00009092 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009093 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009094 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009095
Richard Smith41ae3282012-11-14 00:50:40 +00009096 // If we built a call to a trivial 'operator=' while copying an array,
9097 // bail out. We'll replace the whole shebang with a memcpy.
9098 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9099 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9100 return StmtResult((Stmt*)0);
9101
Richard Smith52c0b582012-11-13 00:54:12 +00009102 // Convert to an expression-statement, and clean up any produced
9103 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +00009104 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009105 }
John McCallab8c2732010-03-16 06:11:48 +00009106
Richard Smith52c0b582012-11-13 00:54:12 +00009107 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +00009108 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +00009109 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009110 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +00009111 ExprResult Assignment = S.CreateBuiltinBinOp(
9112 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009113 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009114 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +00009115 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009116 }
Richard Smith52c0b582012-11-13 00:54:12 +00009117
9118 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +00009119 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +00009120
Douglas Gregorb139cd52010-05-01 20:49:11 +00009121 // Construct a loop over the array bounds, e.g.,
9122 //
9123 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9124 //
9125 // that will copy each of the array elements.
9126 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +00009127
Douglas Gregorb139cd52010-05-01 20:49:11 +00009128 // Create the iteration variable.
9129 IdentifierInfo *IterationVarName = 0;
9130 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009131 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009132 llvm::raw_svector_ostream OS(Str);
9133 OS << "__i" << Depth;
9134 IterationVarName = &S.Context.Idents.get(OS.str());
9135 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00009136 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009137 IterationVarName, SizeType,
9138 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009139 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +00009140
Douglas Gregorb139cd52010-05-01 20:49:11 +00009141 // Initialize the iteration variable to zero.
9142 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009143 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009144
Pavel Labath58934982013-08-30 08:52:28 +00009145 // Creates a reference to the iteration variable.
9146 RefBuilder IterationVarRef(IterationVar, SizeType);
9147 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +00009148
Douglas Gregorb139cd52010-05-01 20:49:11 +00009149 // Create the DeclStmt that holds the iteration variable.
9150 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009151
Douglas Gregorb139cd52010-05-01 20:49:11 +00009152 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +00009153 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9154 MoveCastBuilder FromIndexMove(FromIndexCopy);
9155 const ExprBuilder *FromIndex;
9156 if (Copying)
9157 FromIndex = &FromIndexCopy;
9158 else
9159 FromIndex = &FromIndexMove;
9160
9161 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009162
9163 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +00009164 StmtResult Copy =
9165 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +00009166 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +00009167 Copying, Depth + 1);
9168 // Bail out if copying fails or if we determined that we should use memcpy.
9169 if (Copy.isInvalid() || !Copy.get())
9170 return Copy;
9171
9172 // Create the comparison against the array bound.
9173 llvm::APInt Upper
9174 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9175 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +00009176 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +00009177 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9178 BO_NE, S.Context.BoolTy,
9179 VK_RValue, OK_Ordinary, Loc, false);
9180
9181 // Create the pre-increment of the iteration variable.
9182 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +00009183 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9184 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009185
Douglas Gregorb139cd52010-05-01 20:49:11 +00009186 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00009187 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009188 S.MakeFullExpr(Comparison),
Richard Smith945f8d32013-01-14 22:39:08 +00009189 0, S.MakeFullDiscardedValueExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00009190 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009191}
9192
Richard Smith41ae3282012-11-14 00:50:40 +00009193static StmtResult
9194buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009195 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009196 bool CopyingBaseSubobject, bool Copying) {
9197 // Maybe we should use a memcpy?
9198 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9199 T.isTriviallyCopyableType(S.Context))
9200 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9201
9202 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9203 CopyingBaseSubobject,
9204 Copying, 0));
9205
9206 // If we ended up picking a trivial assignment operator for an array of a
9207 // non-trivially-copyable class type, just emit a memcpy.
9208 if (!Result.isInvalid() && !Result.get())
9209 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9210
9211 return Result;
9212}
9213
Richard Smithd3b5c9082012-07-27 04:22:15 +00009214Sema::ImplicitExceptionSpecification
9215Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9216 CXXRecordDecl *ClassDecl = MD->getParent();
9217
9218 ImplicitExceptionSpecification ExceptSpec(*this);
9219 if (ClassDecl->isInvalidDecl())
9220 return ExceptSpec;
9221
9222 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00009223 assert(T->getNumParams() == 1 && "not a copy assignment op");
9224 unsigned ArgQuals =
9225 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009226
Douglas Gregor68e11362010-07-01 17:48:08 +00009227 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +00009228 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +00009229 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00009230
9231 // It is unspecified whether or not an implicit copy assignment operator
9232 // attempts to deduplicate calls to assignment operators of virtual bases are
9233 // made. As such, this exception specification is effectively unspecified.
9234 // Based on a similar decision made for constness in C++0x, we're erring on
9235 // the side of assuming such calls to be made regardless of whether they
9236 // actually happen.
Douglas Gregor68e11362010-07-01 17:48:08 +00009237 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9238 BaseEnd = ClassDecl->bases_end();
9239 Base != BaseEnd; ++Base) {
Alexis Hunt491ec602011-06-21 23:42:56 +00009240 if (Base->isVirtual())
9241 continue;
9242
Douglas Gregor330b9cf2010-07-02 21:50:04 +00009243 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00009244 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009245 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9246 ArgQuals, false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009247 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00009248 }
Alexis Hunt491ec602011-06-21 23:42:56 +00009249
9250 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9251 BaseEnd = ClassDecl->vbases_end();
9252 Base != BaseEnd; ++Base) {
9253 CXXRecordDecl *BaseClassDecl
9254 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9255 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9256 ArgQuals, false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009257 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +00009258 }
9259
Douglas Gregor68e11362010-07-01 17:48:08 +00009260 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9261 FieldEnd = ClassDecl->field_end();
9262 Field != FieldEnd;
9263 ++Field) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009264 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00009265 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9266 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +00009267 LookupCopyingAssignment(FieldClassDecl,
9268 ArgQuals | FieldType.getCVRQualifiers(),
9269 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009270 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009271 }
Douglas Gregor68e11362010-07-01 17:48:08 +00009272 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009273
Richard Smithd3b5c9082012-07-27 04:22:15 +00009274 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +00009275}
9276
9277CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9278 // Note: The following rules are largely analoguous to the copy
9279 // constructor rules. Note that virtual bases are not taken into account
9280 // for determining the argument type of the operator. Note also that
9281 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +00009282 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +00009283
Richard Smith8bf22e52012-11-29 01:34:07 +00009284 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9285 if (DSM.isAlreadyBeingDeclared())
9286 return 0;
9287
Alexis Hunt119f3652011-05-14 05:23:20 +00009288 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9289 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +00009290 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9291 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +00009292 ArgType = ArgType.withConst();
9293 ArgType = Context.getLValueReferenceType(ArgType);
9294
Richard Smith99005e62013-05-07 03:19:20 +00009295 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9296 CXXCopyAssignment,
9297 Const);
9298
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009299 // An implicitly-declared copy assignment operator is an inline public
9300 // member of its class.
9301 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009302 SourceLocation ClassLoc = ClassDecl->getLocation();
9303 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009304 CXXMethodDecl *CopyAssignment =
9305 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9306 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
9307 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009308 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00009309 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009310 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009311
9312 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009313 FunctionProtoType::ExtProtoInfo EPI =
9314 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009315 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009316
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009317 // Add the parameter to the operator.
9318 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00009319 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009320 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00009321 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00009322 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +00009323
Richard Smith6b02d462012-12-08 08:32:28 +00009324 AddOverriddenMethods(ClassDecl, CopyAssignment);
9325
9326 CopyAssignment->setTrivial(
9327 ClassDecl->needsOverloadResolutionForCopyAssignment()
9328 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9329 : ClassDecl->hasTrivialCopyAssignment());
9330
Richard Smith852265f2012-03-30 20:53:28 +00009331 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smithb4d2a152013-04-02 19:38:47 +00009332 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +00009333
Richard Smith6b02d462012-12-08 08:32:28 +00009334 // Note that we have added this copy-assignment operator.
9335 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9336
9337 if (Scope *S = getScopeForContext(ClassDecl))
9338 PushOnScopeChains(CopyAssignment, S, false);
9339 ClassDecl->addDecl(CopyAssignment);
9340
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009341 return CopyAssignment;
9342}
9343
Richard Smithd577fbb2013-06-13 03:23:42 +00009344/// Diagnose an implicit copy operation for a class which is odr-used, but
9345/// which is deprecated because the class has a user-declared copy constructor,
9346/// copy assignment operator, or destructor.
9347static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9348 SourceLocation UseLoc) {
9349 assert(CopyOp->isImplicit());
9350
9351 CXXRecordDecl *RD = CopyOp->getParent();
9352 CXXMethodDecl *UserDeclaredOperation = 0;
9353
9354 // In Microsoft mode, assignment operations don't affect constructors and
9355 // vice versa.
9356 if (RD->hasUserDeclaredDestructor()) {
9357 UserDeclaredOperation = RD->getDestructor();
9358 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9359 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009360 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009361 // Find any user-declared copy constructor.
9362 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
9363 E = RD->ctor_end(); I != E; ++I) {
9364 if (I->isCopyConstructor()) {
9365 UserDeclaredOperation = *I;
9366 break;
9367 }
9368 }
9369 assert(UserDeclaredOperation);
9370 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9371 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009372 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009373 // Find any user-declared move assignment operator.
9374 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
9375 E = RD->method_end(); I != E; ++I) {
9376 if (I->isCopyAssignmentOperator()) {
9377 UserDeclaredOperation = *I;
9378 break;
9379 }
9380 }
9381 assert(UserDeclaredOperation);
9382 }
9383
9384 if (UserDeclaredOperation) {
9385 S.Diag(UserDeclaredOperation->getLocation(),
9386 diag::warn_deprecated_copy_operation)
9387 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9388 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9389 S.Diag(UseLoc, diag::note_member_synthesized_at)
9390 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9391 : Sema::CXXCopyAssignment)
9392 << RD;
9393 }
9394}
9395
Douglas Gregorb139cd52010-05-01 20:49:11 +00009396void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9397 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00009398 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009399 CopyAssignOperator->isOverloadedOperator() &&
9400 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009401 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9402 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009403 "DefineImplicitCopyAssignment called for wrong function");
9404
9405 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9406
9407 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9408 CopyAssignOperator->setInvalidDecl();
9409 return;
9410 }
Richard Smithd577fbb2013-06-13 03:23:42 +00009411
9412 // C++11 [class.copy]p18:
9413 // The [definition of an implicitly declared copy assignment operator] is
9414 // deprecated if the class has a user-declared copy constructor or a
9415 // user-declared destructor.
9416 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9417 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9418
Eli Friedman276dd182013-09-05 00:02:25 +00009419 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009420
Eli Friedmaneaf34142012-10-18 20:14:08 +00009421 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009422 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009423
9424 // C++0x [class.copy]p30:
9425 // The implicitly-defined or explicitly-defaulted copy assignment operator
9426 // for a non-union class X performs memberwise copy assignment of its
9427 // subobjects. The direct base classes of X are assigned first, in the
9428 // order of their declaration in the base-specifier-list, and then the
9429 // immediate non-static data members of X are assigned, in the order in
9430 // which they were declared in the class definition.
9431
9432 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009433 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009434
9435 // The parameter for the "other" object, which we are copying from.
9436 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9437 Qualifiers OtherQuals = Other->getType().getQualifiers();
9438 QualType OtherRefType = Other->getType();
9439 if (const LValueReferenceType *OtherRef
9440 = OtherRefType->getAs<LValueReferenceType>()) {
9441 OtherRefType = OtherRef->getPointeeType();
9442 OtherQuals = OtherRefType.getQualifiers();
9443 }
9444
9445 // Our location for everything implicitly-generated.
9446 SourceLocation Loc = CopyAssignOperator->getLocation();
9447
Pavel Labath58934982013-08-30 08:52:28 +00009448 // Builds a DeclRefExpr for the "other" object.
9449 RefBuilder OtherRef(Other, OtherRefType);
9450
9451 // Builds the "this" pointer.
9452 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009453
9454 // Assign base classes.
9455 bool Invalid = false;
9456 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9457 E = ClassDecl->bases_end(); Base != E; ++Base) {
9458 // Form the assignment:
9459 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9460 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009461 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009462 Invalid = true;
9463 continue;
9464 }
9465
John McCallcf142162010-08-07 06:22:56 +00009466 CXXCastPath BasePath;
9467 BasePath.push_back(Base);
9468
Douglas Gregorb139cd52010-05-01 20:49:11 +00009469 // Construct the "from" expression, which is an implicit cast to the
9470 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009471 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9472 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009473
9474 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009475 DerefBuilder DerefThis(This);
9476 CastBuilder To(DerefThis,
9477 Context.getCVRQualifiedType(
9478 BaseType, CopyAssignOperator->getTypeQualifiers()),
9479 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009480
9481 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +00009482 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +00009483 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009484 /*CopyingBaseSubobject=*/true,
9485 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009486 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009487 Diag(CurrentLocation, diag::note_member_synthesized_at)
9488 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9489 CopyAssignOperator->setInvalidDecl();
9490 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009491 }
9492
9493 // Success! Record the copy.
9494 Statements.push_back(Copy.takeAs<Expr>());
9495 }
9496
Douglas Gregorb139cd52010-05-01 20:49:11 +00009497 // Assign non-static members.
9498 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9499 FieldEnd = ClassDecl->field_end();
9500 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009501 if (Field->isUnnamedBitfield())
9502 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009503
9504 if (Field->isInvalidDecl()) {
9505 Invalid = true;
9506 continue;
9507 }
9508
Douglas Gregorb139cd52010-05-01 20:49:11 +00009509 // Check for members of reference type; we can't copy those.
9510 if (Field->getType()->isReferenceType()) {
9511 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9512 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9513 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009514 Diag(CurrentLocation, diag::note_member_synthesized_at)
9515 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009516 Invalid = true;
9517 continue;
9518 }
9519
9520 // Check for members of const-qualified, non-class type.
9521 QualType BaseType = Context.getBaseElementType(Field->getType());
9522 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9523 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9524 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9525 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009526 Diag(CurrentLocation, diag::note_member_synthesized_at)
9527 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009528 Invalid = true;
9529 continue;
9530 }
John McCall1b1a1db2011-06-17 00:18:42 +00009531
9532 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009533 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9534 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009535
9536 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00009537 if (FieldType->isIncompleteArrayType()) {
9538 assert(ClassDecl->hasFlexibleArrayMember() &&
9539 "Incomplete array type is not valid");
9540 continue;
9541 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009542
9543 // Build references to the field in the object we're copying from and to.
9544 CXXScopeSpec SS; // Intentionally empty
9545 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9546 LookupMemberName);
David Blaikie40ed2972012-06-06 20:45:41 +00009547 MemberLookup.addDecl(*Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009548 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +00009549
9550 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9551
9552 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009553
Douglas Gregorb139cd52010-05-01 20:49:11 +00009554 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +00009555 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +00009556 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009557 /*CopyingBaseSubobject=*/false,
9558 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009559 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009560 Diag(CurrentLocation, diag::note_member_synthesized_at)
9561 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9562 CopyAssignOperator->setInvalidDecl();
9563 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009564 }
9565
9566 // Success! Record the copy.
9567 Statements.push_back(Copy.takeAs<Stmt>());
9568 }
9569
9570 if (!Invalid) {
9571 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +00009572 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009573
John McCalldadc5752010-08-24 06:29:42 +00009574 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009575 if (Return.isInvalid())
9576 Invalid = true;
9577 else {
9578 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00009579
9580 if (Trap.hasErrorOccurred()) {
9581 Diag(CurrentLocation, diag::note_member_synthesized_at)
9582 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9583 Invalid = true;
9584 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009585 }
9586 }
9587
9588 if (Invalid) {
9589 CopyAssignOperator->setInvalidDecl();
9590 return;
9591 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009592
9593 StmtResult Body;
9594 {
9595 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009596 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009597 /*isStmtExpr=*/false);
9598 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9599 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009600 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00009601
9602 if (ASTMutationListener *L = getASTMutationListener()) {
9603 L->CompletedImplicitDefinition(CopyAssignOperator);
9604 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009605}
9606
Sebastian Redl22653ba2011-08-30 19:58:05 +00009607Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009608Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9609 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009610
Richard Smithd3b5c9082012-07-27 04:22:15 +00009611 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009612 if (ClassDecl->isInvalidDecl())
9613 return ExceptSpec;
9614
9615 // C++0x [except.spec]p14:
9616 // An implicitly declared special member function (Clause 12) shall have an
9617 // exception-specification. [...]
9618
9619 // It is unspecified whether or not an implicit move assignment operator
9620 // attempts to deduplicate calls to assignment operators of virtual bases are
9621 // made. As such, this exception specification is effectively unspecified.
9622 // Based on a similar decision made for constness in C++0x, we're erring on
9623 // the side of assuming such calls to be made regardless of whether they
9624 // actually happen.
9625 // Note that a move constructor is not implicitly declared when there are
9626 // virtual bases, but it can still be user-declared and explicitly defaulted.
9627 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9628 BaseEnd = ClassDecl->bases_end();
9629 Base != BaseEnd; ++Base) {
9630 if (Base->isVirtual())
9631 continue;
9632
9633 CXXRecordDecl *BaseClassDecl
9634 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9635 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009636 0, false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009637 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009638 }
9639
9640 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9641 BaseEnd = ClassDecl->vbases_end();
9642 Base != BaseEnd; ++Base) {
9643 CXXRecordDecl *BaseClassDecl
9644 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9645 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009646 0, false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009647 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009648 }
9649
9650 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9651 FieldEnd = ClassDecl->field_end();
9652 Field != FieldEnd;
9653 ++Field) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009654 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009655 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +00009656 if (CXXMethodDecl *MoveAssign =
9657 LookupMovingAssignment(FieldClassDecl,
9658 FieldType.getCVRQualifiers(),
9659 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009660 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009661 }
9662 }
9663
9664 return ExceptSpec;
9665}
9666
9667CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009668 assert(ClassDecl->needsImplicitMoveAssignment());
9669
Richard Smith8bf22e52012-11-29 01:34:07 +00009670 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9671 if (DSM.isAlreadyBeingDeclared())
9672 return 0;
9673
Sebastian Redl22653ba2011-08-30 19:58:05 +00009674 // Note: The following rules are largely analoguous to the move
9675 // constructor rules.
9676
Sebastian Redl22653ba2011-08-30 19:58:05 +00009677 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9678 QualType RetType = Context.getLValueReferenceType(ArgType);
9679 ArgType = Context.getRValueReferenceType(ArgType);
9680
Richard Smith99005e62013-05-07 03:19:20 +00009681 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9682 CXXMoveAssignment,
9683 false);
9684
Sebastian Redl22653ba2011-08-30 19:58:05 +00009685 // An implicitly-declared move assignment operator is an inline public
9686 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +00009687 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9688 SourceLocation ClassLoc = ClassDecl->getLocation();
9689 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009690 CXXMethodDecl *MoveAssignment =
9691 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9692 /*TInfo=*/0, /*StorageClass=*/SC_None,
9693 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009694 MoveAssignment->setAccess(AS_public);
9695 MoveAssignment->setDefaulted();
9696 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009697
Richard Smithd3b5c9082012-07-27 04:22:15 +00009698 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009699 FunctionProtoType::ExtProtoInfo EPI =
9700 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009701 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009702
Sebastian Redl22653ba2011-08-30 19:58:05 +00009703 // Add the parameter to the operator.
9704 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9705 ClassLoc, ClassLoc, /*Id=*/0,
9706 ArgType, /*TInfo=*/0,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009707 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00009708 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009709
Richard Smith6b02d462012-12-08 08:32:28 +00009710 AddOverriddenMethods(ClassDecl, MoveAssignment);
9711
9712 MoveAssignment->setTrivial(
9713 ClassDecl->needsOverloadResolutionForMoveAssignment()
9714 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9715 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009716
Richard Smithd951a1d2012-02-18 02:02:13 +00009717 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +00009718 ClassDecl->setImplicitMoveAssignmentIsDeleted();
9719 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009720 }
9721
Richard Smith6b02d462012-12-08 08:32:28 +00009722 // Note that we have added this copy-assignment operator.
9723 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9724
Sebastian Redl22653ba2011-08-30 19:58:05 +00009725 if (Scope *S = getScopeForContext(ClassDecl))
9726 PushOnScopeChains(MoveAssignment, S, false);
9727 ClassDecl->addDecl(MoveAssignment);
9728
Sebastian Redl22653ba2011-08-30 19:58:05 +00009729 return MoveAssignment;
9730}
9731
Richard Smithb2504bd2013-11-04 04:26:14 +00009732/// Check if we're implicitly defining a move assignment operator for a class
9733/// with virtual bases. Such a move assignment might move-assign the virtual
9734/// base multiple times.
9735static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
9736 SourceLocation CurrentLocation) {
9737 assert(!Class->isDependentContext() && "should not define dependent move");
9738
9739 // Only a virtual base could get implicitly move-assigned multiple times.
9740 // Only a non-trivial move assignment can observe this. We only want to
9741 // diagnose if we implicitly define an assignment operator that assigns
9742 // two base classes, both of which move-assign the same virtual base.
9743 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
9744 Class->getNumBases() < 2)
9745 return;
9746
9747 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
9748 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
9749 VBaseMap VBases;
9750
9751 for (CXXRecordDecl::base_class_iterator BI = Class->bases_begin(),
9752 BE = Class->bases_end();
9753 BI != BE; ++BI) {
9754 Worklist.push_back(&*BI);
9755 while (!Worklist.empty()) {
9756 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
9757 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
9758
9759 // If the base has no non-trivial move assignment operators,
9760 // we don't care about moves from it.
9761 if (!Base->hasNonTrivialMoveAssignment())
9762 continue;
9763
9764 // If there's nothing virtual here, skip it.
9765 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
9766 continue;
9767
9768 // If we're not actually going to call a move assignment for this base,
9769 // or the selected move assignment is trivial, skip it.
9770 Sema::SpecialMemberOverloadResult *SMOR =
9771 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
9772 /*ConstArg*/false, /*VolatileArg*/false,
9773 /*RValueThis*/true, /*ConstThis*/false,
9774 /*VolatileThis*/false);
9775 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
9776 !SMOR->getMethod()->isMoveAssignmentOperator())
9777 continue;
9778
9779 if (BaseSpec->isVirtual()) {
9780 // We're going to move-assign this virtual base, and its move
9781 // assignment operator is not trivial. If this can happen for
9782 // multiple distinct direct bases of Class, diagnose it. (If it
9783 // only happens in one base, we'll diagnose it when synthesizing
9784 // that base class's move assignment operator.)
9785 CXXBaseSpecifier *&Existing =
9786 VBases.insert(std::make_pair(Base->getCanonicalDecl(), BI))
9787 .first->second;
9788 if (Existing && Existing != BI) {
9789 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
9790 << Class << Base;
9791 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
9792 << (Base->getCanonicalDecl() ==
9793 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9794 << Base << Existing->getType() << Existing->getSourceRange();
9795 S.Diag(BI->getLocStart(), diag::note_vbase_moved_here)
9796 << (Base->getCanonicalDecl() ==
9797 BI->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9798 << Base << BI->getType() << BaseSpec->getSourceRange();
9799
9800 // Only diagnose each vbase once.
9801 Existing = 0;
9802 }
9803 } else {
9804 // Only walk over bases that have defaulted move assignment operators.
9805 // We assume that any user-provided move assignment operator handles
9806 // the multiple-moves-of-vbase case itself somehow.
9807 if (!SMOR->getMethod()->isDefaulted())
9808 continue;
9809
9810 // We're going to move the base classes of Base. Add them to the list.
9811 for (CXXRecordDecl::base_class_iterator BI = Base->bases_begin(),
9812 BE = Base->bases_end();
9813 BI != BE; ++BI)
9814 Worklist.push_back(&*BI);
9815 }
9816 }
9817 }
9818}
9819
Sebastian Redl22653ba2011-08-30 19:58:05 +00009820void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9821 CXXMethodDecl *MoveAssignOperator) {
9822 assert((MoveAssignOperator->isDefaulted() &&
9823 MoveAssignOperator->isOverloadedOperator() &&
9824 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009825 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9826 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +00009827 "DefineImplicitMoveAssignment called for wrong function");
9828
9829 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9830
9831 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9832 MoveAssignOperator->setInvalidDecl();
9833 return;
9834 }
9835
Eli Friedman276dd182013-09-05 00:02:25 +00009836 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009837
Eli Friedmaneaf34142012-10-18 20:14:08 +00009838 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009839 DiagnosticErrorTrap Trap(Diags);
9840
9841 // C++0x [class.copy]p28:
9842 // The implicitly-defined or move assignment operator for a non-union class
9843 // X performs memberwise move assignment of its subobjects. The direct base
9844 // classes of X are assigned first, in the order of their declaration in the
9845 // base-specifier-list, and then the immediate non-static data members of X
9846 // are assigned, in the order in which they were declared in the class
9847 // definition.
9848
Richard Smithb2504bd2013-11-04 04:26:14 +00009849 // Issue a warning if our implicit move assignment operator will move
9850 // from a virtual base more than once.
9851 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +00009852
Sebastian Redl22653ba2011-08-30 19:58:05 +00009853 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009854 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +00009855
9856 // The parameter for the "other" object, which we are move from.
9857 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9858 QualType OtherRefType = Other->getType()->
9859 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +00009860 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +00009861 "Bad argument type of defaulted move assignment");
9862
9863 // Our location for everything implicitly-generated.
9864 SourceLocation Loc = MoveAssignOperator->getLocation();
9865
Pavel Labath58934982013-08-30 08:52:28 +00009866 // Builds a reference to the "other" object.
9867 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009868 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009869 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009870
Pavel Labath58934982013-08-30 08:52:28 +00009871 // Builds the "this" pointer.
9872 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009873
Sebastian Redl22653ba2011-08-30 19:58:05 +00009874 // Assign base classes.
9875 bool Invalid = false;
9876 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9877 E = ClassDecl->bases_end(); Base != E; ++Base) {
Richard Smithb2504bd2013-11-04 04:26:14 +00009878 // C++11 [class.copy]p28:
9879 // It is unspecified whether subobjects representing virtual base classes
9880 // are assigned more than once by the implicitly-defined copy assignment
9881 // operator.
9882 // FIXME: Do not assign to a vbase that will be assigned by some other base
9883 // class. For a move-assignment, this can result in the vbase being moved
9884 // multiple times.
9885
Sebastian Redl22653ba2011-08-30 19:58:05 +00009886 // Form the assignment:
9887 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9888 QualType BaseType = Base->getType().getUnqualifiedType();
9889 if (!BaseType->isRecordType()) {
9890 Invalid = true;
9891 continue;
9892 }
9893
9894 CXXCastPath BasePath;
9895 BasePath.push_back(Base);
9896
9897 // Construct the "from" expression, which is an implicit cast to the
9898 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009899 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009900
9901 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009902 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009903
9904 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009905 CastBuilder To(DerefThis,
9906 Context.getCVRQualifiedType(
9907 BaseType, MoveAssignOperator->getTypeQualifiers()),
9908 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009909
9910 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +00009911 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +00009912 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009913 /*CopyingBaseSubobject=*/true,
9914 /*Copying=*/false);
9915 if (Move.isInvalid()) {
9916 Diag(CurrentLocation, diag::note_member_synthesized_at)
9917 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9918 MoveAssignOperator->setInvalidDecl();
9919 return;
9920 }
9921
9922 // Success! Record the move.
9923 Statements.push_back(Move.takeAs<Expr>());
9924 }
9925
Sebastian Redl22653ba2011-08-30 19:58:05 +00009926 // Assign non-static members.
9927 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9928 FieldEnd = ClassDecl->field_end();
9929 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009930 if (Field->isUnnamedBitfield())
9931 continue;
9932
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009933 if (Field->isInvalidDecl()) {
9934 Invalid = true;
9935 continue;
9936 }
9937
Sebastian Redl22653ba2011-08-30 19:58:05 +00009938 // Check for members of reference type; we can't move those.
9939 if (Field->getType()->isReferenceType()) {
9940 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9941 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9942 Diag(Field->getLocation(), diag::note_declared_at);
9943 Diag(CurrentLocation, diag::note_member_synthesized_at)
9944 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9945 Invalid = true;
9946 continue;
9947 }
9948
9949 // Check for members of const-qualified, non-class type.
9950 QualType BaseType = Context.getBaseElementType(Field->getType());
9951 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9952 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9953 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9954 Diag(Field->getLocation(), diag::note_declared_at);
9955 Diag(CurrentLocation, diag::note_member_synthesized_at)
9956 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9957 Invalid = true;
9958 continue;
9959 }
9960
9961 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009962 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9963 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +00009964
9965 QualType FieldType = Field->getType().getNonReferenceType();
9966 if (FieldType->isIncompleteArrayType()) {
9967 assert(ClassDecl->hasFlexibleArrayMember() &&
9968 "Incomplete array type is not valid");
9969 continue;
9970 }
9971
9972 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +00009973 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9974 LookupMemberName);
David Blaikie40ed2972012-06-06 20:45:41 +00009975 MemberLookup.addDecl(*Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009976 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +00009977 MemberBuilder From(MoveOther, OtherRefType,
9978 /*IsArrow=*/false, MemberLookup);
9979 MemberBuilder To(This, getCurrentThisType(),
9980 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009981
Pavel Labath58934982013-08-30 08:52:28 +00009982 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +00009983 "Member reference with rvalue base must be rvalue except for reference "
9984 "members, which aren't allowed for move assignment.");
9985
Sebastian Redl22653ba2011-08-30 19:58:05 +00009986 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +00009987 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +00009988 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009989 /*CopyingBaseSubobject=*/false,
9990 /*Copying=*/false);
9991 if (Move.isInvalid()) {
9992 Diag(CurrentLocation, diag::note_member_synthesized_at)
9993 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9994 MoveAssignOperator->setInvalidDecl();
9995 return;
9996 }
Richard Smith11d19592012-11-12 23:33:00 +00009997
Sebastian Redl22653ba2011-08-30 19:58:05 +00009998 // Success! Record the copy.
9999 Statements.push_back(Move.takeAs<Stmt>());
10000 }
10001
10002 if (!Invalid) {
10003 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +000010004 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Sebastian Redl22653ba2011-08-30 19:58:05 +000010005
10006 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
10007 if (Return.isInvalid())
10008 Invalid = true;
10009 else {
10010 Statements.push_back(Return.takeAs<Stmt>());
10011
10012 if (Trap.hasErrorOccurred()) {
10013 Diag(CurrentLocation, diag::note_member_synthesized_at)
10014 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10015 Invalid = true;
10016 }
10017 }
10018 }
10019
10020 if (Invalid) {
10021 MoveAssignOperator->setInvalidDecl();
10022 return;
10023 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010024
10025 StmtResult Body;
10026 {
10027 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010028 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010029 /*isStmtExpr=*/false);
10030 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10031 }
Sebastian Redl22653ba2011-08-30 19:58:05 +000010032 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
10033
10034 if (ASTMutationListener *L = getASTMutationListener()) {
10035 L->CompletedImplicitDefinition(MoveAssignOperator);
10036 }
10037}
10038
Richard Smithd3b5c9082012-07-27 04:22:15 +000010039Sema::ImplicitExceptionSpecification
10040Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10041 CXXRecordDecl *ClassDecl = MD->getParent();
10042
10043 ImplicitExceptionSpecification ExceptSpec(*this);
10044 if (ClassDecl->isInvalidDecl())
10045 return ExceptSpec;
10046
10047 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000010048 assert(T->getNumParams() >= 1 && "not a copy ctor");
10049 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010050
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010051 // C++ [except.spec]p14:
10052 // An implicitly declared special member function (Clause 12) shall have an
10053 // exception-specification. [...]
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010054 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
10055 BaseEnd = ClassDecl->bases_end();
10056 Base != BaseEnd;
10057 ++Base) {
10058 // Virtual bases are handled below.
10059 if (Base->isVirtual())
10060 continue;
10061
Douglas Gregora6d69502010-07-02 23:41:54 +000010062 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010063 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010064 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010065 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithf623c962012-04-17 00:58:00 +000010066 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010067 }
10068 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
10069 BaseEnd = ClassDecl->vbases_end();
10070 Base != BaseEnd;
10071 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +000010072 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010073 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010074 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010075 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithf623c962012-04-17 00:58:00 +000010076 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010077 }
10078 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
10079 FieldEnd = ClassDecl->field_end();
10080 Field != FieldEnd;
10081 ++Field) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010082 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000010083 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10084 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000010085 LookupCopyingConstructor(FieldClassDecl,
10086 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000010087 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010088 }
10089 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010090
Richard Smithd3b5c9082012-07-27 04:22:15 +000010091 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000010092}
10093
10094CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10095 CXXRecordDecl *ClassDecl) {
10096 // C++ [class.copy]p4:
10097 // If the class definition does not explicitly declare a copy
10098 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000010099 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000010100
Richard Smith8bf22e52012-11-29 01:34:07 +000010101 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10102 if (DSM.isAlreadyBeingDeclared())
10103 return 0;
10104
Alexis Hunt913820d2011-05-13 06:10:58 +000010105 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10106 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000010107 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000010108 if (Const)
10109 ArgType = ArgType.withConst();
10110 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000010111
Richard Smithb5800092012-06-10 05:43:50 +000010112 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10113 CXXCopyConstructor,
10114 Const);
10115
Douglas Gregor54be3392010-07-01 17:57:27 +000010116 DeclarationName Name
10117 = Context.DeclarationNames.getCXXConstructorName(
10118 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010119 SourceLocation ClassLoc = ClassDecl->getLocation();
10120 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000010121
10122 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010123 // member of its class.
10124 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +000010125 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +000010126 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010127 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000010128 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000010129 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010130
Richard Smithd3b5c9082012-07-27 04:22:15 +000010131 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010132 FunctionProtoType::ExtProtoInfo EPI =
10133 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010134 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010135 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010136
Douglas Gregor54be3392010-07-01 17:57:27 +000010137 // Add the parameter to the constructor.
10138 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000010139 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +000010140 /*IdentifierInfo=*/0,
10141 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +000010142 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +000010143 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000010144
Richard Smith6b02d462012-12-08 08:32:28 +000010145 CopyConstructor->setTrivial(
10146 ClassDecl->needsOverloadResolutionForCopyConstructor()
10147 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10148 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000010149
Richard Smith852265f2012-03-30 20:53:28 +000010150 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +000010151 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010152
Richard Smith6b02d462012-12-08 08:32:28 +000010153 // Note that we have declared this constructor.
10154 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10155
10156 if (Scope *S = getScopeForContext(ClassDecl))
10157 PushOnScopeChains(CopyConstructor, S, false);
10158 ClassDecl->addDecl(CopyConstructor);
10159
Douglas Gregor54be3392010-07-01 17:57:27 +000010160 return CopyConstructor;
10161}
10162
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010163void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000010164 CXXConstructorDecl *CopyConstructor) {
10165 assert((CopyConstructor->isDefaulted() &&
10166 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010167 !CopyConstructor->doesThisDeclarationHaveABody() &&
10168 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010169 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010170
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000010171 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010172 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010173
Richard Smithd577fbb2013-06-13 03:23:42 +000010174 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000010175 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000010176 // deprecated if the class has a user-declared copy assignment operator
10177 // or a user-declared destructor.
10178 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10179 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10180
Eli Friedmaneaf34142012-10-18 20:14:08 +000010181 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010182 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010183
David Blaikie3fc2f912013-01-17 05:26:25 +000010184 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010185 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000010186 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000010187 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000010188 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000010189 } else {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010190 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010191 CopyConstructor->setBody(ActOnCompoundStmt(
10192 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
10193 /*isStmtExpr=*/ false).takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000010194 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010195
Eli Friedman276dd182013-09-05 00:02:25 +000010196 CopyConstructor->markUsed(Context);
Sebastian Redlab238a72011-04-24 16:28:06 +000010197 if (ASTMutationListener *L = getASTMutationListener()) {
10198 L->CompletedImplicitDefinition(CopyConstructor);
10199 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010200}
10201
Sebastian Redl22653ba2011-08-30 19:58:05 +000010202Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010203Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10204 CXXRecordDecl *ClassDecl = MD->getParent();
10205
Sebastian Redl22653ba2011-08-30 19:58:05 +000010206 // C++ [except.spec]p14:
10207 // An implicitly declared special member function (Clause 12) shall have an
10208 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000010209 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010210 if (ClassDecl->isInvalidDecl())
10211 return ExceptSpec;
10212
10213 // Direct base-class constructors.
10214 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
10215 BEnd = ClassDecl->bases_end();
10216 B != BEnd; ++B) {
10217 if (B->isVirtual()) // Handled below.
10218 continue;
10219
10220 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10221 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010222 CXXConstructorDecl *Constructor =
10223 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010224 // If this is a deleted function, add it anyway. This might be conformant
10225 // with the standard. This might not. I'm not sure. It might not matter.
10226 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010227 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010228 }
10229 }
10230
10231 // Virtual base-class constructors.
10232 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
10233 BEnd = ClassDecl->vbases_end();
10234 B != BEnd; ++B) {
10235 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10236 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010237 CXXConstructorDecl *Constructor =
10238 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010239 // If this is a deleted function, add it anyway. This might be conformant
10240 // with the standard. This might not. I'm not sure. It might not matter.
10241 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010242 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010243 }
10244 }
10245
10246 // Field constructors.
10247 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
10248 FEnd = ClassDecl->field_end();
10249 F != FEnd; ++F) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010250 QualType FieldType = Context.getBaseElementType(F->getType());
10251 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10252 CXXConstructorDecl *Constructor =
10253 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010254 // If this is a deleted function, add it anyway. This might be conformant
10255 // with the standard. This might not. I'm not sure. It might not matter.
10256 // In particular, the problem is that this function never gets called. It
10257 // might just be ill-formed because this function attempts to refer to
10258 // a deleted function here.
10259 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010260 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010261 }
10262 }
10263
10264 return ExceptSpec;
10265}
10266
10267CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10268 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010269 assert(ClassDecl->needsImplicitMoveConstructor());
10270
Richard Smith8bf22e52012-11-29 01:34:07 +000010271 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10272 if (DSM.isAlreadyBeingDeclared())
10273 return 0;
10274
Sebastian Redl22653ba2011-08-30 19:58:05 +000010275 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10276 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010277
Richard Smithb5800092012-06-10 05:43:50 +000010278 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10279 CXXMoveConstructor,
10280 false);
10281
Sebastian Redl22653ba2011-08-30 19:58:05 +000010282 DeclarationName Name
10283 = Context.DeclarationNames.getCXXConstructorName(
10284 Context.getCanonicalType(ClassType));
10285 SourceLocation ClassLoc = ClassDecl->getLocation();
10286 DeclarationNameInfo NameInfo(Name, ClassLoc);
10287
Richard Smith99005e62013-05-07 03:19:20 +000010288 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000010289 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010290 // member of its class.
10291 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +000010292 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +000010293 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010294 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010295 MoveConstructor->setAccess(AS_public);
10296 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010297
Richard Smithd3b5c9082012-07-27 04:22:15 +000010298 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010299 FunctionProtoType::ExtProtoInfo EPI =
10300 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010301 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010302 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010303
Sebastian Redl22653ba2011-08-30 19:58:05 +000010304 // Add the parameter to the constructor.
10305 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10306 ClassLoc, ClassLoc,
10307 /*IdentifierInfo=*/0,
10308 ArgType, /*TInfo=*/0,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010309 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +000010310 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010311
Richard Smith6b02d462012-12-08 08:32:28 +000010312 MoveConstructor->setTrivial(
10313 ClassDecl->needsOverloadResolutionForMoveConstructor()
10314 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10315 : ClassDecl->hasTrivialMoveConstructor());
10316
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000010317 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010318 ClassDecl->setImplicitMoveConstructorIsDeleted();
10319 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010320 }
10321
10322 // Note that we have declared this constructor.
10323 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10324
10325 if (Scope *S = getScopeForContext(ClassDecl))
10326 PushOnScopeChains(MoveConstructor, S, false);
10327 ClassDecl->addDecl(MoveConstructor);
10328
10329 return MoveConstructor;
10330}
10331
10332void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10333 CXXConstructorDecl *MoveConstructor) {
10334 assert((MoveConstructor->isDefaulted() &&
10335 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010336 !MoveConstructor->doesThisDeclarationHaveABody() &&
10337 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010338 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10339
10340 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10341 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10342
Eli Friedmaneaf34142012-10-18 20:14:08 +000010343 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010344 DiagnosticErrorTrap Trap(Diags);
10345
David Blaikie3fc2f912013-01-17 05:26:25 +000010346 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000010347 Trap.hasErrorOccurred()) {
10348 Diag(CurrentLocation, diag::note_member_synthesized_at)
10349 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10350 MoveConstructor->setInvalidDecl();
10351 } else {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010352 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010353 MoveConstructor->setBody(ActOnCompoundStmt(
10354 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
10355 /*isStmtExpr=*/ false).takeAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010356 }
10357
Eli Friedman276dd182013-09-05 00:02:25 +000010358 MoveConstructor->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010359
10360 if (ASTMutationListener *L = getASTMutationListener()) {
10361 L->CompletedImplicitDefinition(MoveConstructor);
10362 }
10363}
10364
Douglas Gregor74f7d502012-02-15 19:33:52 +000010365bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000010366 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000010367}
Douglas Gregord3b672c2012-02-16 01:06:16 +000010368
10369void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000010370 SourceLocation CurrentLocation,
10371 CXXConversionDecl *Conv) {
10372 CXXRecordDecl *Lambda = Conv->getParent();
10373 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10374 // If we are defining a specialization of a conversion to function-ptr
10375 // cache the deduced template arguments for this specialization
10376 // so that we can use them to retrieve the corresponding call-operator
10377 // and static-invoker.
10378 const TemplateArgumentList *DeducedTemplateArgs = 0;
10379
Douglas Gregor355efbb2012-02-17 03:02:34 +000010380
Faisal Vali571df122013-09-29 08:45:24 +000010381 // Retrieve the corresponding call-operator specialization.
10382 if (Lambda->isGenericLambda()) {
10383 assert(Conv->isFunctionTemplateSpecialization());
10384 FunctionTemplateDecl *CallOpTemplate =
10385 CallOp->getDescribedFunctionTemplate();
10386 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
10387 void *InsertPos = 0;
10388 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10389 DeducedTemplateArgs->data(),
10390 DeducedTemplateArgs->size(),
10391 InsertPos);
10392 assert(CallOpSpec &&
10393 "Conversion operator must have a corresponding call operator");
10394 CallOp = cast<CXXMethodDecl>(CallOpSpec);
10395 }
10396 // Mark the call operator referenced (and add to pending instantiations
10397 // if necessary).
10398 // For both the conversion and static-invoker template specializations
10399 // we construct their body's in this function, so no need to add them
10400 // to the PendingInstantiations.
10401 MarkFunctionReferenced(CurrentLocation, CallOp);
10402
Eli Friedmaneaf34142012-10-18 20:14:08 +000010403 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010404 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000010405
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010406 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000010407 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10408 // ... and get the corresponding specialization for a generic lambda.
10409 if (Lambda->isGenericLambda()) {
10410 assert(DeducedTemplateArgs &&
10411 "Must have deduced template arguments from Conversion Operator");
10412 FunctionTemplateDecl *InvokeTemplate =
10413 Invoker->getDescribedFunctionTemplate();
10414 void *InsertPos = 0;
10415 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10416 DeducedTemplateArgs->data(),
10417 DeducedTemplateArgs->size(),
10418 InsertPos);
10419 assert(InvokeSpec &&
10420 "Must have a corresponding static invoker specialization");
10421 Invoker = cast<CXXMethodDecl>(InvokeSpec);
10422 }
10423 // Construct the body of the conversion function { return __invoke; }.
10424 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
10425 VK_LValue, Conv->getLocation()).take();
10426 assert(FunctionRef && "Can't refer to __invoke function?");
10427 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
10428 Conv->setBody(new (Context) CompoundStmt(Context, Return,
10429 Conv->getLocation(),
10430 Conv->getLocation()));
10431
10432 Conv->markUsed(Context);
10433 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010434
Faisal Vali571df122013-09-29 08:45:24 +000010435 // Fill in the __invoke function with a dummy implementation. IR generation
10436 // will fill in the actual details.
10437 Invoker->markUsed(Context);
10438 Invoker->setReferenced();
10439 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10440
Douglas Gregord3b672c2012-02-16 01:06:16 +000010441 if (ASTMutationListener *L = getASTMutationListener()) {
10442 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000010443 L->CompletedImplicitDefinition(Invoker);
10444 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000010445}
10446
Faisal Vali571df122013-09-29 08:45:24 +000010447
10448
Douglas Gregord3b672c2012-02-16 01:06:16 +000010449void Sema::DefineImplicitLambdaToBlockPointerConversion(
10450 SourceLocation CurrentLocation,
10451 CXXConversionDecl *Conv)
10452{
Faisal Vali850da1a2013-09-29 17:08:32 +000010453 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000010454
Eli Friedman276dd182013-09-05 00:02:25 +000010455 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010456
Eli Friedmaneaf34142012-10-18 20:14:08 +000010457 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010458 DiagnosticErrorTrap Trap(Diags);
10459
Douglas Gregored90df32012-02-22 05:02:47 +000010460 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010461 Expr *This = ActOnCXXThis(CurrentLocation).take();
10462 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010463
Eli Friedman98b01ed2012-03-01 04:01:32 +000010464 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10465 Conv->getLocation(),
10466 Conv, DerefThis);
10467
10468 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10469 // behavior. Note that only the general conversion function does this
10470 // (since it's unusable otherwise); in the case where we inline the
10471 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010472 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000010473 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10474 CK_CopyAndAutoreleaseBlockObject,
10475 BuildBlock.get(), 0, VK_RValue);
10476
10477 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000010478 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000010479 Conv->setInvalidDecl();
10480 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000010481 }
Douglas Gregored90df32012-02-22 05:02:47 +000010482
Douglas Gregored90df32012-02-22 05:02:47 +000010483 // Create the return statement that returns the block from the conversion
10484 // function.
Eli Friedman98b01ed2012-03-01 04:01:32 +000010485 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000010486 if (Return.isInvalid()) {
10487 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10488 Conv->setInvalidDecl();
10489 return;
10490 }
10491
10492 // Set the body of the conversion function.
10493 Stmt *ReturnS = Return.take();
Nico Webera2a0eb92012-12-29 20:03:39 +000010494 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000010495 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000010496 Conv->getLocation()));
10497
Douglas Gregored90df32012-02-22 05:02:47 +000010498 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010499 if (ASTMutationListener *L = getASTMutationListener()) {
10500 L->CompletedImplicitDefinition(Conv);
10501 }
10502}
10503
Douglas Gregord2f70072012-03-10 06:53:13 +000010504/// \brief Determine whether the given list arguments contains exactly one
10505/// "real" (non-default) argument.
10506static bool hasOneRealArgument(MultiExprArg Args) {
10507 switch (Args.size()) {
10508 case 0:
10509 return false;
10510
10511 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010512 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000010513 return false;
10514
10515 // fall through
10516 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010517 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000010518 }
10519
10520 return false;
10521}
10522
John McCalldadc5752010-08-24 06:29:42 +000010523ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010524Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +000010525 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010526 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010527 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010528 bool IsListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010529 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010530 unsigned ConstructKind,
10531 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000010532 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000010533
Douglas Gregor45cf7e32010-04-02 18:24:57 +000010534 // C++0x [class.copy]p34:
10535 // When certain criteria are met, an implementation is allowed to
10536 // omit the copy/move construction of a class object, even if the
10537 // copy/move constructor and/or destructor for the object have
10538 // side effects. [...]
10539 // - when a temporary class object that has not been bound to a
10540 // reference (12.2) would be copied/moved to a class object
10541 // with the same cv-unqualified type, the copy/move operation
10542 // can be omitted by constructing the temporary object
10543 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +000010544 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregord2f70072012-03-10 06:53:13 +000010545 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010546 Expr *SubExpr = ExprArgs[0];
John McCall7a626f62010-09-15 10:14:12 +000010547 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +000010548 }
Mike Stump11289f42009-09-09 15:08:12 +000010549
10550 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010551 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010552 IsListInitialization, RequiresZeroInit,
10553 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000010554}
10555
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010556/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10557/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +000010558ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010559Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10560 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010561 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010562 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010563 bool IsListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010564 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010565 unsigned ConstructKind,
10566 SourceRange ParenRange) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010567 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +000010568 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010569 Constructor, Elidable, ExprArgs,
Richard Smithd59b8322012-12-19 01:39:02 +000010570 HadMultipleCandidates,
10571 IsListInitialization, RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010572 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10573 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010574}
10575
John McCall03c48482010-02-02 09:10:11 +000010576void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000010577 if (VD->isInvalidDecl()) return;
10578
John McCall03c48482010-02-02 09:10:11 +000010579 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000010580 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000010581 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000010582 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000010583
Chandler Carruth86d17d32011-03-27 21:26:48 +000010584 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010585 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000010586 CheckDestructorAccess(VD->getLocation(), Destructor,
10587 PDiag(diag::err_access_dtor_var)
10588 << VD->getDeclName()
10589 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000010590 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000010591
Chandler Carruth86d17d32011-03-27 21:26:48 +000010592 if (!VD->hasGlobalStorage()) return;
10593
10594 // Emit warning for non-trivial dtor in global scope (a real global,
10595 // class-static, function-static).
10596 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10597
10598 // TODO: this should be re-enabled for static locals by !CXAAtExit
10599 if (!VD->isStaticLocal())
10600 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010601}
10602
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010603/// \brief Given a constructor and the set of arguments provided for the
10604/// constructor, convert the arguments and add any required default arguments
10605/// to form a proper call to this constructor.
10606///
10607/// \returns true if an error occurred, false otherwise.
10608bool
10609Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10610 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000010611 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000010612 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010613 bool AllowExplicit,
10614 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010615 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10616 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010617 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010618
10619 const FunctionProtoType *Proto
10620 = Constructor->getType()->getAs<FunctionProtoType>();
10621 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010622 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000010623
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010624 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010625 if (NumArgs < NumParams)
10626 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010627 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010628 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010629
10630 VariadicCallType CallType =
10631 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010632 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010633 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010634 Proto, 0,
10635 llvm::makeArrayRef(Args, NumArgs),
10636 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010637 CallType, AllowExplicit,
10638 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000010639 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000010640
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010641 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010642
Dmitri Gribenko765396f2013-01-13 20:46:02 +000010643 CheckConstructorCall(Constructor,
10644 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10645 AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000010646 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010647
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010648 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000010649}
10650
Anders Carlssone363c8e2009-12-12 00:32:00 +000010651static inline bool
10652CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10653 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000010654 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000010655 if (isa<NamespaceDecl>(DC)) {
10656 return SemaRef.Diag(FnDecl->getLocation(),
10657 diag::err_operator_new_delete_declared_in_namespace)
10658 << FnDecl->getDeclName();
10659 }
10660
10661 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000010662 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010663 return SemaRef.Diag(FnDecl->getLocation(),
10664 diag::err_operator_new_delete_declared_static)
10665 << FnDecl->getDeclName();
10666 }
10667
Anders Carlsson60659a82009-12-12 02:43:16 +000010668 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000010669}
10670
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010671static inline bool
10672CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10673 CanQualType ExpectedResultType,
10674 CanQualType ExpectedFirstParamType,
10675 unsigned DependentParamTypeDiag,
10676 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000010677 QualType ResultType =
10678 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010679
10680 // Check that the result type is not dependent.
10681 if (ResultType->isDependentType())
10682 return SemaRef.Diag(FnDecl->getLocation(),
10683 diag::err_operator_new_delete_dependent_result_type)
10684 << FnDecl->getDeclName() << ExpectedResultType;
10685
10686 // Check that the result type is what we expect.
10687 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10688 return SemaRef.Diag(FnDecl->getLocation(),
10689 diag::err_operator_new_delete_invalid_result_type)
10690 << FnDecl->getDeclName() << ExpectedResultType;
10691
10692 // A function template must have at least 2 parameters.
10693 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10694 return SemaRef.Diag(FnDecl->getLocation(),
10695 diag::err_operator_new_delete_template_too_few_parameters)
10696 << FnDecl->getDeclName();
10697
10698 // The function decl must have at least 1 parameter.
10699 if (FnDecl->getNumParams() == 0)
10700 return SemaRef.Diag(FnDecl->getLocation(),
10701 diag::err_operator_new_delete_too_few_parameters)
10702 << FnDecl->getDeclName();
10703
Sylvestre Ledru830885c2012-07-23 08:59:39 +000010704 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010705 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10706 if (FirstParamType->isDependentType())
10707 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10708 << FnDecl->getDeclName() << ExpectedFirstParamType;
10709
10710 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000010711 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010712 ExpectedFirstParamType)
10713 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10714 << FnDecl->getDeclName() << ExpectedFirstParamType;
10715
10716 return false;
10717}
10718
Anders Carlsson12308f42009-12-11 23:23:22 +000010719static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010720CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010721 // C++ [basic.stc.dynamic.allocation]p1:
10722 // A program is ill-formed if an allocation function is declared in a
10723 // namespace scope other than global scope or declared static in global
10724 // scope.
10725 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10726 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010727
10728 CanQualType SizeTy =
10729 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10730
10731 // C++ [basic.stc.dynamic.allocation]p1:
10732 // The return type shall be void*. The first parameter shall have type
10733 // std::size_t.
10734 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10735 SizeTy,
10736 diag::err_operator_new_dependent_param_type,
10737 diag::err_operator_new_param_type))
10738 return true;
10739
10740 // C++ [basic.stc.dynamic.allocation]p1:
10741 // The first parameter shall not have an associated default argument.
10742 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000010743 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010744 diag::err_operator_new_default_arg)
10745 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10746
10747 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000010748}
10749
10750static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000010751CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000010752 // C++ [basic.stc.dynamic.deallocation]p1:
10753 // A program is ill-formed if deallocation functions are declared in a
10754 // namespace scope other than global scope or declared static in global
10755 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000010756 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10757 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010758
10759 // C++ [basic.stc.dynamic.deallocation]p2:
10760 // Each deallocation function shall return void and its first parameter
10761 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010762 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10763 SemaRef.Context.VoidPtrTy,
10764 diag::err_operator_delete_dependent_param_type,
10765 diag::err_operator_delete_param_type))
10766 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010767
Anders Carlsson12308f42009-12-11 23:23:22 +000010768 return false;
10769}
10770
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010771/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10772/// of this overloaded operator is well-formed. If so, returns false;
10773/// otherwise, emits appropriate diagnostics and returns true.
10774bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000010775 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010776 "Expected an overloaded operator declaration");
10777
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010778 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10779
Mike Stump11289f42009-09-09 15:08:12 +000010780 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010781 // The allocation and deallocation functions, operator new,
10782 // operator new[], operator delete and operator delete[], are
10783 // described completely in 3.7.3. The attributes and restrictions
10784 // found in the rest of this subclause do not apply to them unless
10785 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000010786 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000010787 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000010788
Anders Carlsson22f443f2009-12-12 00:26:23 +000010789 if (Op == OO_New || Op == OO_Array_New)
10790 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010791
10792 // C++ [over.oper]p6:
10793 // An operator function shall either be a non-static member
10794 // function or be a non-member function and have at least one
10795 // parameter whose type is a class, a reference to a class, an
10796 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000010797 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10798 if (MethodDecl->isStatic())
10799 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010800 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010801 } else {
10802 bool ClassOrEnumParam = false;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010803 for (auto Param : FnDecl->params()) {
10804 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000010805 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10806 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010807 ClassOrEnumParam = true;
10808 break;
10809 }
10810 }
10811
Douglas Gregord69246b2008-11-17 16:14:12 +000010812 if (!ClassOrEnumParam)
10813 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000010814 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010815 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010816 }
10817
10818 // C++ [over.oper]p8:
10819 // An operator function cannot have default arguments (8.3.6),
10820 // except where explicitly stated below.
10821 //
Mike Stump11289f42009-09-09 15:08:12 +000010822 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010823 // (C++ [over.call]p1).
10824 if (Op != OO_Call) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010825 for (auto Param : FnDecl->params()) {
10826 if (Param->hasDefaultArg())
10827 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000010828 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000010829 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010830 }
10831 }
10832
Douglas Gregor6cf08062008-11-10 13:38:07 +000010833 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10834 { false, false, false }
10835#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10836 , { Unary, Binary, MemberOnly }
10837#include "clang/Basic/OperatorKinds.def"
10838 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010839
Douglas Gregor6cf08062008-11-10 13:38:07 +000010840 bool CanBeUnaryOperator = OperatorUses[Op][0];
10841 bool CanBeBinaryOperator = OperatorUses[Op][1];
10842 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010843
10844 // C++ [over.oper]p8:
10845 // [...] Operator functions cannot have more or fewer parameters
10846 // than the number required for the corresponding operator, as
10847 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000010848 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000010849 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010850 if (Op != OO_Call &&
10851 ((NumParams == 1 && !CanBeUnaryOperator) ||
10852 (NumParams == 2 && !CanBeBinaryOperator) ||
10853 (NumParams < 1) || (NumParams > 2))) {
10854 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010855 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000010856 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010857 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000010858 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010859 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000010860 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000010861 assert(CanBeBinaryOperator &&
10862 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010863 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000010864 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010865
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010866 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010867 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010868 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000010869
Douglas Gregord69246b2008-11-17 16:14:12 +000010870 // Overloaded operators other than operator() cannot be variadic.
10871 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000010872 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000010873 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010874 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010875 }
10876
10877 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000010878 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10879 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000010880 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010881 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010882 }
10883
10884 // C++ [over.inc]p1:
10885 // The user-defined function called operator++ implements the
10886 // prefix and postfix ++ operator. If this function is a member
10887 // function with no parameters, or a non-member function with one
10888 // parameter of class or enumeration type, it defines the prefix
10889 // increment operator ++ for objects of that type. If the function
10890 // is a member function with one parameter (which shall be of type
10891 // int) or a non-member function with two parameters (the second
10892 // of which shall be of type int), it defines the postfix
10893 // increment operator ++ for objects of that type.
10894 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10895 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000010896 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010897
Richard Smith538b52a2014-01-30 22:24:05 +000010898 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
10899 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000010900 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000010901 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000010902 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010903 }
10904
Douglas Gregord69246b2008-11-17 16:14:12 +000010905 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010906}
Chris Lattner3b024a32008-12-17 07:09:26 +000010907
Alexis Huntc88db062010-01-13 09:01:02 +000010908/// CheckLiteralOperatorDeclaration - Check whether the declaration
10909/// of this literal operator function is well-formed. If so, returns
10910/// false; otherwise, emits appropriate diagnostics and returns true.
10911bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000010912 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000010913 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10914 << FnDecl->getDeclName();
10915 return true;
10916 }
10917
Richard Smith72eebee2012-03-04 09:41:16 +000010918 if (FnDecl->isExternC()) {
10919 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10920 return true;
10921 }
10922
Alexis Huntc88db062010-01-13 09:01:02 +000010923 bool Valid = false;
10924
Richard Smithbcc22fc2012-03-09 08:00:36 +000010925 // This might be the definition of a literal operator template.
10926 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10927 // This might be a specialization of a literal operator template.
10928 if (!TpDecl)
10929 TpDecl = FnDecl->getPrimaryTemplate();
10930
Richard Smithb8b41d32013-10-07 19:57:58 +000010931 // template <char...> type operator "" name() and
10932 // template <class T, T...> type operator "" name() are the only valid
10933 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000010934 if (TpDecl) {
Richard Smith72eebee2012-03-04 09:41:16 +000010935 if (FnDecl->param_size() == 0) {
Richard Smithb8b41d32013-10-07 19:57:58 +000010936 // Must have one or two template parameters
Alexis Hunt7dd26172010-04-07 23:11:06 +000010937 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10938 if (Params->size() == 1) {
10939 NonTypeTemplateParmDecl *PmDecl =
Richard Smithed943022012-08-03 21:14:57 +000010940 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +000010941
Alexis Hunt7dd26172010-04-07 23:11:06 +000010942 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +000010943 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10944 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10945 Valid = true;
Richard Smithb8b41d32013-10-07 19:57:58 +000010946 } else if (Params->size() == 2) {
10947 TemplateTypeParmDecl *PmType =
10948 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
10949 NonTypeTemplateParmDecl *PmArgs =
10950 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
10951
10952 // The second template parameter must be a parameter pack with the
10953 // first template parameter as its type.
10954 if (PmType && PmArgs &&
10955 !PmType->isTemplateParameterPack() &&
10956 PmArgs->isTemplateParameterPack()) {
10957 const TemplateTypeParmType *TArgs =
10958 PmArgs->getType()->getAs<TemplateTypeParmType>();
10959 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
10960 TArgs->getIndex() == PmType->getIndex()) {
10961 Valid = true;
10962 if (ActiveTemplateInstantiations.empty())
10963 Diag(FnDecl->getLocation(),
10964 diag::ext_string_literal_operator_template);
10965 }
10966 }
Alexis Hunt7dd26172010-04-07 23:11:06 +000010967 }
10968 }
Richard Smith72eebee2012-03-04 09:41:16 +000010969 } else if (FnDecl->param_size()) {
Alexis Huntc88db062010-01-13 09:01:02 +000010970 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +000010971 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10972
Richard Smith72eebee2012-03-04 09:41:16 +000010973 QualType T = (*Param)->getType().getUnqualifiedType();
Alexis Huntc88db062010-01-13 09:01:02 +000010974
Alexis Hunt079a6f72010-04-07 22:57:35 +000010975 // unsigned long long int, long double, and any character type are allowed
10976 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +000010977 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10978 Context.hasSameType(T, Context.LongDoubleTy) ||
10979 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000010980 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000010981 Context.hasSameType(T, Context.Char16Ty) ||
10982 Context.hasSameType(T, Context.Char32Ty)) {
10983 if (++Param == FnDecl->param_end())
10984 Valid = true;
10985 goto FinishedParams;
10986 }
10987
Alexis Hunt079a6f72010-04-07 22:57:35 +000010988 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +000010989 const PointerType *PT = T->getAs<PointerType>();
10990 if (!PT)
10991 goto FinishedParams;
10992 T = PT->getPointeeType();
Richard Smith72eebee2012-03-04 09:41:16 +000010993 if (!T.isConstQualified() || T.isVolatileQualified())
Alexis Huntc88db062010-01-13 09:01:02 +000010994 goto FinishedParams;
10995 T = T.getUnqualifiedType();
10996
10997 // Move on to the second parameter;
10998 ++Param;
10999
11000 // If there is no second parameter, the first must be a const char *
11001 if (Param == FnDecl->param_end()) {
11002 if (Context.hasSameType(T, Context.CharTy))
11003 Valid = true;
11004 goto FinishedParams;
11005 }
11006
11007 // const char *, const wchar_t*, const char16_t*, and const char32_t*
11008 // are allowed as the first parameter to a two-parameter function
11009 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011010 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011011 Context.hasSameType(T, Context.Char16Ty) ||
11012 Context.hasSameType(T, Context.Char32Ty)))
11013 goto FinishedParams;
11014
11015 // The second and final parameter must be an std::size_t
11016 T = (*Param)->getType().getUnqualifiedType();
11017 if (Context.hasSameType(T, Context.getSizeType()) &&
11018 ++Param == FnDecl->param_end())
11019 Valid = true;
11020 }
11021
11022 // FIXME: This diagnostic is absolutely terrible.
11023FinishedParams:
11024 if (!Valid) {
11025 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11026 << FnDecl->getDeclName();
11027 return true;
11028 }
11029
Richard Smith768cecc2012-03-09 08:16:22 +000011030 // A parameter-declaration-clause containing a default argument is not
11031 // equivalent to any of the permitted forms.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011032 for (auto Param : FnDecl->params()) {
11033 if (Param->hasDefaultArg()) {
11034 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000011035 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011036 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000011037 break;
11038 }
11039 }
11040
Richard Smith0df56f42012-03-08 02:39:21 +000011041 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000011042 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11043 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000011044 // C++11 [usrlit.suffix]p1:
11045 // Literal suffix identifiers that do not start with an underscore
11046 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000011047 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11048 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000011049 }
Richard Smith0df56f42012-03-08 02:39:21 +000011050
Alexis Huntc88db062010-01-13 09:01:02 +000011051 return false;
11052}
11053
Douglas Gregor07665a62009-01-05 19:45:36 +000011054/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11055/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000011056/// the '{'. ExternLoc is the location of the 'extern', Lang is the
11057/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000011058/// the '{' brace. Otherwise, this linkage specification does not
11059/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000011060Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000011061 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000011062 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011063 StringLiteral *Lit = cast<StringLiteral>(LangStr);
11064 if (!Lit->isAscii()) {
11065 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11066 << LangStr->getSourceRange();
11067 return 0;
11068 }
11069
11070 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000011071 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000011072 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000011073 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000011074 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000011075 Language = LinkageSpecDecl::lang_cxx;
11076 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000011077 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11078 << LangStr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +000011079 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +000011080 }
Mike Stump11289f42009-09-09 15:08:12 +000011081
Chris Lattner438e5012008-12-17 07:13:27 +000011082 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000011083
Richard Smith4ee696d2014-02-17 23:25:27 +000011084 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11085 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000011086 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011087 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000011088 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000011089 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000011090}
11091
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000011092/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000011093/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11094/// valid, it's the position of the closing '}' brace in a linkage
11095/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000011096Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011097 Decl *LinkageSpec,
11098 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011099 if (RBraceLoc.isValid()) {
11100 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11101 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011102 }
Richard Smith4ee696d2014-02-17 23:25:27 +000011103 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000011104 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000011105}
11106
Michael Han84324352013-02-22 17:15:32 +000011107Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11108 AttributeList *AttrList,
11109 SourceLocation SemiLoc) {
11110 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11111 // Attribute declarations appertain to empty declaration so we handle
11112 // them here.
11113 if (AttrList)
11114 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000011115
Michael Han84324352013-02-22 17:15:32 +000011116 CurContext->addDecl(ED);
11117 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000011118}
11119
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011120/// \brief Perform semantic analysis for the variable declaration that
11121/// occurs within a C++ catch clause, returning the newly-created
11122/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011123VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000011124 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011125 SourceLocation StartLoc,
11126 SourceLocation Loc,
11127 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011128 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011129 QualType ExDeclType = TInfo->getType();
11130
Sebastian Redl54c04d42008-12-22 19:15:10 +000011131 // Arrays and functions decay.
11132 if (ExDeclType->isArrayType())
11133 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11134 else if (ExDeclType->isFunctionType())
11135 ExDeclType = Context.getPointerType(ExDeclType);
11136
11137 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11138 // The exception-declaration shall not denote a pointer or reference to an
11139 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000011140 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000011141 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011142 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000011143 Invalid = true;
11144 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011145
Sebastian Redl54c04d42008-12-22 19:15:10 +000011146 QualType BaseType = ExDeclType;
11147 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000011148 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011149 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011150 BaseType = Ptr->getPointeeType();
11151 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011152 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000011153 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000011154 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011155 BaseType = Ref->getPointeeType();
11156 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011157 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011158 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000011159 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011160 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000011161 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011162
Mike Stump11289f42009-09-09 15:08:12 +000011163 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011164 RequireNonAbstractType(Loc, ExDeclType,
11165 diag::err_abstract_type_in_decl,
11166 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000011167 Invalid = true;
11168
John McCall2ca705e2010-07-24 00:37:23 +000011169 // Only the non-fragile NeXT runtime currently supports C++ catches
11170 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011171 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000011172 QualType T = ExDeclType;
11173 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11174 T = RT->getPointeeType();
11175
11176 if (T->isObjCObjectType()) {
11177 Diag(Loc, diag::err_objc_object_catch);
11178 Invalid = true;
11179 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000011180 // FIXME: should this be a test for macosx-fragile specifically?
11181 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000011182 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000011183 }
11184 }
11185
Abramo Bagnaradff19302011-03-08 08:55:46 +000011186 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000011187 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000011188 ExDecl->setExceptionVariable(true);
11189
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011190 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011191 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011192 Invalid = true;
11193
Douglas Gregor750734c2011-07-06 18:14:43 +000011194 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000011195 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000011196 // Insulate this from anything else we might currently be parsing.
11197 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11198
Douglas Gregor6de584c2010-03-05 23:38:39 +000011199 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000011200 // The object declared in an exception-declaration or, if the
11201 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000011202 // copy-initialized (8.5) from the exception object. [...]
11203 // The object is destroyed when the handler exits, after the destruction
11204 // of any automatic objects initialized within the handler.
11205 //
Nick Lewycky0f292892013-09-22 10:06:57 +000011206 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000011207 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +000011208 QualType initType = ExDeclType;
11209
11210 InitializedEntity entity =
11211 InitializedEntity::InitializeVariable(ExDecl);
11212 InitializationKind initKind =
11213 InitializationKind::CreateCopy(Loc, SourceLocation());
11214
11215 Expr *opaqueValue =
11216 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000011217 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11218 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000011219 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000011220 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000011221 else {
11222 // If the constructor used was non-trivial, set this as the
11223 // "initializer".
Nick Lewycky0f292892013-09-22 10:06:57 +000011224 CXXConstructExpr *construct = result.takeAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000011225 if (!construct->getConstructor()->isTrivial()) {
11226 Expr *init = MaybeCreateExprWithCleanups(construct);
11227 ExDecl->setInit(init);
11228 }
11229
11230 // And make sure it's destructable.
11231 FinalizeVarWithDestructor(ExDecl, recordType);
11232 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000011233 }
11234 }
11235
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011236 if (Invalid)
11237 ExDecl->setInvalidDecl();
11238
11239 return ExDecl;
11240}
11241
11242/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11243/// handler.
John McCall48871652010-08-21 09:40:31 +000011244Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000011245 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000011246 bool Invalid = D.isInvalidType();
11247
11248 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000011249 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11250 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000011251 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11252 D.getIdentifierLoc());
11253 Invalid = true;
11254 }
11255
Sebastian Redl54c04d42008-12-22 19:15:10 +000011256 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011257 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000011258 LookupOrdinaryName,
11259 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011260 // The scope should be freshly made just for us. There is just no way
11261 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +000011262 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +000011263 if (PrevDecl->isTemplateParameter()) {
11264 // Maybe we will complain about the shadowed template parameter.
11265 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorf4ef4d22011-10-20 17:58:49 +000011266 PrevDecl = 0;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011267 }
11268 }
11269
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011270 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011271 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11272 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011273 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011274 }
11275
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011276 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011277 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011278 D.getIdentifierLoc(),
11279 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011280 if (Invalid)
11281 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000011282
Sebastian Redl54c04d42008-12-22 19:15:10 +000011283 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011284 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011285 PushOnScopeChains(ExDecl, S);
11286 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011287 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011288
Douglas Gregor758a8692009-06-17 21:51:59 +000011289 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000011290 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011291}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011292
Abramo Bagnaraea947882011-03-08 16:41:52 +000011293Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000011294 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000011295 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000011296 SourceLocation RParenLoc) {
Richard Smithded9c2e2012-07-11 22:37:56 +000011297 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011298
Richard Smithded9c2e2012-07-11 22:37:56 +000011299 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11300 return 0;
11301
11302 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11303 AssertMessage, RParenLoc, false);
11304}
11305
11306Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11307 Expr *AssertExpr,
11308 StringLiteral *AssertMessage,
11309 SourceLocation RParenLoc,
11310 bool Failed) {
11311 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11312 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000011313 // In a static_assert-declaration, the constant-expression shall be a
11314 // constant expression that can be contextually converted to bool.
11315 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11316 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011317 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000011318
Richard Smith902ca212011-12-14 23:32:26 +000011319 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000011320 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000011321 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000011322 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011323 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011324
Richard Smithded9c2e2012-07-11 22:37:56 +000011325 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011326 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000011327 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith235341b2012-08-16 03:56:14 +000011328 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000011329 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smithf506eaf2012-03-05 23:20:05 +000011330 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000011331 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000011332 }
Anders Carlsson54b26982009-03-14 00:33:21 +000011333 }
Mike Stump11289f42009-09-09 15:08:12 +000011334
Abramo Bagnaraea947882011-03-08 16:41:52 +000011335 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000011336 AssertExpr, AssertMessage, RParenLoc,
11337 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000011338
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011339 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000011340 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011341}
Sebastian Redlf769df52009-03-24 22:27:57 +000011342
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011343/// \brief Perform semantic analysis of the given friend type declaration.
11344///
11345/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000011346FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000011347 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011348 TypeSourceInfo *TSInfo) {
11349 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11350
11351 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000011352 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011353
Richard Smithc8239732011-10-18 21:39:00 +000011354 // C++03 [class.friend]p2:
11355 // An elaborated-type-specifier shall be used in a friend declaration
11356 // for a class.*
11357 //
11358 // * The class-key of the elaborated-type-specifier is required.
11359 if (!ActiveTemplateInstantiations.empty()) {
11360 // Do not complain about the form of friend template types during
11361 // template instantiation; we will already have complained when the
11362 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000011363 } else {
11364 if (!T->isElaboratedTypeSpecifier()) {
11365 // If we evaluated the type to a record type, suggest putting
11366 // a tag in front.
11367 if (const RecordType *RT = T->getAs<RecordType>()) {
11368 RecordDecl *RD = RT->getDecl();
Richard Smithc8239732011-10-18 21:39:00 +000011369
Nick Lewycky36722d22013-02-06 05:59:33 +000011370 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smithc8239732011-10-18 21:39:00 +000011371
Nick Lewycky36722d22013-02-06 05:59:33 +000011372 Diag(TypeRange.getBegin(),
11373 getLangOpts().CPlusPlus11 ?
11374 diag::warn_cxx98_compat_unelaborated_friend_type :
11375 diag::ext_unelaborated_friend_type)
11376 << (unsigned) RD->getTagKind()
11377 << T
11378 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11379 InsertionText);
11380 } else {
11381 Diag(FriendLoc,
11382 getLangOpts().CPlusPlus11 ?
11383 diag::warn_cxx98_compat_nonclass_type_friend :
11384 diag::ext_nonclass_type_friend)
11385 << T
11386 << TypeRange;
11387 }
11388 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000011389 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011390 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000011391 diag::warn_cxx98_compat_enum_friend :
11392 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011393 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000011394 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011395 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011396
Nick Lewycky36722d22013-02-06 05:59:33 +000011397 // C++11 [class.friend]p3:
11398 // A friend declaration that does not declare a function shall have one
11399 // of the following forms:
11400 // friend elaborated-type-specifier ;
11401 // friend simple-type-specifier ;
11402 // friend typename-specifier ;
11403 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11404 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11405 }
Richard Smitha31a89a2012-09-20 01:31:00 +000011406
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011407 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000011408 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011409 // the friend declaration is ignored.
Richard Smitha31a89a2012-09-20 01:31:00 +000011410 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011411}
11412
John McCallace48cd2010-10-19 01:40:49 +000011413/// Handle a friend tag declaration where the scope specifier was
11414/// templated.
11415Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11416 unsigned TagSpec, SourceLocation TagLoc,
11417 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011418 IdentifierInfo *Name,
11419 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000011420 AttributeList *Attr,
11421 MultiTemplateParamsArg TempParamLists) {
11422 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11423
11424 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000011425 bool Invalid = false;
11426
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011427 if (TemplateParameterList *TemplateParams =
11428 MatchTemplateParametersToScopeSpecifier(
11429 TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true,
11430 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000011431 if (TemplateParams->size() > 0) {
11432 // This is a declaration of a class template.
11433 if (Invalid)
11434 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000011435
Eric Christopher6f228b52011-07-21 05:34:24 +000011436 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11437 SS, Name, NameLoc, Attr,
11438 TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000011439 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher6f228b52011-07-21 05:34:24 +000011440 TempParamLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011441 TempParamLists.data()).take();
John McCallace48cd2010-10-19 01:40:49 +000011442 } else {
11443 // The "template<>" header is extraneous.
11444 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11445 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11446 isExplicitSpecialization = true;
11447 }
11448 }
11449
11450 if (Invalid) return 0;
11451
John McCallace48cd2010-10-19 01:40:49 +000011452 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000011453 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011454 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000011455 isAllExplicitSpecializations = false;
11456 break;
11457 }
11458 }
11459
11460 // FIXME: don't ignore attributes.
11461
11462 // If it's explicit specializations all the way down, just forget
11463 // about the template header and build an appropriate non-templated
11464 // friend. TODO: for source fidelity, remember the headers.
11465 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011466 if (SS.isEmpty()) {
11467 bool Owned = false;
11468 bool IsDependent = false;
11469 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000011470 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011471 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000011472 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000011473 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011474 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000011475 /*UnderlyingType=*/TypeResult(),
11476 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011477 }
Richard Smith649c7b062014-01-08 00:56:48 +000011478
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011479 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000011480 ElaboratedTypeKeyword Keyword
11481 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011482 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000011483 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011484 if (T.isNull())
11485 return 0;
11486
11487 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11488 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000011489 DependentNameTypeLoc TL =
11490 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011491 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011492 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000011493 TL.setNameLoc(NameLoc);
11494 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000011495 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011496 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000011497 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000011498 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011499 }
11500
11501 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011502 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011503 Friend->setAccess(AS_public);
11504 CurContext->addDecl(Friend);
11505 return Friend;
11506 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011507
11508 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11509
11510
John McCallace48cd2010-10-19 01:40:49 +000011511
11512 // Handle the case of a templated-scope friend class. e.g.
11513 // template <class T> class A<T>::B;
11514 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000011515 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
11516 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000011517 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11518 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11519 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000011520 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011521 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011522 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000011523 TL.setNameLoc(NameLoc);
11524
11525 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011526 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011527 Friend->setAccess(AS_public);
11528 Friend->setUnsupportedFriend(true);
11529 CurContext->addDecl(Friend);
11530 return Friend;
11531}
11532
11533
John McCall11083da2009-09-16 22:47:08 +000011534/// Handle a friend type declaration. This works in tandem with
11535/// ActOnTag.
11536///
11537/// Notes on friend class templates:
11538///
11539/// We generally treat friend class declarations as if they were
11540/// declaring a class. So, for example, the elaborated type specifier
11541/// in a friend declaration is required to obey the restrictions of a
11542/// class-head (i.e. no typedefs in the scope chain), template
11543/// parameters are required to match up with simple template-ids, &c.
11544/// However, unlike when declaring a template specialization, it's
11545/// okay to refer to a template specialization without an empty
11546/// template parameter declaration, e.g.
11547/// friend class A<T>::B<unsigned>;
11548/// We permit this as a special case; if there are any template
11549/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000011550/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000011551Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000011552 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011553 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000011554
11555 assert(DS.isFriendSpecified());
11556 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11557
John McCall11083da2009-09-16 22:47:08 +000011558 // Try to convert the decl specifier to a type. This works for
11559 // friend templates because ActOnTag never produces a ClassTemplateDecl
11560 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000011561 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000011562 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11563 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000011564 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +000011565 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011566
Douglas Gregor6c110f32010-12-16 01:14:37 +000011567 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11568 return 0;
11569
John McCall11083da2009-09-16 22:47:08 +000011570 // This is definitely an error in C++98. It's probably meant to
11571 // be forbidden in C++0x, too, but the specification is just
11572 // poorly written.
11573 //
11574 // The problem is with declarations like the following:
11575 // template <T> friend A<T>::foo;
11576 // where deciding whether a class C is a friend or not now hinges
11577 // on whether there exists an instantiation of A that causes
11578 // 'foo' to equal C. There are restrictions on class-heads
11579 // (which we declare (by fiat) elaborated friend declarations to
11580 // be) that makes this tractable.
11581 //
11582 // FIXME: handle "template <> friend class A<T>;", which
11583 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000011584 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000011585 Diag(Loc, diag::err_tagless_friend_type_template)
11586 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +000011587 return 0;
John McCall11083da2009-09-16 22:47:08 +000011588 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011589
John McCallaa74a0c2009-08-28 07:59:38 +000011590 // C++98 [class.friend]p1: A friend of a class is a function
11591 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000011592 // This is fixed in DR77, which just barely didn't make the C++03
11593 // deadline. It's also a very silly restriction that seriously
11594 // affects inner classes and which nobody else seems to implement;
11595 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000011596 //
11597 // But note that we could warn about it: it's always useless to
11598 // friend one of your own members (it's not, however, worthless to
11599 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000011600
John McCall11083da2009-09-16 22:47:08 +000011601 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011602 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000011603 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011604 NumTempParamLists,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011605 TempParams.data(),
John McCall15ad0962010-03-25 18:04:51 +000011606 TSI,
John McCall11083da2009-09-16 22:47:08 +000011607 DS.getFriendSpecLoc());
11608 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000011609 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011610
11611 if (!D)
John McCall48871652010-08-21 09:40:31 +000011612 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011613
John McCall11083da2009-09-16 22:47:08 +000011614 D->setAccess(AS_public);
11615 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000011616
John McCall48871652010-08-21 09:40:31 +000011617 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000011618}
11619
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000011620NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11621 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000011622 const DeclSpec &DS = D.getDeclSpec();
11623
11624 assert(DS.isFriendSpecified());
11625 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11626
11627 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000011628 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000011629
11630 // C++ [class.friend]p1
11631 // A friend of a class is a function or class....
11632 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000011633 // It *doesn't* see through dependent types, which is correct
11634 // according to [temp.arg.type]p3:
11635 // If a declaration acquires a function type through a
11636 // type dependent on a template-parameter and this causes
11637 // a declaration that does not use the syntactic form of a
11638 // function declarator to have a function type, the program
11639 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011640 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000011641 Diag(Loc, diag::err_unexpected_friend);
11642
11643 // It might be worthwhile to try to recover by creating an
11644 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +000011645 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011646 }
11647
11648 // C++ [namespace.memdef]p3
11649 // - If a friend declaration in a non-local class first declares a
11650 // class or function, the friend class or function is a member
11651 // of the innermost enclosing namespace.
11652 // - The name of the friend is not found by simple name lookup
11653 // until a matching declaration is provided in that namespace
11654 // scope (either before or after the class declaration granting
11655 // friendship).
11656 // - If a friend function is called, its name may be found by the
11657 // name lookup that considers functions from namespaces and
11658 // classes associated with the types of the function arguments.
11659 // - When looking for a prior declaration of a class or a function
11660 // declared as a friend, scopes outside the innermost enclosing
11661 // namespace scope are not considered.
11662
John McCallde3fd222010-10-12 23:13:28 +000011663 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011664 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11665 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000011666 assert(Name);
11667
Douglas Gregor6c110f32010-12-16 01:14:37 +000011668 // Check for unexpanded parameter packs.
11669 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11670 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11671 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11672 return 0;
11673
John McCall07e91c02009-08-06 02:15:43 +000011674 // The context we found the declaration in, or in which we should
11675 // create the declaration.
11676 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000011677 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011678 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000011679 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000011680
Richard Smith114394f2013-08-09 04:35:01 +000011681 // There are five cases here.
11682 // - There's no scope specifier and we're in a local class. Only look
11683 // for functions declared in the immediately-enclosing block scope.
11684 // We recover from invalid scope qualifiers as if they just weren't there.
11685 FunctionDecl *FunctionContainingLocalClass = 0;
11686 if ((SS.isInvalid() || !SS.isSet()) &&
11687 (FunctionContainingLocalClass =
11688 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11689 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000011690 // If a friend declaration appears in a local class and the name
11691 // specified is an unqualified name, a prior declaration is
11692 // looked up without considering scopes that are outside the
11693 // innermost enclosing non-class scope. For a friend function
11694 // declaration, if there is no prior declaration, the program is
11695 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000011696
11697 // Find the innermost enclosing non-class scope. This is the block
11698 // scope containing the local class definition (or for a nested class,
11699 // the outer local class).
11700 DCScope = S->getFnParent();
11701
11702 // Look up the function name in the scope.
11703 Previous.clear(LookupLocalFriendName);
11704 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11705
11706 if (!Previous.empty()) {
11707 // All possible previous declarations must have the same context:
11708 // either they were declared at block scope or they are members of
11709 // one of the enclosing local classes.
11710 DC = Previous.getRepresentativeDecl()->getDeclContext();
11711 } else {
11712 // This is ill-formed, but provide the context that we would have
11713 // declared the function in, if we were permitted to, for error recovery.
11714 DC = FunctionContainingLocalClass;
11715 }
Richard Smith541b38b2013-09-20 01:15:31 +000011716 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000011717
11718 // C++ [class.friend]p6:
11719 // A function can be defined in a friend declaration of a class if and
11720 // only if the class is a non-local class (9.8), the function name is
11721 // unqualified, and the function has namespace scope.
11722 if (D.isFunctionDefinition()) {
11723 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11724 }
11725
11726 // - There's no scope specifier, in which case we just go to the
11727 // appropriate scope and look for a function or function template
11728 // there as appropriate.
11729 } else if (SS.isInvalid() || !SS.isSet()) {
11730 // C++11 [namespace.memdef]p3:
11731 // If the name in a friend declaration is neither qualified nor
11732 // a template-id and the declaration is a function or an
11733 // elaborated-type-specifier, the lookup to determine whether
11734 // the entity has been previously declared shall not consider
11735 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000011736 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000011737
John McCallf7cfb222010-10-13 05:45:15 +000011738 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000011739 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000011740
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011741 // Skip class contexts. If someone can cite chapter and verse
11742 // for this behavior, that would be nice --- it's what GCC and
11743 // EDG do, and it seems like a reasonable intent, but the spec
11744 // really only says that checks for unqualified existing
11745 // declarations should stop at the nearest enclosing namespace,
11746 // not that they should only consider the nearest enclosing
11747 // namespace.
11748 while (DC->isRecord())
11749 DC = DC->getParent();
11750
11751 DeclContext *LookupDC = DC;
11752 while (LookupDC->isTransparentContext())
11753 LookupDC = LookupDC->getParent();
11754
11755 while (true) {
11756 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000011757
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011758 if (!Previous.empty()) {
11759 DC = LookupDC;
11760 break;
John McCallf4776592010-10-14 22:22:28 +000011761 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011762
11763 if (isTemplateId) {
11764 if (isa<TranslationUnitDecl>(LookupDC)) break;
11765 } else {
11766 if (LookupDC->isFileContext()) break;
11767 }
11768 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000011769 }
11770
John McCallccbc0322010-10-13 06:22:15 +000011771 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000011772
John McCallde3fd222010-10-12 23:13:28 +000011773 // - There's a non-dependent scope specifier, in which case we
11774 // compute it and do a previous lookup there for a function
11775 // or function template.
11776 } else if (!SS.getScopeRep()->isDependent()) {
11777 DC = computeDeclContext(SS);
11778 if (!DC) return 0;
11779
11780 if (RequireCompleteDeclContext(SS, DC)) return 0;
11781
11782 LookupQualifiedName(Previous, DC);
11783
11784 // Ignore things found implicitly in the wrong scope.
11785 // TODO: better diagnostics for this case. Suggesting the right
11786 // qualified scope would be nice...
11787 LookupResult::Filter F = Previous.makeFilter();
11788 while (F.hasNext()) {
11789 NamedDecl *D = F.next();
11790 if (!DC->InEnclosingNamespaceSetOf(
11791 D->getDeclContext()->getRedeclContext()))
11792 F.erase();
11793 }
11794 F.done();
11795
11796 if (Previous.empty()) {
11797 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011798 Diag(Loc, diag::err_qualified_friend_not_found)
11799 << Name << TInfo->getType();
John McCallde3fd222010-10-12 23:13:28 +000011800 return 0;
11801 }
11802
11803 // C++ [class.friend]p1: A friend of a class is a function or
11804 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000011805 if (DC->Equals(CurContext))
11806 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011807 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000011808 diag::warn_cxx98_compat_friend_is_member :
11809 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000011810
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011811 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000011812 // C++ [class.friend]p6:
11813 // A function can be defined in a friend declaration of a class if and
11814 // only if the class is a non-local class (9.8), the function name is
11815 // unqualified, and the function has namespace scope.
11816 SemaDiagnosticBuilder DB
11817 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11818
11819 DB << SS.getScopeRep();
11820 if (DC->isFileContext())
11821 DB << FixItHint::CreateRemoval(SS.getRange());
11822 SS.clear();
11823 }
John McCallde3fd222010-10-12 23:13:28 +000011824
11825 // - There's a scope specifier that does not match any template
11826 // parameter lists, in which case we use some arbitrary context,
11827 // create a method or method template, and wait for instantiation.
11828 // - There's a scope specifier that does match some template
11829 // parameter lists, which we don't handle right now.
11830 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011831 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000011832 // C++ [class.friend]p6:
11833 // A function can be defined in a friend declaration of a class if and
11834 // only if the class is a non-local class (9.8), the function name is
11835 // unqualified, and the function has namespace scope.
11836 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11837 << SS.getScopeRep();
11838 }
11839
John McCallde3fd222010-10-12 23:13:28 +000011840 DC = CurContext;
11841 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000011842 }
Douglas Gregor16e65612011-10-10 01:11:59 +000011843
John McCallf7cfb222010-10-13 05:45:15 +000011844 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000011845 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000011846 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11847 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11848 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000011849 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000011850 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11851 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +000011852 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011853 }
John McCall07e91c02009-08-06 02:15:43 +000011854 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011855
Douglas Gregordd847ba2011-11-03 16:37:14 +000011856 // FIXME: This is an egregious hack to cope with cases where the scope stack
11857 // does not contain the declaration context, i.e., in an out-of-line
11858 // definition of a class.
11859 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11860 if (!DCScope) {
11861 FakeDCScope.setEntity(DC);
11862 DCScope = &FakeDCScope;
11863 }
Richard Smith114394f2013-08-09 04:35:01 +000011864
Francois Pichet00c7e6c2011-08-14 03:52:19 +000011865 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011866 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011867 TemplateParams, AddToScope);
John McCall48871652010-08-21 09:40:31 +000011868 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +000011869
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011870 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000011871
Richard Smith114394f2013-08-09 04:35:01 +000011872 // If we performed typo correction, we might have added a scope specifier
11873 // and changed the decl context.
11874 DC = ND->getDeclContext();
11875
John McCall759e32b2009-08-31 22:39:49 +000011876 // Add the function declaration to the appropriate lookup tables,
11877 // adjusting the redeclarations list as necessary. We don't
11878 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000011879 //
John McCall759e32b2009-08-31 22:39:49 +000011880 // Also update the scope-based lookup if the target context's
11881 // lookup context is in lexical scope.
11882 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000011883 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000011884 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000011885 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011886 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000011887 }
John McCallaa74a0c2009-08-28 07:59:38 +000011888
11889 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011890 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000011891 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000011892 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000011893 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000011894
John McCalla0a96892012-08-10 03:15:35 +000011895 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000011896 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000011897 } else {
11898 if (DC->isRecord()) CheckFriendAccess(ND);
11899
John McCall2c2eb122010-10-16 06:59:13 +000011900 FunctionDecl *FD;
11901 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11902 FD = FTD->getTemplatedDecl();
11903 else
11904 FD = cast<FunctionDecl>(ND);
11905
David Majnemer502b0ed2013-06-25 23:09:30 +000011906 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11907 // default argument expression, that declaration shall be a definition
11908 // and shall be the only declaration of the function or function
11909 // template in the translation unit.
11910 if (functionDeclHasDefaultArgument(FD)) {
11911 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11912 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11913 Diag(OldFD->getLocation(), diag::note_previous_declaration);
11914 } else if (!D.isFunctionDefinition())
11915 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11916 }
11917
John McCall2c2eb122010-10-16 06:59:13 +000011918 // Mark templated-scope function declarations as unsupported.
11919 if (FD->getNumTemplateParameterLists())
11920 FrD->setUnsupportedFriend(true);
11921 }
John McCallde3fd222010-10-12 23:13:28 +000011922
John McCall48871652010-08-21 09:40:31 +000011923 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000011924}
11925
John McCall48871652010-08-21 09:40:31 +000011926void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11927 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000011928
Aaron Ballmanf96361e2013-01-16 23:39:10 +000011929 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000011930 if (!Fn) {
11931 Diag(DelLoc, diag::err_deleted_non_function);
11932 return;
11933 }
Richard Smithb4d2a152013-04-02 19:38:47 +000011934
Douglas Gregorec9fd132012-01-14 16:38:05 +000011935 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000011936 // Don't consider the implicit declaration we generate for explicit
11937 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000011938 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
11939 Prev->getPreviousDecl()) &&
11940 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000011941 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000011942 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
11943 Prev->isImplicit() ? diag::note_previous_implicit_declaration
11944 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000011945 }
Sebastian Redlf769df52009-03-24 22:27:57 +000011946 // If the declaration wasn't the first, we delete the function anyway for
11947 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000011948 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000011949 }
Richard Smithb4d2a152013-04-02 19:38:47 +000011950
11951 if (Fn->isDeleted())
11952 return;
11953
11954 // See if we're deleting a function which is already known to override a
11955 // non-deleted virtual function.
11956 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11957 bool IssuedDiagnostic = false;
11958 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11959 E = MD->end_overridden_methods();
11960 I != E; ++I) {
11961 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11962 if (!IssuedDiagnostic) {
11963 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11964 IssuedDiagnostic = true;
11965 }
11966 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11967 }
11968 }
11969 }
11970
Richard Smithb63b6ee2014-01-22 01:43:19 +000011971 // C++11 [basic.start.main]p3:
11972 // A program that defines main as deleted [...] is ill-formed.
11973 if (Fn->isMain())
11974 Diag(DelLoc, diag::err_deleted_main);
11975
Alexis Hunt4a8ea102011-05-06 20:44:56 +000011976 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000011977}
Sebastian Redl4c018662009-04-27 21:33:24 +000011978
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011979void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000011980 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011981
11982 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000011983 if (MD->getParent()->isDependentType()) {
11984 MD->setDefaulted();
11985 MD->setExplicitlyDefaulted();
11986 return;
11987 }
11988
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011989 CXXSpecialMember Member = getSpecialMember(MD);
11990 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000011991 if (!MD->isInvalidDecl())
11992 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011993 return;
11994 }
11995
11996 MD->setDefaulted();
11997 MD->setExplicitlyDefaulted();
11998
Alexis Hunt61ae8d32011-05-23 23:14:04 +000011999 // If this definition appears within the record, do the checking when
12000 // the record is complete.
12001 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000012002 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012003 // Find the uninstantiated declaration that actually had the '= default'
12004 // on it.
Richard Smith802c4b72012-08-23 06:16:52 +000012005 Pattern->isDefined(Primary);
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012006
Richard Smith3901dfe2013-03-27 00:22:47 +000012007 // If the method was defaulted on its first declaration, we will have
12008 // already performed the checking in CheckCompletedCXXClass. Such a
12009 // declaration doesn't trigger an implicit definition.
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012010 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012011 return;
12012
Richard Smithd3b5c9082012-07-27 04:22:15 +000012013 CheckExplicitlyDefaultedSpecialMember(MD);
12014
Richard Smithbd305122012-12-11 01:14:52 +000012015 // The exception specification is needed because we are defining the
12016 // function.
12017 ResolveExceptionSpec(DefaultLoc,
12018 MD->getType()->castAs<FunctionProtoType>());
12019
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012020 if (MD->isInvalidDecl())
12021 return;
12022
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012023 switch (Member) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012024 case CXXDefaultConstructor:
12025 DefineImplicitDefaultConstructor(DefaultLoc,
12026 cast<CXXConstructorDecl>(MD));
Alexis Hunt913820d2011-05-13 06:10:58 +000012027 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012028 case CXXCopyConstructor:
12029 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012030 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012031 case CXXCopyAssignment:
12032 DefineImplicitCopyAssignment(DefaultLoc, MD);
Alexis Huntc9a55732011-05-14 05:23:28 +000012033 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012034 case CXXDestructor:
12035 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Alexis Huntf91729462011-05-12 22:46:25 +000012036 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012037 case CXXMoveConstructor:
12038 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt119c10e2011-05-25 23:16:36 +000012039 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012040 case CXXMoveAssignment:
12041 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012042 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000012043 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000012044 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012045 }
12046 } else {
12047 Diag(DefaultLoc, diag::err_default_special_members);
12048 }
12049}
12050
Sebastian Redl4c018662009-04-27 21:33:24 +000012051static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000012052 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000012053 Stmt *SubStmt = *CI;
12054 if (!SubStmt)
12055 continue;
12056 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012057 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000012058 diag::err_return_in_constructor_handler);
12059 if (!isa<Expr>(SubStmt))
12060 SearchForReturnInStmt(Self, SubStmt);
12061 }
12062}
12063
12064void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12065 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12066 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12067 SearchForReturnInStmt(*this, Handler);
12068 }
12069}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012070
David Blaikie68f71a32013-01-18 23:03:15 +000012071bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000012072 const CXXMethodDecl *Old) {
12073 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12074 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12075
12076 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12077
12078 // If the calling conventions match, everything is fine
12079 if (NewCC == OldCC)
12080 return false;
12081
Hans Wennborg2545efe2013-12-11 17:42:11 +000012082 // If the calling conventions mismatch because the new function is static,
12083 // suppress the calling convention mismatch error; the error about static
12084 // function override (err_static_overrides_virtual from
12085 // Sema::CheckFunctionDeclaration) is more clear.
12086 if (New->getStorageClass() == SC_Static)
12087 return false;
12088
Reid Kleckner78af0702013-08-27 23:08:25 +000012089 Diag(New->getLocation(),
12090 diag::err_conflicting_overriding_cc_attributes)
12091 << New->getDeclName() << New->getType() << Old->getType();
12092 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12093 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000012094}
12095
Mike Stump11289f42009-09-09 15:08:12 +000012096bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012097 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000012098 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12099 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012100
Chandler Carruth284bb2e2010-02-15 11:53:20 +000012101 if (Context.hasSameType(NewTy, OldTy) ||
12102 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012103 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012104
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012105 // Check if the return types are covariant
12106 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000012107
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012108 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012109 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12110 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012111 NewClassTy = NewPT->getPointeeType();
12112 OldClassTy = OldPT->getPointeeType();
12113 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012114 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12115 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12116 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12117 NewClassTy = NewRT->getPointeeType();
12118 OldClassTy = OldRT->getPointeeType();
12119 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012120 }
12121 }
Mike Stump11289f42009-09-09 15:08:12 +000012122
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012123 // The return types aren't either both pointers or references to a class type.
12124 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000012125 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012126 diag::err_different_return_type_for_overriding_virtual_function)
12127 << New->getDeclName() << NewTy << OldTy;
12128 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +000012129
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012130 return true;
12131 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012132
Anders Carlssone60365b2009-12-31 18:34:24 +000012133 // C++ [class.virtual]p6:
12134 // If the return type of D::f differs from the return type of B::f, the
12135 // class type in the return type of D::f shall be complete at the point of
12136 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012137 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12138 if (!RT->isBeingDefined() &&
12139 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012140 diag::err_covariant_return_incomplete,
12141 New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000012142 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012143 }
Anders Carlssone60365b2009-12-31 18:34:24 +000012144
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000012145 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012146 // Check if the new class derives from the old class.
12147 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12148 Diag(New->getLocation(),
12149 diag::err_covariant_return_not_derived)
12150 << New->getDeclName() << NewTy << OldTy;
12151 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12152 return true;
12153 }
Mike Stump11289f42009-09-09 15:08:12 +000012154
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012155 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +000012156 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +000012157 diag::err_covariant_return_inaccessible_base,
12158 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12159 // FIXME: Should this point to the return type?
12160 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +000012161 // FIXME: this note won't trigger for delayed access control
12162 // diagnostics, and it's impossible to get an undelayed error
12163 // here from access control during the original parse because
12164 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012165 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12166 return true;
12167 }
12168 }
Mike Stump11289f42009-09-09 15:08:12 +000012169
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012170 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012171 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012172 Diag(New->getLocation(),
12173 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012174 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012175 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12176 return true;
12177 };
Mike Stump11289f42009-09-09 15:08:12 +000012178
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012179
12180 // The new class type must have the same or less qualifiers as the old type.
12181 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12182 Diag(New->getLocation(),
12183 diag::err_covariant_return_type_class_type_more_qualified)
12184 << New->getDeclName() << NewTy << OldTy;
12185 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12186 return true;
12187 };
Mike Stump11289f42009-09-09 15:08:12 +000012188
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012189 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012190}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012191
Douglas Gregor21920e372009-12-01 17:24:26 +000012192/// \brief Mark the given method pure.
12193///
12194/// \param Method the method to be marked pure.
12195///
12196/// \param InitRange the source range that covers the "0" initializer.
12197bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012198 SourceLocation EndLoc = InitRange.getEnd();
12199 if (EndLoc.isValid())
12200 Method->setRangeEnd(EndLoc);
12201
Douglas Gregor21920e372009-12-01 17:24:26 +000012202 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12203 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000012204 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012205 }
Douglas Gregor21920e372009-12-01 17:24:26 +000012206
12207 if (!Method->isInvalidDecl())
12208 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12209 << Method->getDeclName() << InitRange;
12210 return true;
12211}
12212
Douglas Gregor926410d2012-02-21 02:22:07 +000012213/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012214static bool isStaticDataMember(const Decl *D) {
12215 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12216 return Var->isStaticDataMember();
12217
12218 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000012219}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012220
John McCall1f4ee7b2009-12-19 09:28:58 +000012221/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12222/// an initializer for the out-of-line declaration 'Dcl'. The scope
12223/// is a fresh scope pushed for just this purpose.
12224///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012225/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12226/// static data member of class X, names should be looked up in the scope of
12227/// class X.
John McCall48871652010-08-21 09:40:31 +000012228void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012229 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000012230 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012231
Richard Smitha2302242013-12-05 07:51:02 +000012232 // We will always have a nested name specifier here, but this declaration
12233 // might not be out of line if the specifier names the current namespace:
12234 // extern int n;
12235 // int ::n = 0;
12236 if (D->isOutOfLine())
12237 EnterDeclaratorContext(S, D->getDeclContext());
12238
Douglas Gregor926410d2012-02-21 02:22:07 +000012239 // If we are parsing the initializer for a static data member, push a
12240 // new expression evaluation context that is associated with this static
12241 // data member.
12242 if (isStaticDataMember(D))
12243 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012244}
12245
12246/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000012247/// initializer for the out-of-line declaration 'D'.
12248void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012249 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000012250 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012251
Douglas Gregor926410d2012-02-21 02:22:07 +000012252 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000012253 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000012254
Richard Smitha2302242013-12-05 07:51:02 +000012255 if (D->isOutOfLine())
12256 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012257}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012258
12259/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12260/// C++ if/switch/while/for statement.
12261/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000012262DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012263 // C++ 6.4p2:
12264 // The declarator shall not specify a function or an array.
12265 // The type-specifier-seq shall not contain typedef and shall not declare a
12266 // new class or enumeration.
12267 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12268 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012269
12270 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012271 if (!Dcl)
12272 return true;
12273
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012274 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12275 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012276 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012277 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012278 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012279
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012280 return Dcl;
12281}
Anders Carlssonf98849e2009-12-02 17:15:43 +000012282
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012283void Sema::LoadExternalVTableUses() {
12284 if (!ExternalSource)
12285 return;
12286
12287 SmallVector<ExternalVTableUse, 4> VTables;
12288 ExternalSource->ReadUsedVTables(VTables);
12289 SmallVector<VTableUse, 4> NewUses;
12290 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12291 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12292 = VTablesUsed.find(VTables[I].Record);
12293 // Even if a definition wasn't required before, it may be required now.
12294 if (Pos != VTablesUsed.end()) {
12295 if (!Pos->second && VTables[I].DefinitionRequired)
12296 Pos->second = true;
12297 continue;
12298 }
12299
12300 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12301 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12302 }
12303
12304 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12305}
12306
Douglas Gregor88d292c2010-05-13 16:44:06 +000012307void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12308 bool DefinitionRequired) {
12309 // Ignore any vtable uses in unevaluated operands or for classes that do
12310 // not have a vtable.
12311 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000012312 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000012313 return;
12314
Douglas Gregor88d292c2010-05-13 16:44:06 +000012315 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012316 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012317 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12318 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12319 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12320 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000012321 // If we already had an entry, check to see if we are promoting this vtable
12322 // to required a definition. If so, we need to reappend to the VTableUses
12323 // list, since we may have already processed the first entry.
12324 if (DefinitionRequired && !Pos.first->second) {
12325 Pos.first->second = true;
12326 } else {
12327 // Otherwise, we can early exit.
12328 return;
12329 }
Hans Wennborg3d791542014-02-24 15:58:24 +000012330 } else {
12331 // The Microsoft ABI requires that we perform the destructor body
12332 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
12333 // the deleting destructor is emitted with the vtable, not with the
12334 // destructor definition as in the Itanium ABI.
12335 // If it has a definition, we do the check at that point instead.
12336 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12337 Class->hasUserDeclaredDestructor() &&
12338 !Class->getDestructor()->isDefined() &&
12339 !Class->getDestructor()->isDeleted()) {
12340 CheckDestructor(Class->getDestructor());
12341 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012342 }
12343
12344 // Local classes need to have their virtual members marked
12345 // immediately. For all other classes, we mark their virtual members
12346 // at the end of the translation unit.
12347 if (Class->isLocalClass())
12348 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000012349 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000012350 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000012351}
12352
Douglas Gregor88d292c2010-05-13 16:44:06 +000012353bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012354 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012355 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000012356 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000012357
Douglas Gregor88d292c2010-05-13 16:44:06 +000012358 // Note: The VTableUses vector could grow as a result of marking
12359 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000012360 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000012361 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000012362 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012363 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000012364 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012365 if (!Class)
12366 continue;
12367
12368 SourceLocation Loc = VTableUses[I].second;
12369
Richard Smithd3b5c9082012-07-27 04:22:15 +000012370 bool DefineVTable = true;
12371
Douglas Gregor88d292c2010-05-13 16:44:06 +000012372 // If this class has a key function, but that key function is
12373 // defined in another translation unit, we don't need to emit the
12374 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000012375 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000012376 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000012377 // The key function is in another translation unit.
12378 DefineVTable = false;
12379 TemplateSpecializationKind TSK =
12380 KeyFunction->getTemplateSpecializationKind();
12381 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12382 TSK != TSK_ImplicitInstantiation &&
12383 "Instantiations don't have key functions");
12384 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012385 } else if (!KeyFunction) {
12386 // If we have a class with no key function that is the subject
12387 // of an explicit instantiation declaration, suppress the
12388 // vtable; it will live with the explicit instantiation
12389 // definition.
12390 bool IsExplicitInstantiationDeclaration
12391 = Class->getTemplateSpecializationKind()
12392 == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000012393 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000012394 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000012395 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012396 if (TSK == TSK_ExplicitInstantiationDeclaration)
12397 IsExplicitInstantiationDeclaration = true;
12398 else if (TSK == TSK_ExplicitInstantiationDefinition) {
12399 IsExplicitInstantiationDeclaration = false;
12400 break;
12401 }
12402 }
12403
12404 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000012405 DefineVTable = false;
12406 }
12407
12408 // The exception specifications for all virtual members may be needed even
12409 // if we are not providing an authoritative form of the vtable in this TU.
12410 // We may choose to emit it available_externally anyway.
12411 if (!DefineVTable) {
12412 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12413 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012414 }
12415
12416 // Mark all of the virtual members of this class as referenced, so
12417 // that we can build a vtable. Then, tell the AST consumer that a
12418 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000012419 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012420 MarkVirtualMembersReferenced(Loc, Class);
12421 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12422 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12423
12424 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000012425 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000012426 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregor34bc6e52011-09-23 19:04:03 +000012427 const FunctionDecl *KeyFunctionDef = 0;
12428 if (!KeyFunction ||
12429 (KeyFunction->hasBody(KeyFunctionDef) &&
12430 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000012431 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12432 TSK_ExplicitInstantiationDefinition
12433 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12434 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012435 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000012436 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012437 VTableUses.clear();
12438
Douglas Gregor97509692011-04-22 22:25:37 +000012439 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000012440}
Anders Carlsson82fccd02009-12-07 08:24:59 +000012441
Richard Smithd3b5c9082012-07-27 04:22:15 +000012442void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12443 const CXXRecordDecl *RD) {
12444 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
12445 E = RD->method_end(); I != E; ++I)
12446 if ((*I)->isVirtual() && !(*I)->isPure())
12447 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
12448}
12449
Rafael Espindola5b334082010-03-26 00:36:59 +000012450void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12451 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000012452 // Mark all functions which will appear in RD's vtable as used.
12453 CXXFinalOverriderMap FinalOverriders;
12454 RD->getFinalOverriders(FinalOverriders);
12455 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12456 E = FinalOverriders.end();
12457 I != E; ++I) {
12458 for (OverridingMethods::const_iterator OI = I->second.begin(),
12459 OE = I->second.end();
12460 OI != OE; ++OI) {
12461 assert(OI->second.size() > 0 && "no final overrider");
12462 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000012463
Richard Smith4ff9ff92012-07-07 06:59:51 +000012464 // C++ [basic.def.odr]p2:
12465 // [...] A virtual member function is used if it is not pure. [...]
12466 if (!Overrider->isPure())
12467 MarkFunctionReferenced(Loc, Overrider);
12468 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012469 }
Rafael Espindola5b334082010-03-26 00:36:59 +000012470
12471 // Only classes that have virtual bases need a VTT.
12472 if (RD->getNumVBases() == 0)
12473 return;
12474
12475 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
12476 e = RD->bases_end(); i != e; ++i) {
12477 const CXXRecordDecl *Base =
12478 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000012479 if (Base->getNumVBases() == 0)
12480 continue;
12481 MarkVirtualMembersReferenced(Loc, Base);
12482 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012483}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012484
12485/// SetIvarInitializers - This routine builds initialization ASTs for the
12486/// Objective-C implementation whose ivars need be initialized.
12487void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000012488 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012489 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000012490 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012491 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012492 CollectIvarsToConstructOrDestruct(OID, ivars);
12493 if (ivars.empty())
12494 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012495 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012496 for (unsigned i = 0; i < ivars.size(); i++) {
12497 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000012498 if (Field->isInvalidDecl())
12499 continue;
12500
Alexis Hunt1d792652011-01-08 20:30:50 +000012501 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012502 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12503 InitializationKind InitKind =
12504 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000012505
12506 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12507 ExprResult MemberInit =
12508 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000012509 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012510 // Note, MemberInit could actually come back empty if no initialization
12511 // is required (e.g., because it would call a trivial default constructor)
12512 if (!MemberInit.get() || MemberInit.isInvalid())
12513 continue;
John McCallacf0ee52010-10-08 02:01:28 +000012514
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012515 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000012516 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12517 SourceLocation(),
12518 MemberInit.takeAs<Expr>(),
12519 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012520 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000012521
12522 // Be sure that the destructor is accessible and is marked as referenced.
12523 if (const RecordType *RecordTy
12524 = Context.getBaseElementType(Field->getType())
12525 ->getAs<RecordType>()) {
12526 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000012527 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000012528 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000012529 CheckDestructorAccess(Field->getLocation(), Destructor,
12530 PDiag(diag::err_access_dtor_ivar)
12531 << Context.getBaseElementType(Field->getType()));
12532 }
12533 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012534 }
12535 ObjCImplementation->setIvarInitializers(Context,
12536 AllToInit.data(), AllToInit.size());
12537 }
12538}
Alexis Hunt6118d662011-05-04 05:57:24 +000012539
Alexis Hunt27a761d2011-05-04 23:29:54 +000012540static
12541void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12542 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12543 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12544 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12545 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000012546 if (Ctor->isInvalidDecl())
12547 return;
12548
Richard Smith802c4b72012-08-23 06:16:52 +000012549 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12550
12551 // Target may not be determinable yet, for instance if this is a dependent
12552 // call in an uninstantiated template.
12553 if (Target) {
12554 const FunctionDecl *FNTarget = 0;
12555 (void)Target->hasBody(FNTarget);
12556 Target = const_cast<CXXConstructorDecl*>(
12557 cast_or_null<CXXConstructorDecl>(FNTarget));
12558 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000012559
12560 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12561 // Avoid dereferencing a null pointer here.
12562 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12563
12564 if (!Current.insert(Canonical))
12565 return;
12566
12567 // We know that beyond here, we aren't chaining into a cycle.
12568 if (!Target || !Target->isDelegatingConstructor() ||
12569 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012570 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012571 Current.clear();
12572 // We've hit a cycle.
12573 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12574 Current.count(TCanonical)) {
12575 // If we haven't diagnosed this cycle yet, do so now.
12576 if (!Invalid.count(TCanonical)) {
12577 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000012578 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012579 << Ctor;
12580
Richard Smith802c4b72012-08-23 06:16:52 +000012581 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000012582 if (TCanonical != Canonical)
12583 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12584
12585 CXXConstructorDecl *C = Target;
12586 while (C->getCanonicalDecl() != Canonical) {
Richard Smith802c4b72012-08-23 06:16:52 +000012587 const FunctionDecl *FNTarget = 0;
Alexis Hunt27a761d2011-05-04 23:29:54 +000012588 (void)C->getTargetConstructor()->hasBody(FNTarget);
12589 assert(FNTarget && "Ctor cycle through bodiless function");
12590
Richard Smith802c4b72012-08-23 06:16:52 +000012591 C = const_cast<CXXConstructorDecl*>(
12592 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000012593 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12594 }
12595 }
12596
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012597 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012598 Current.clear();
12599 } else {
12600 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12601 }
12602}
12603
12604
Alexis Hunt6118d662011-05-04 05:57:24 +000012605void Sema::CheckDelegatingCtorCycles() {
12606 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12607
Douglas Gregorbae31202011-07-27 21:57:17 +000012608 for (DelegatingCtorDeclsType::iterator
12609 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000012610 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000012611 I != E; ++I)
12612 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000012613
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012614 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12615 CE = Invalid.end();
12616 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012617 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000012618}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012619
Douglas Gregor3024f072012-04-16 07:05:22 +000012620namespace {
12621 /// \brief AST visitor that finds references to the 'this' expression.
12622 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12623 Sema &S;
12624
12625 public:
12626 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12627
12628 bool VisitCXXThisExpr(CXXThisExpr *E) {
12629 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12630 << E->isImplicit();
12631 return false;
12632 }
12633 };
12634}
12635
12636bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12637 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12638 if (!TSInfo)
12639 return false;
12640
12641 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012642 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000012643 if (!ProtoTL)
12644 return false;
12645
12646 // C++11 [expr.prim.general]p3:
12647 // [The expression this] shall not appear before the optional
12648 // cv-qualifier-seq and it shall not appear within the declaration of a
12649 // static member function (although its type and value category are defined
12650 // within a static member function as they are within a non-static member
12651 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000012652 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000012653 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000012654 FindCXXThisExpr Finder(*this);
12655
12656 // If the return type came after the cv-qualifier-seq, check it now.
12657 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000012658 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000012659 return true;
12660
12661 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000012662 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12663 return true;
12664
12665 return checkThisInStaticMemberFunctionAttributes(Method);
12666}
12667
12668bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12669 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12670 if (!TSInfo)
12671 return false;
12672
12673 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012674 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000012675 if (!ProtoTL)
12676 return false;
12677
David Blaikie6adc78e2013-02-18 22:06:02 +000012678 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000012679 FindCXXThisExpr Finder(*this);
12680
Douglas Gregor3024f072012-04-16 07:05:22 +000012681 switch (Proto->getExceptionSpecType()) {
Richard Smithf623c962012-04-17 00:58:00 +000012682 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000012683 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000012684 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000012685 case EST_DynamicNone:
12686 case EST_MSAny:
12687 case EST_None:
12688 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000012689
Douglas Gregor3024f072012-04-16 07:05:22 +000012690 case EST_ComputedNoexcept:
12691 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12692 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000012693
Douglas Gregor3024f072012-04-16 07:05:22 +000012694 case EST_Dynamic:
12695 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor433e0532012-04-16 18:27:27 +000012696 EEnd = Proto->exception_end();
Douglas Gregor3024f072012-04-16 07:05:22 +000012697 E != EEnd; ++E) {
12698 if (!Finder.TraverseType(*E))
12699 return true;
12700 }
12701 break;
12702 }
Douglas Gregor433e0532012-04-16 18:27:27 +000012703
12704 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000012705}
12706
12707bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12708 FindCXXThisExpr Finder(*this);
12709
12710 // Check attributes.
Aaron Ballman7dce1a82014-03-07 13:13:38 +000012711 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12712 A != AEnd; ++A) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012713 // FIXME: This should be emitted by tblgen.
12714 Expr *Arg = 0;
12715 ArrayRef<Expr *> Args;
Aaron Ballman7dce1a82014-03-07 13:13:38 +000012716 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012717 Arg = G->getArg();
Aaron Ballman7dce1a82014-03-07 13:13:38 +000012718 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012719 Arg = G->getArg();
Aaron Ballman7dce1a82014-03-07 13:13:38 +000012720 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012721 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
Aaron Ballman7dce1a82014-03-07 13:13:38 +000012722 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012723 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
Aaron Ballman7dce1a82014-03-07 13:13:38 +000012724 else if (ExclusiveLockFunctionAttr *ELF
12725 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012726 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
Aaron Ballman7dce1a82014-03-07 13:13:38 +000012727 else if (SharedLockFunctionAttr *SLF
12728 = dyn_cast<SharedLockFunctionAttr>(*A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012729 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
Aaron Ballman7dce1a82014-03-07 13:13:38 +000012730 else if (ExclusiveTrylockFunctionAttr *ETLF
12731 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012732 Arg = ETLF->getSuccessValue();
12733 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
Aaron Ballman7dce1a82014-03-07 13:13:38 +000012734 } else if (SharedTrylockFunctionAttr *STLF
12735 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012736 Arg = STLF->getSuccessValue();
12737 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
Aaron Ballman7dce1a82014-03-07 13:13:38 +000012738 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012739 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
Aaron Ballman7dce1a82014-03-07 13:13:38 +000012740 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012741 Arg = LR->getArg();
Aaron Ballman7dce1a82014-03-07 13:13:38 +000012742 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012743 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
Aaron Ballman7dce1a82014-03-07 13:13:38 +000012744 else if (RequiresCapabilityAttr *RC
12745 = dyn_cast<RequiresCapabilityAttr>(*A))
Aaron Ballmanefe348e2014-02-18 17:36:50 +000012746 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
Aaron Ballman7dce1a82014-03-07 13:13:38 +000012747 else if (AcquireCapabilityAttr *AC = dyn_cast<AcquireCapabilityAttr>(*A))
Aaron Ballman9e9d1842014-02-21 21:05:14 +000012748 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
Aaron Ballman7dce1a82014-03-07 13:13:38 +000012749 else if (TryAcquireCapabilityAttr *AC
12750 = dyn_cast<TryAcquireCapabilityAttr>(*A))
12751 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
12752 else if (ReleaseCapabilityAttr *RC = dyn_cast<ReleaseCapabilityAttr>(*A))
Aaron Ballman9e9d1842014-02-21 21:05:14 +000012753 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000012754
12755 if (Arg && !Finder.TraverseStmt(Arg))
12756 return true;
12757
12758 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12759 if (!Finder.TraverseStmt(Args[I]))
12760 return true;
12761 }
12762 }
12763
12764 return false;
12765}
12766
Douglas Gregor433e0532012-04-16 18:27:27 +000012767void
12768Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12769 ArrayRef<ParsedType> DynamicExceptions,
12770 ArrayRef<SourceRange> DynamicExceptionRanges,
12771 Expr *NoexceptExpr,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012772 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor433e0532012-04-16 18:27:27 +000012773 FunctionProtoType::ExtProtoInfo &EPI) {
12774 Exceptions.clear();
12775 EPI.ExceptionSpecType = EST;
12776 if (EST == EST_Dynamic) {
12777 Exceptions.reserve(DynamicExceptions.size());
12778 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12779 // FIXME: Preserve type source info.
12780 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12781
12782 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12783 collectUnexpandedParameterPacks(ET, Unexpanded);
12784 if (!Unexpanded.empty()) {
12785 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12786 UPPC_ExceptionType,
12787 Unexpanded);
12788 continue;
12789 }
12790
12791 // Check that the type is valid for an exception spec, and
12792 // drop it if not.
12793 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12794 Exceptions.push_back(ET);
12795 }
12796 EPI.NumExceptions = Exceptions.size();
12797 EPI.Exceptions = Exceptions.data();
12798 return;
12799 }
12800
12801 if (EST == EST_ComputedNoexcept) {
12802 // If an error occurred, there's no expression here.
12803 if (NoexceptExpr) {
12804 assert((NoexceptExpr->isTypeDependent() ||
12805 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12806 Context.BoolTy) &&
12807 "Parser should have made sure that the expression is boolean");
12808 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12809 EPI.ExceptionSpecType = EST_BasicNoexcept;
12810 return;
12811 }
12812
12813 if (!NoexceptExpr->isValueDependent())
12814 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregore2b37442012-05-04 22:38:52 +000012815 diag::err_noexcept_needs_constant_expression,
Douglas Gregor433e0532012-04-16 18:27:27 +000012816 /*AllowFold*/ false).take();
12817 EPI.NoexceptExpr = NoexceptExpr;
12818 }
12819 return;
12820 }
12821}
12822
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012823/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12824Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12825 // Implicitly declared functions (e.g. copy constructors) are
12826 // __host__ __device__
12827 if (D->isImplicit())
12828 return CFT_HostDevice;
12829
12830 if (D->hasAttr<CUDAGlobalAttr>())
12831 return CFT_Global;
12832
12833 if (D->hasAttr<CUDADeviceAttr>()) {
12834 if (D->hasAttr<CUDAHostAttr>())
12835 return CFT_HostDevice;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012836 return CFT_Device;
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012837 }
12838
12839 return CFT_Host;
12840}
12841
12842bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12843 CUDAFunctionTarget CalleeTarget) {
12844 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12845 // Callable from the device only."
12846 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12847 return true;
12848
12849 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12850 // Callable from the host only."
12851 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12852 // Callable from the host only."
12853 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12854 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12855 return true;
12856
12857 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12858 return true;
12859
12860 return false;
12861}
John McCall5e77d762013-04-16 07:28:30 +000012862
12863/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12864///
12865MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12866 SourceLocation DeclStart,
12867 Declarator &D, Expr *BitWidth,
12868 InClassInitStyle InitStyle,
12869 AccessSpecifier AS,
12870 AttributeList *MSPropertyAttr) {
12871 IdentifierInfo *II = D.getIdentifier();
12872 if (!II) {
12873 Diag(DeclStart, diag::err_anonymous_property);
12874 return NULL;
12875 }
12876 SourceLocation Loc = D.getIdentifierLoc();
12877
12878 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12879 QualType T = TInfo->getType();
12880 if (getLangOpts().CPlusPlus) {
12881 CheckExtraCXXDefaultArguments(D);
12882
12883 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12884 UPPC_DataMemberType)) {
12885 D.setInvalidType();
12886 T = Context.IntTy;
12887 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12888 }
12889 }
12890
12891 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12892
12893 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12894 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12895 diag::err_invalid_thread)
12896 << DeclSpec::getSpecifierName(TSCS);
12897
12898 // Check to see if this name was declared as a member previously
12899 NamedDecl *PrevDecl = 0;
12900 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12901 LookupName(Previous, S);
12902 switch (Previous.getResultKind()) {
12903 case LookupResult::Found:
12904 case LookupResult::FoundUnresolvedValue:
12905 PrevDecl = Previous.getAsSingle<NamedDecl>();
12906 break;
12907
12908 case LookupResult::FoundOverloaded:
12909 PrevDecl = Previous.getRepresentativeDecl();
12910 break;
12911
12912 case LookupResult::NotFound:
12913 case LookupResult::NotFoundInCurrentInstantiation:
12914 case LookupResult::Ambiguous:
12915 break;
12916 }
12917
12918 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12919 // Maybe we will complain about the shadowed template parameter.
12920 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12921 // Just pretend that we didn't see the previous declaration.
12922 PrevDecl = 0;
12923 }
12924
12925 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12926 PrevDecl = 0;
12927
12928 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000012929 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000012930 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
12931 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000012932 ProcessDeclAttributes(TUScope, NewPD, D);
12933 NewPD->setAccess(AS);
12934
12935 if (NewPD->isInvalidDecl())
12936 Record->setInvalidDecl();
12937
12938 if (D.getDeclSpec().isModulePrivateSpecified())
12939 NewPD->setModulePrivate();
12940
12941 if (NewPD->isInvalidDecl() && PrevDecl) {
12942 // Don't introduce NewFD into scope; there's already something
12943 // with the same name in the same scope.
12944 } else if (II) {
12945 PushOnScopeChains(NewPD, S);
12946 } else
12947 Record->addDecl(NewPD);
12948
12949 return NewPD;
12950}