blob: 3fe6337d502508bfe76fc6f8e1eb4379a0805d48 [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 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000383 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
384 ParmVarDecl *Param =
John McCall48871652010-08-21 09:40:31 +0000385 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000386 if (Param->hasUnparsedDefaultArg()) {
387 CachedTokens *Toks = chunk.Fun.ArgInfo[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;
392 chunk.Fun.ArgInfo[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;
793 QualType RT = NewFD->getResultType();
794 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.
Richard Smith3da88fa2013-04-26 14:36:30 +00001183 bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->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.
2322 for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
2323 I != E; ++I) {
2324 if (FieldDecl *FD = dyn_cast<FieldDecl>(*I)) {
2325 UninitializedFields.insert(FD);
2326 } else if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I)) {
2327 UninitializedFields.insert(IFD->getAnonField());
2328 }
2329 }
2330
2331 for (CXXConstructorDecl::init_const_iterator FieldInit =
2332 Constructor->init_begin(),
2333 FieldInitEnd = Constructor->init_end();
2334 FieldInit != FieldInitEnd; ++FieldInit) {
2335
2336 Expr *InitExpr = (*FieldInit)->getInit();
2337
2338 CheckInitExprContainsUninitializedFields(
2339 SemaRef, InitExpr, UninitializedFields, Constructor);
2340
2341 if (FieldDecl *Field = (*FieldInit)->getAnyMember())
2342 UninitializedFields.erase(Field);
2343 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002344 }
2345} // namespace
2346
Richard Smith74108172014-01-17 03:11:34 +00002347/// \brief Enter a new C++ default initializer scope. After calling this, the
2348/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2349/// parsing or instantiating the initializer failed.
2350void Sema::ActOnStartCXXInClassMemberInitializer() {
2351 // Create a synthetic function scope to represent the call to the constructor
2352 // that notionally surrounds a use of this initializer.
2353 PushFunctionScope();
2354}
2355
2356/// \brief This is invoked after parsing an in-class initializer for a
2357/// non-static C++ class member, and after instantiating an in-class initializer
2358/// in a class template. Such actions are deferred until the class is complete.
2359void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2360 SourceLocation InitLoc,
2361 Expr *InitExpr) {
2362 // Pop the notional constructor scope we created earlier.
2363 PopFunctionScopeInfo(0, D);
2364
Richard Smith938f40b2011-06-11 17:19:42 +00002365 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smith2b013182012-06-10 03:12:00 +00002366 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2367 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00002368
2369 if (!InitExpr) {
2370 FD->setInvalidDecl();
2371 FD->removeInClassInitializer();
2372 return;
2373 }
2374
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002375 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2376 FD->setInvalidDecl();
2377 FD->removeInClassInitializer();
2378 return;
2379 }
2380
Richard Smith938f40b2011-06-11 17:19:42 +00002381 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00002382 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002383 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00002384 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00002385 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00002386 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002387 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2388 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00002389 if (Init.isInvalid()) {
2390 FD->setInvalidDecl();
2391 return;
2392 }
Richard Smith938f40b2011-06-11 17:19:42 +00002393 }
2394
Richard Smith945f8d32013-01-14 22:39:08 +00002395 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00002396 // The initialization of each base and member constitutes a
2397 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002398 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00002399 if (Init.isInvalid()) {
2400 FD->setInvalidDecl();
2401 return;
2402 }
2403
2404 InitExpr = Init.release();
2405
2406 FD->setInClassInitializer(InitExpr);
2407}
2408
Douglas Gregor15e77a22009-12-31 09:10:24 +00002409/// \brief Find the direct and/or virtual base specifiers that
2410/// correspond to the given base type, for use in base initialization
2411/// within a constructor.
2412static bool FindBaseInitializer(Sema &SemaRef,
2413 CXXRecordDecl *ClassDecl,
2414 QualType BaseType,
2415 const CXXBaseSpecifier *&DirectBaseSpec,
2416 const CXXBaseSpecifier *&VirtualBaseSpec) {
2417 // First, check for a direct base class.
2418 DirectBaseSpec = 0;
2419 for (CXXRecordDecl::base_class_const_iterator Base
2420 = ClassDecl->bases_begin();
2421 Base != ClassDecl->bases_end(); ++Base) {
2422 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2423 // We found a direct base of this type. That's what we're
2424 // initializing.
2425 DirectBaseSpec = &*Base;
2426 break;
2427 }
2428 }
2429
2430 // Check for a virtual base class.
2431 // FIXME: We might be able to short-circuit this if we know in advance that
2432 // there are no virtual bases.
2433 VirtualBaseSpec = 0;
2434 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2435 // We haven't found a base yet; search the class hierarchy for a
2436 // virtual base class.
2437 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2438 /*DetectVirtual=*/false);
2439 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2440 BaseType, Paths)) {
2441 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2442 Path != Paths.end(); ++Path) {
2443 if (Path->back().Base->isVirtual()) {
2444 VirtualBaseSpec = Path->back().Base;
2445 break;
2446 }
2447 }
2448 }
2449 }
2450
2451 return DirectBaseSpec || VirtualBaseSpec;
2452}
2453
Sebastian Redla74948d2011-09-24 17:48:25 +00002454/// \brief Handle a C++ member initializer using braced-init-list syntax.
2455MemInitResult
2456Sema::ActOnMemInitializer(Decl *ConstructorD,
2457 Scope *S,
2458 CXXScopeSpec &SS,
2459 IdentifierInfo *MemberOrBase,
2460 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002461 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002462 SourceLocation IdLoc,
2463 Expr *InitList,
2464 SourceLocation EllipsisLoc) {
2465 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002466 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00002467 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002468}
2469
2470/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00002471MemInitResult
John McCall48871652010-08-21 09:40:31 +00002472Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00002473 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002474 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002475 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00002476 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002477 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002478 SourceLocation IdLoc,
2479 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002480 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002481 SourceLocation RParenLoc,
2482 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00002483 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002484 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002485 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002486 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002487}
2488
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002489namespace {
2490
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00002491// Callback to only accept typo corrections that can be a valid C++ member
2492// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002493class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002494public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002495 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2496 : ClassDecl(ClassDecl) {}
2497
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002498 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002499 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2500 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2501 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002502 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002503 }
2504 return false;
2505 }
2506
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002507private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002508 CXXRecordDecl *ClassDecl;
2509};
2510
2511}
2512
Sebastian Redla74948d2011-09-24 17:48:25 +00002513/// \brief Handle a C++ member initializer.
2514MemInitResult
2515Sema::BuildMemInitializer(Decl *ConstructorD,
2516 Scope *S,
2517 CXXScopeSpec &SS,
2518 IdentifierInfo *MemberOrBase,
2519 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002520 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002521 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00002522 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002523 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002524 if (!ConstructorD)
2525 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002526
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002527 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00002528
2529 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002530 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00002531 if (!Constructor) {
2532 // The user wrote a constructor initializer on a function that is
2533 // not a C++ constructor. Ignore the error for now, because we may
2534 // have more member initializers coming; we'll diagnose it just
2535 // once in ActOnMemInitializers.
2536 return true;
2537 }
2538
2539 CXXRecordDecl *ClassDecl = Constructor->getParent();
2540
2541 // C++ [class.base.init]p2:
2542 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00002543 // constructor's class and, if not found in that scope, are looked
2544 // up in the scope containing the constructor's definition.
2545 // [Note: if the constructor's class contains a member with the
2546 // same name as a direct or virtual base class of the class, a
2547 // mem-initializer-id naming the member or base class and composed
2548 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00002549 // mem-initializer-id for the hidden base class may be specified
2550 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00002551 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002552 // Look for a member, first.
Mike Stump11289f42009-09-09 15:08:12 +00002553 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002554 = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00002555 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00002556 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00002557 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2558 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00002559 if (EllipsisLoc.isValid())
2560 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00002561 << MemberOrBase
2562 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002563
Sebastian Redla9351792012-02-11 23:51:47 +00002564 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00002565 }
Francois Pichetd583da02010-12-04 09:14:42 +00002566 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002567 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002568 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002569 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00002570 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00002571
2572 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00002573 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00002574 } else if (DS.getTypeSpecType() == TST_decltype) {
2575 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00002576 } else {
2577 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2578 LookupParsedName(R, S, &SS);
2579
2580 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2581 if (!TyD) {
2582 if (R.isAmbiguous()) return true;
2583
John McCallda6841b2010-04-09 19:01:14 +00002584 // We don't want access-control diagnostics here.
2585 R.suppressDiagnostics();
2586
Douglas Gregora3b624a2010-01-19 06:46:48 +00002587 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2588 bool NotUnknownSpecialization = false;
2589 DeclContext *DC = computeDeclContext(SS, false);
2590 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2591 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2592
2593 if (!NotUnknownSpecialization) {
2594 // When the scope specifier can refer to a member of an unknown
2595 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00002596 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2597 SS.getWithLocInContext(Context),
2598 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00002599 if (BaseType.isNull())
2600 return true;
2601
Douglas Gregora3b624a2010-01-19 06:46:48 +00002602 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002603 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002604 }
2605 }
2606
Douglas Gregor15e77a22009-12-31 09:10:24 +00002607 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002608 TypoCorrection Corr;
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002609 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002610 if (R.empty() && BaseType.isNull() &&
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002611 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00002612 Validator, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002613 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002614 // We have found a non-static data member with a similar
2615 // name to what was typed; complain and initialize that
2616 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00002617 diagnoseTypo(Corr,
2618 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2619 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00002620 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002621 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002622 const CXXBaseSpecifier *DirectBaseSpec;
2623 const CXXBaseSpecifier *VirtualBaseSpec;
2624 if (FindBaseInitializer(*this, ClassDecl,
2625 Context.getTypeDeclType(Type),
2626 DirectBaseSpec, VirtualBaseSpec)) {
2627 // We have found a direct or virtual base class with a
2628 // similar name to what was typed; complain and initialize
2629 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00002630 diagnoseTypo(Corr,
2631 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2632 << MemberOrBase << false,
2633 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00002634
Richard Smithf9b15102013-08-17 00:46:16 +00002635 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2636 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002637 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00002638 diag::note_base_class_specified_here)
2639 << BaseSpec->getType()
2640 << BaseSpec->getSourceRange();
2641
Douglas Gregor15e77a22009-12-31 09:10:24 +00002642 TyD = Type;
2643 }
2644 }
2645 }
2646
Douglas Gregora3b624a2010-01-19 06:46:48 +00002647 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002648 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00002649 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00002650 return true;
2651 }
John McCallb5a0d312009-12-21 10:41:20 +00002652 }
2653
Douglas Gregora3b624a2010-01-19 06:46:48 +00002654 if (BaseType.isNull()) {
2655 BaseType = Context.getTypeDeclType(TyD);
Aaron Ballman4a979672014-01-03 13:56:08 +00002656 if (SS.isSet())
Douglas Gregora3b624a2010-01-19 06:46:48 +00002657 // FIXME: preserve source range information
Aaron Ballman4a979672014-01-03 13:56:08 +00002658 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2659 BaseType);
John McCallb5a0d312009-12-21 10:41:20 +00002660 }
2661 }
Mike Stump11289f42009-09-09 15:08:12 +00002662
John McCallbcd03502009-12-07 02:54:59 +00002663 if (!TInfo)
2664 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002665
Sebastian Redla9351792012-02-11 23:51:47 +00002666 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00002667}
2668
Chandler Carruth599deef2011-09-03 01:14:15 +00002669/// Checks a member initializer expression for cases where reference (or
2670/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00002671static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2672 Expr *Init,
2673 SourceLocation IdLoc) {
2674 QualType MemberTy = Member->getType();
2675
2676 // We only handle pointers and references currently.
2677 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2678 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2679 return;
2680
2681 const bool IsPointer = MemberTy->isPointerType();
2682 if (IsPointer) {
2683 if (const UnaryOperator *Op
2684 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2685 // The only case we're worried about with pointers requires taking the
2686 // address.
2687 if (Op->getOpcode() != UO_AddrOf)
2688 return;
2689
2690 Init = Op->getSubExpr();
2691 } else {
2692 // We only handle address-of expression initializers for pointers.
2693 return;
2694 }
2695 }
2696
Richard Smithe3b28bc2013-06-12 21:51:50 +00002697 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002698 // We only warn when referring to a non-reference parameter declaration.
2699 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2700 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00002701 return;
2702
2703 S.Diag(Init->getExprLoc(),
2704 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2705 : diag::warn_bind_ref_member_to_parameter)
2706 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002707 } else {
2708 // Other initializers are fine.
2709 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00002710 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002711
2712 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2713 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00002714}
2715
John McCallfaf5fb42010-08-26 23:41:50 +00002716MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002717Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002718 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002719 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2720 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2721 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00002722 "Member must be a FieldDecl or IndirectFieldDecl");
2723
Sebastian Redla9351792012-02-11 23:51:47 +00002724 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002725 return true;
2726
Douglas Gregor266bb5f2010-11-05 22:21:31 +00002727 if (Member->isInvalidDecl())
2728 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00002729
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002730 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00002731 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002732 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00002733 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002734 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00002735 } else {
2736 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002737 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002738 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00002739
Sebastian Redla9351792012-02-11 23:51:47 +00002740 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002741
Sebastian Redla9351792012-02-11 23:51:47 +00002742 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002743 // Can't check initialization for a member of dependent type or when
2744 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00002745 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00002746 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00002747 bool InitList = false;
2748 if (isa<InitListExpr>(Init)) {
2749 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002750 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002751 }
2752
Chandler Carruthd44c3102010-12-06 09:23:57 +00002753 // Initialize the member.
2754 InitializedEntity MemberEntity =
2755 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2756 : InitializedEntity::InitializeMember(IndirectMember, 0);
2757 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002758 InitList ? InitializationKind::CreateDirectList(IdLoc)
2759 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2760 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00002761
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002762 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2763 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002764 if (MemberInit.isInvalid())
2765 return true;
2766
Richard Smith736a9472013-06-12 20:42:33 +00002767 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2768
Richard Smith945f8d32013-01-14 22:39:08 +00002769 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00002770 // The initialization of each base and member constitutes a
2771 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002772 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002773 if (MemberInit.isInvalid())
2774 return true;
2775
Richard Smithd59b8322012-12-19 01:39:02 +00002776 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002777 }
2778
Chandler Carruthd44c3102010-12-06 09:23:57 +00002779 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00002780 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2781 InitRange.getBegin(), Init,
2782 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002783 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00002784 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2785 InitRange.getBegin(), Init,
2786 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002787 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00002788}
2789
John McCallfaf5fb42010-08-26 23:41:50 +00002790MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002791Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002792 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002793 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002794 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002795 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002796 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002797 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00002798
Sebastian Redl0501c632012-02-12 16:37:36 +00002799 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002800 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002801 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2802 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002803 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00002804 }
2805
Sebastian Redla9351792012-02-11 23:51:47 +00002806 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00002807 // Initialize the object.
2808 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2809 QualType(ClassDecl->getTypeForDecl(), 0));
2810 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002811 InitList ? InitializationKind::CreateDirectList(NameLoc)
2812 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2813 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002814 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00002815 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002816 Args, 0);
Alexis Huntc5575cc2011-02-26 19:13:13 +00002817 if (DelegationInit.isInvalid())
2818 return true;
2819
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00002820 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2821 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00002822
Richard Smith945f8d32013-01-14 22:39:08 +00002823 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00002824 // The initialization of each base and member constitutes a
2825 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002826 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2827 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002828 if (DelegationInit.isInvalid())
2829 return true;
2830
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00002831 // If we are in a dependent context, template instantiation will
2832 // perform this type-checking again. Just save the arguments that we
2833 // received in a ParenListExpr.
2834 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2835 // of the information that we have about the base
2836 // initializer. However, deconstructing the ASTs is a dicey process,
2837 // and this approach is far more likely to get the corner cases right.
2838 if (CurContext->isDependentContext())
2839 DelegationInit = Owned(Init);
2840
Sebastian Redla9351792012-02-11 23:51:47 +00002841 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00002842 DelegationInit.takeAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002843 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002844}
2845
2846MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00002847Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00002848 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002849 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002850 SourceLocation BaseLoc
2851 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00002852
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002853 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2854 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2855 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2856
2857 // C++ [class.base.init]p2:
2858 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00002859 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002860 // of that class, the mem-initializer is ill-formed. A
2861 // mem-initializer-list can initialize a base class using any
2862 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00002863 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002864
Sebastian Redla9351792012-02-11 23:51:47 +00002865 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00002866 if (EllipsisLoc.isValid()) {
2867 // This is a pack expansion.
2868 if (!BaseType->containsUnexpandedParameterPack()) {
2869 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00002870 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002871
Douglas Gregor44e7df62011-01-04 00:32:56 +00002872 EllipsisLoc = SourceLocation();
2873 }
2874 } else {
2875 // Check for any unexpanded parameter packs.
2876 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2877 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00002878
Sebastian Redla9351792012-02-11 23:51:47 +00002879 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00002880 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00002881 }
Sebastian Redla74948d2011-09-24 17:48:25 +00002882
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002883 // Check for direct and virtual base classes.
2884 const CXXBaseSpecifier *DirectBaseSpec = 0;
2885 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2886 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002887 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2888 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00002889 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002890
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002891 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2892 VirtualBaseSpec);
2893
2894 // C++ [base.class.init]p2:
2895 // Unless the mem-initializer-id names a nonstatic data member of the
2896 // constructor's class or a direct or virtual base of that class, the
2897 // mem-initializer is ill-formed.
2898 if (!DirectBaseSpec && !VirtualBaseSpec) {
2899 // If the class has any dependent bases, then it's possible that
2900 // one of those types will resolve to the same type as
2901 // BaseType. Therefore, just treat this as a dependent base
2902 // class initialization. FIXME: Should we try to check the
2903 // initialization anyway? It seems odd.
2904 if (ClassDecl->hasAnyDependentBases())
2905 Dependent = true;
2906 else
2907 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2908 << BaseType << Context.getTypeDeclType(ClassDecl)
2909 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2910 }
2911 }
2912
2913 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00002914 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002915
Sebastian Redla74948d2011-09-24 17:48:25 +00002916 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2917 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00002918 InitRange.getBegin(), Init,
2919 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002920 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002921
2922 // C++ [base.class.init]p2:
2923 // If a mem-initializer-id is ambiguous because it designates both
2924 // a direct non-virtual base class and an inherited virtual base
2925 // class, the mem-initializer is ill-formed.
2926 if (DirectBaseSpec && VirtualBaseSpec)
2927 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002928 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002929
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002930 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002931 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002932 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002933
2934 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00002935 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002936 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002937 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00002938 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002939 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00002940 }
Sebastian Redl0501c632012-02-12 16:37:36 +00002941
2942 InitializedEntity BaseEntity =
2943 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2944 InitializationKind Kind =
2945 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2946 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2947 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002948 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2949 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002950 if (BaseInit.isInvalid())
2951 return true;
John McCallacf0ee52010-10-08 02:01:28 +00002952
Richard Smith945f8d32013-01-14 22:39:08 +00002953 // C++11 [class.base.init]p7:
2954 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002955 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002956 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002957 if (BaseInit.isInvalid())
2958 return true;
2959
2960 // If we are in a dependent context, template instantiation will
2961 // perform this type-checking again. Just save the arguments that we
2962 // received in a ParenListExpr.
2963 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2964 // of the information that we have about the base
2965 // initializer. However, deconstructing the ASTs is a dicey process,
2966 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00002967 if (CurContext->isDependentContext())
Sebastian Redla9351792012-02-11 23:51:47 +00002968 BaseInit = Owned(Init);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002969
Alexis Hunt1d792652011-01-08 20:30:50 +00002970 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002971 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00002972 InitRange.getBegin(),
Sebastian Redla74948d2011-09-24 17:48:25 +00002973 BaseInit.takeAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002974 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002975}
2976
Sebastian Redl22653ba2011-08-30 19:58:05 +00002977// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00002978static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2979 if (T.isNull()) T = E->getType();
2980 QualType TargetType = SemaRef.BuildReferenceType(
2981 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002982 SourceLocation ExprLoc = E->getLocStart();
2983 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2984 TargetType, ExprLoc);
2985
2986 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2987 SourceRange(ExprLoc, ExprLoc),
2988 E->getSourceRange()).take();
2989}
2990
Anders Carlsson1b00e242010-04-23 03:10:23 +00002991/// ImplicitInitializerKind - How an implicit base or member initializer should
2992/// initialize its base or member.
2993enum ImplicitInitializerKind {
2994 IIK_Default,
2995 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00002996 IIK_Move,
2997 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00002998};
2999
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003000static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00003001BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003002 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00003003 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003004 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00003005 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003006 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00003007 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3008 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003009
John McCalldadc5752010-08-24 06:29:42 +00003010 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003011
3012 switch (ImplicitInitKind) {
Richard Smithc2bc61b2013-03-18 21:12:30 +00003013 case IIK_Inherit: {
3014 const CXXRecordDecl *Inherited =
3015 Constructor->getInheritedConstructor()->getParent();
3016 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3017 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3018 // C++11 [class.inhctor]p8:
3019 // Each expression in the expression-list is of the form
3020 // static_cast<T&&>(p), where p is the name of the corresponding
3021 // constructor parameter and T is the declared type of p.
3022 SmallVector<Expr*, 16> Args;
3023 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3024 ParmVarDecl *PD = Constructor->getParamDecl(I);
3025 ExprResult ArgExpr =
3026 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3027 VK_LValue, SourceLocation());
3028 if (ArgExpr.isInvalid())
3029 return true;
3030 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
3031 }
3032
3033 InitializationKind InitKind = InitializationKind::CreateDirect(
3034 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003035 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smithc2bc61b2013-03-18 21:12:30 +00003036 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3037 break;
3038 }
3039 }
3040 // Fall through.
Anders Carlsson1b00e242010-04-23 03:10:23 +00003041 case IIK_Default: {
3042 InitializationKind InitKind
3043 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003044 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3045 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003046 break;
3047 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003048
Sebastian Redl22653ba2011-08-30 19:58:05 +00003049 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00003050 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003051 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003052 ParmVarDecl *Param = Constructor->getParamDecl(0);
3053 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00003054
Anders Carlsson1b00e242010-04-23 03:10:23 +00003055 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003056 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003057 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003058 Constructor->getLocation(), ParamType,
3059 VK_LValue, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003060
Eli Friedmanfa0df832012-02-02 03:46:19 +00003061 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3062
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003063 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00003064 QualType ArgTy =
3065 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3066 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00003067
Sebastian Redl22653ba2011-08-30 19:58:05 +00003068 if (Moving) {
3069 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3070 }
3071
John McCallcf142162010-08-07 06:22:56 +00003072 CXXCastPath BasePath;
3073 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00003074 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3075 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003076 Moving ? VK_XValue : VK_LValue,
Sebastian Redl22653ba2011-08-30 19:58:05 +00003077 &BasePath).take();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003078
Anders Carlsson1b00e242010-04-23 03:10:23 +00003079 InitializationKind InitKind
3080 = InitializationKind::CreateDirect(Constructor->getLocation(),
3081 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003082 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3083 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003084 break;
3085 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00003086 }
John McCallb268a282010-08-23 23:25:46 +00003087
Douglas Gregora40433a2010-12-07 00:41:46 +00003088 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003089 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003090 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003091
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003092 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00003093 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003094 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3095 SourceLocation()),
3096 BaseSpec->isVirtual(),
3097 SourceLocation(),
3098 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003099 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003100 SourceLocation());
3101
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003102 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003103}
3104
Sebastian Redl22653ba2011-08-30 19:58:05 +00003105static bool RefersToRValueRef(Expr *MemRef) {
3106 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3107 return Referenced->getType()->isRValueReferenceType();
3108}
3109
Anders Carlsson3c1db572010-04-23 02:15:47 +00003110static bool
3111BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003112 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00003113 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00003114 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003115 if (Field->isInvalidDecl())
3116 return true;
3117
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003118 SourceLocation Loc = Constructor->getLocation();
3119
Sebastian Redl22653ba2011-08-30 19:58:05 +00003120 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3121 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00003122 ParmVarDecl *Param = Constructor->getParamDecl(0);
3123 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00003124
3125 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00003126 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3127 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003128
Anders Carlsson423f5d82010-04-23 16:04:08 +00003129 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003130 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003131 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003132 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003133
Eli Friedmanfa0df832012-02-02 03:46:19 +00003134 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3135
Sebastian Redl22653ba2011-08-30 19:58:05 +00003136 if (Moving) {
3137 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3138 }
3139
Douglas Gregor94f9a482010-05-05 05:51:00 +00003140 // Build a reference to this field within the parameter.
3141 CXXScopeSpec SS;
3142 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3143 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003144 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3145 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003146 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00003147 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00003148 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003149 ParamType, Loc,
3150 /*IsArrow=*/false,
3151 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003152 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00003153 /*FirstQualifierInScope=*/0,
3154 MemberLookup,
3155 /*TemplateArgs=*/0);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003156 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00003157 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003158
3159 // C++11 [class.copy]p15:
3160 // - if a member m has rvalue reference type T&&, it is direct-initialized
3161 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003162 if (RefersToRValueRef(CtorArg.get())) {
3163 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003164 }
3165
Douglas Gregor94f9a482010-05-05 05:51:00 +00003166 // When the field we are copying is an array, create index variables for
3167 // each dimension of the array. We use these index variables to subscript
3168 // the source array, and other clients (e.g., CodeGen) will perform the
3169 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003170 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003171 QualType BaseType = Field->getType();
3172 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003173 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003174 while (const ConstantArrayType *Array
3175 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003176 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003177 // Create the iteration variable for this array index.
3178 IdentifierInfo *IterationVarName = 0;
3179 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003180 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003181 llvm::raw_svector_ostream OS(Str);
3182 OS << "__i" << IndexVariables.size();
3183 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3184 }
3185 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00003186 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003187 IterationVarName, SizeType,
3188 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003189 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003190 IndexVariables.push_back(IterationVar);
3191
3192 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00003193 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00003194 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003195 assert(!IterationVarRef.isInvalid() &&
3196 "Reference to invented variable cannot fail!");
Eli Friedman844f9452012-01-23 02:35:22 +00003197 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3198 assert(!IterationVarRef.isInvalid() &&
3199 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00003200
Douglas Gregor94f9a482010-05-05 05:51:00 +00003201 // Subscript the array with this iteration variable.
Sebastian Redle9c4e842011-09-04 18:14:28 +00003202 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCallb268a282010-08-23 23:25:46 +00003203 IterationVarRef.take(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00003204 Loc);
3205 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00003206 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003207
Douglas Gregor94f9a482010-05-05 05:51:00 +00003208 BaseType = Array->getElementType();
3209 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00003210
3211 // The array subscript expression is an lvalue, which is wrong for moving.
3212 if (Moving && InitializingArray)
Sebastian Redle9c4e842011-09-04 18:14:28 +00003213 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003214
Douglas Gregor94f9a482010-05-05 05:51:00 +00003215 // Construct the entity that we will be initializing. For an array, this
3216 // will be first element in the array, which may require several levels
3217 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003218 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003219 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00003220 if (Indirect)
3221 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3222 else
3223 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00003224 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3225 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3226 0,
3227 Entities.back()));
3228
3229 // Direct-initialize to use the copy constructor.
3230 InitializationKind InitKind =
3231 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3232
Sebastian Redle9c4e842011-09-04 18:14:28 +00003233 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003234 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003235
John McCalldadc5752010-08-24 06:29:42 +00003236 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00003237 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003238 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00003239 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003240 if (MemberInit.isInvalid())
3241 return true;
3242
Douglas Gregor493627b2011-08-10 15:22:55 +00003243 if (Indirect) {
3244 assert(IndexVariables.size() == 0 &&
3245 "Indirect field improperly initialized");
3246 CXXMemberInit
3247 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3248 Loc, Loc,
3249 MemberInit.takeAs<Expr>(),
3250 Loc);
3251 } else
3252 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3253 Loc, MemberInit.takeAs<Expr>(),
3254 Loc,
3255 IndexVariables.data(),
3256 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00003257 return false;
3258 }
3259
Richard Smithc2bc61b2013-03-18 21:12:30 +00003260 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3261 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00003262
Anders Carlsson3c1db572010-04-23 02:15:47 +00003263 QualType FieldBaseElementType =
3264 SemaRef.Context.getBaseElementType(Field->getType());
3265
Anders Carlsson3c1db572010-04-23 02:15:47 +00003266 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003267 InitializedEntity InitEntity
3268 = Indirect? InitializedEntity::InitializeMember(Indirect)
3269 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00003270 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003271 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003272
3273 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3274 ExprResult MemberInit =
3275 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00003276
Douglas Gregora40433a2010-12-07 00:41:46 +00003277 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003278 if (MemberInit.isInvalid())
3279 return true;
3280
Douglas Gregor493627b2011-08-10 15:22:55 +00003281 if (Indirect)
3282 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3283 Indirect, Loc,
3284 Loc,
3285 MemberInit.get(),
3286 Loc);
3287 else
3288 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3289 Field, Loc, Loc,
3290 MemberInit.get(),
3291 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003292 return false;
3293 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003294
Alexis Hunt8b455182011-05-17 00:19:05 +00003295 if (!Field->getParent()->isUnion()) {
3296 if (FieldBaseElementType->isReferenceType()) {
3297 SemaRef.Diag(Constructor->getLocation(),
3298 diag::err_uninitialized_member_in_ctor)
3299 << (int)Constructor->isImplicit()
3300 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3301 << 0 << Field->getDeclName();
3302 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3303 return true;
3304 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003305
Alexis Hunt8b455182011-05-17 00:19:05 +00003306 if (FieldBaseElementType.isConstQualified()) {
3307 SemaRef.Diag(Constructor->getLocation(),
3308 diag::err_uninitialized_member_in_ctor)
3309 << (int)Constructor->isImplicit()
3310 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3311 << 1 << Field->getDeclName();
3312 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3313 return true;
3314 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003315 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00003316
David Blaikiebbafb8a2012-03-11 07:00:24 +00003317 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003318 FieldBaseElementType->isObjCRetainableType() &&
3319 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3320 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00003321 // ARC:
John McCall31168b02011-06-15 23:02:42 +00003322 // Default-initialize Objective-C pointers to NULL.
3323 CXXMemberInit
3324 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3325 Loc, Loc,
3326 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3327 Loc);
3328 return false;
3329 }
3330
Anders Carlsson3c1db572010-04-23 02:15:47 +00003331 // Nothing to initialize.
3332 CXXMemberInit = 0;
3333 return false;
3334}
John McCallbc83b3f2010-05-20 23:23:51 +00003335
3336namespace {
3337struct BaseAndFieldInfo {
3338 Sema &S;
3339 CXXConstructorDecl *Ctor;
3340 bool AnyErrorsInInits;
3341 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00003342 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003343 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00003344 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00003345
3346 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3347 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003348 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3349 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00003350 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003351 else if (Generated && Ctor->isMoveConstructor())
3352 IIK = IIK_Move;
Richard Smithc2bc61b2013-03-18 21:12:30 +00003353 else if (Ctor->getInheritedConstructor())
3354 IIK = IIK_Inherit;
John McCallbc83b3f2010-05-20 23:23:51 +00003355 else
3356 IIK = IIK_Default;
3357 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00003358
3359 bool isImplicitCopyOrMove() const {
3360 switch (IIK) {
3361 case IIK_Copy:
3362 case IIK_Move:
3363 return true;
3364
3365 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00003366 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00003367 return false;
3368 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003369
3370 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00003371 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00003372
3373 bool addFieldInitializer(CXXCtorInitializer *Init) {
3374 AllToInit.push_back(Init);
3375
3376 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00003377 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003378 S.UnusedPrivateFields.remove(Init->getAnyMember());
3379
3380 return false;
3381 }
John McCallbc83b3f2010-05-20 23:23:51 +00003382
Richard Smithab44d5b2013-12-10 08:25:00 +00003383 bool isInactiveUnionMember(FieldDecl *Field) {
3384 RecordDecl *Record = Field->getParent();
3385 if (!Record->isUnion())
3386 return false;
3387
Richard Smith8d183852013-12-10 20:56:03 +00003388 if (FieldDecl *Active =
3389 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00003390 return Active != Field->getCanonicalDecl();
3391
3392 // In an implicit copy or move constructor, ignore any in-class initializer.
3393 if (isImplicitCopyOrMove())
3394 return true;
3395
3396 // If there's no explicit initialization, the field is active only if it
3397 // has an in-class initializer...
3398 if (Field->hasInClassInitializer())
3399 return false;
3400 // ... or it's an anonymous struct or union whose class has an in-class
3401 // initializer.
3402 if (!Field->isAnonymousStructOrUnion())
3403 return true;
3404 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3405 return !FieldRD->hasInClassInitializer();
3406 }
3407
3408 /// \brief Determine whether the given field is, or is within, a union member
3409 /// that is inactive (because there was an initializer given for a different
3410 /// member of the union, or because the union was not initialized at all).
3411 bool isWithinInactiveUnionMember(FieldDecl *Field,
3412 IndirectFieldDecl *Indirect) {
3413 if (!Indirect)
3414 return isInactiveUnionMember(Field);
3415
3416 for (IndirectFieldDecl::chain_iterator C = Indirect->chain_begin(),
3417 CEnd = Indirect->chain_end();
3418 C != CEnd; ++C) {
3419 FieldDecl *Field = dyn_cast<FieldDecl>(*C);
3420 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00003421 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00003422 }
3423 return false;
3424 }
3425};
Richard Smithc94ec842011-09-19 13:34:43 +00003426}
3427
Douglas Gregor10f939c2011-11-02 23:04:16 +00003428/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3429/// array type.
3430static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3431 if (T->isIncompleteArrayType())
3432 return true;
3433
3434 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3435 if (!ArrayT->getSize())
3436 return true;
3437
3438 T = ArrayT->getElementType();
3439 }
3440
3441 return false;
3442}
3443
Richard Smith938f40b2011-06-11 17:19:42 +00003444static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00003445 FieldDecl *Field,
3446 IndirectFieldDecl *Indirect = 0) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003447 if (Field->isInvalidDecl())
3448 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00003449
Chandler Carruth139e9622010-06-30 02:59:29 +00003450 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0a8cfc72012-08-07 21:30:42 +00003451 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3452 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003453
Richard Smithab44d5b2013-12-10 08:25:00 +00003454 // C++11 [class.base.init]p8:
3455 // if the entity is a non-static data member that has a
3456 // brace-or-equal-initializer and either
3457 // -- the constructor's class is a union and no other variant member of that
3458 // union is designated by a mem-initializer-id or
3459 // -- the constructor's class is not a union, and, if the entity is a member
3460 // of an anonymous union, no other member of that union is designated by
3461 // a mem-initializer-id,
3462 // the entity is initialized as specified in [dcl.init].
3463 //
3464 // We also apply the same rules to handle anonymous structs within anonymous
3465 // unions.
3466 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3467 return false;
3468
Douglas Gregor7db3e952011-11-28 20:03:15 +00003469 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smith852c9db2013-04-20 22:23:05 +00003470 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3471 Info.Ctor->getLocation(), Field);
Douglas Gregor493627b2011-08-10 15:22:55 +00003472 CXXCtorInitializer *Init;
3473 if (Indirect)
3474 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3475 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003476 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003477 SourceLocation());
3478 else
3479 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3480 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003481 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003482 SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00003483 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003484 }
3485
Douglas Gregor10f939c2011-11-02 23:04:16 +00003486 // Don't initialize incomplete or zero-length arrays.
3487 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3488 return false;
3489
John McCallbc83b3f2010-05-20 23:23:51 +00003490 // Don't try to build an implicit initializer if there were semantic
3491 // errors in any of the initializers (and therefore we might be
3492 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003493 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00003494 return false;
3495
Alexis Hunt1d792652011-01-08 20:30:50 +00003496 CXXCtorInitializer *Init = 0;
Douglas Gregor493627b2011-08-10 15:22:55 +00003497 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3498 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00003499 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00003500
Richard Smith0a8cfc72012-08-07 21:30:42 +00003501 if (!Init)
3502 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00003503
Richard Smith0a8cfc72012-08-07 21:30:42 +00003504 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003505}
Alexis Hunt61bc1732011-05-01 07:04:31 +00003506
3507bool
3508Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3509 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00003510 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00003511 Constructor->setNumCtorInitializers(1);
3512 CXXCtorInitializer **initializer =
3513 new (Context) CXXCtorInitializer*[1];
3514 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3515 Constructor->setCtorInitializers(initializer);
3516
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003517 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003518 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003519 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3520 }
3521
Alexis Hunte2622992011-05-05 00:05:47 +00003522 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00003523
Alexis Hunt61bc1732011-05-01 07:04:31 +00003524 return false;
3525}
Douglas Gregor493627b2011-08-10 15:22:55 +00003526
David Blaikie3fc2f912013-01-17 05:26:25 +00003527bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3528 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00003529 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003530 // Just store the initializers as written, they will be checked during
3531 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00003532 if (!Initializers.empty()) {
3533 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00003534 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00003535 new (Context) CXXCtorInitializer*[Initializers.size()];
3536 memcpy(baseOrMemberInitializers, Initializers.data(),
3537 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00003538 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003539 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00003540
3541 // Let template instantiation know whether we had errors.
3542 if (AnyErrors)
3543 Constructor->setInvalidDecl();
3544
Anders Carlssondb0a9652010-04-02 06:26:44 +00003545 return false;
3546 }
3547
John McCallbc83b3f2010-05-20 23:23:51 +00003548 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003549
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003550 // We need to build the initializer AST according to order of construction
3551 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003552 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00003553 if (!ClassDecl)
3554 return true;
3555
Eli Friedman9cf6b592009-11-09 19:20:36 +00003556 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00003557
David Blaikie3fc2f912013-01-17 05:26:25 +00003558 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003559 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00003560
Anders Carlssondb0a9652010-04-02 06:26:44 +00003561 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00003562 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003563 else {
Francois Pichetd583da02010-12-04 09:14:42 +00003564 Info.AllBaseFields[Member->getAnyMember()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003565
3566 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
3567 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3568 CEnd = F->chain_end();
3569 C != CEnd; ++C) {
3570 FieldDecl *FD = dyn_cast<FieldDecl>(*C);
3571 if (FD && FD->getParent()->isUnion())
3572 Info.ActiveUnionMember.insert(std::make_pair(
3573 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3574 }
3575 } else if (FieldDecl *FD = Member->getMember()) {
3576 if (FD->getParent()->isUnion())
3577 Info.ActiveUnionMember.insert(std::make_pair(
3578 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3579 }
3580 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00003581 }
3582
Anders Carlsson43c64af2010-04-21 19:52:01 +00003583 // Keep track of the direct virtual bases.
3584 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3585 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3586 E = ClassDecl->bases_end(); I != E; ++I) {
3587 if (I->isVirtual())
3588 DirectVBases.insert(I);
3589 }
3590
Anders Carlssondb0a9652010-04-02 06:26:44 +00003591 // Push virtual bases before others.
3592 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3593 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3594
Alexis Hunt1d792652011-01-08 20:30:50 +00003595 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00003596 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00003597 // [class.base.init]p7, per DR257:
3598 // A mem-initializer where the mem-initializer-id names a virtual base
3599 // class is ignored during execution of a constructor of any class that
3600 // is not the most derived class.
3601 if (ClassDecl->isAbstract()) {
3602 // FIXME: Provide a fixit to remove the base specifier. This requires
3603 // tracking the location of the associated comma for a base specifier.
3604 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3605 << VBase->getType() << ClassDecl;
3606 DiagnoseAbstractType(ClassDecl);
3607 }
3608
John McCallbc83b3f2010-05-20 23:23:51 +00003609 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00003610 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3611 // [class.base.init]p8, per DR257:
3612 // If a given [...] base class is not named by a mem-initializer-id
3613 // [...] and the entity is not a virtual base class of an abstract
3614 // class, then [...] the entity is default-initialized.
Anders Carlsson43c64af2010-04-21 19:52:01 +00003615 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00003616 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003617 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Richard Smithbc46e432013-07-22 02:56:56 +00003618 VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003619 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003620 HadError = true;
3621 continue;
3622 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003623
John McCallbc83b3f2010-05-20 23:23:51 +00003624 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003625 }
3626 }
Mike Stump11289f42009-09-09 15:08:12 +00003627
John McCallbc83b3f2010-05-20 23:23:51 +00003628 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00003629 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3630 E = ClassDecl->bases_end(); Base != E; ++Base) {
3631 // Virtuals are in the virtual base list and already constructed.
3632 if (Base->isVirtual())
3633 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003634
Alexis Hunt1d792652011-01-08 20:30:50 +00003635 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00003636 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3637 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003638 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003639 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003640 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003641 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003642 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003643 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003644 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003645 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00003646
John McCallbc83b3f2010-05-20 23:23:51 +00003647 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003648 }
3649 }
Mike Stump11289f42009-09-09 15:08:12 +00003650
John McCallbc83b3f2010-05-20 23:23:51 +00003651 // Fields.
Douglas Gregor493627b2011-08-10 15:22:55 +00003652 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3653 MemEnd = ClassDecl->decls_end();
3654 Mem != MemEnd; ++Mem) {
3655 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003656 // C++ [class.bit]p2:
3657 // A declaration for a bit-field that omits the identifier declares an
3658 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3659 // initialized.
3660 if (F->isUnnamedBitfield())
3661 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003662
Sebastian Redl22653ba2011-08-30 19:58:05 +00003663 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00003664 // handle anonymous struct/union fields based on their individual
3665 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003666 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003667 continue;
3668
3669 if (CollectFieldInitializer(*this, Info, F))
3670 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003671 continue;
3672 }
Douglas Gregor493627b2011-08-10 15:22:55 +00003673
3674 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003675 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003676 continue;
3677
3678 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3679 if (F->getType()->isIncompleteArrayType()) {
3680 assert(ClassDecl->hasFlexibleArrayMember() &&
3681 "Incomplete array type is not valid");
3682 continue;
3683 }
3684
Douglas Gregor493627b2011-08-10 15:22:55 +00003685 // Initialize each field of an anonymous struct individually.
3686 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3687 HadError = true;
3688
3689 continue;
3690 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003691 }
Mike Stump11289f42009-09-09 15:08:12 +00003692
David Blaikie3fc2f912013-01-17 05:26:25 +00003693 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003694 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003695 Constructor->setNumCtorInitializers(NumInitializers);
3696 CXXCtorInitializer **baseOrMemberInitializers =
3697 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00003698 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00003699 NumInitializers * sizeof(CXXCtorInitializer*));
3700 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00003701
John McCalla6309952010-03-16 21:39:52 +00003702 // Constructors implicitly reference the base and member
3703 // destructors.
3704 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3705 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003706 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00003707
3708 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003709}
3710
David Blaikieb61b8152013-01-17 08:49:22 +00003711static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003712 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00003713 const RecordDecl *RD = RT->getDecl();
3714 if (RD->isAnonymousStructOrUnion()) {
3715 for (RecordDecl::field_iterator Field = RD->field_begin(),
3716 E = RD->field_end(); Field != E; ++Field)
3717 PopulateKeysForFields(*Field, IdealInits);
3718 return;
3719 }
Eli Friedman952c15d2009-07-21 19:28:10 +00003720 }
David Blaikieb61b8152013-01-17 08:49:22 +00003721 IdealInits.push_back(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00003722}
3723
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003724static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3725 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00003726}
3727
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003728static const void *GetKeyForMember(ASTContext &Context,
3729 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00003730 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003731 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00003732
David Blaikieb61b8152013-01-17 08:49:22 +00003733 return Member->getAnyMember();
Eli Friedman952c15d2009-07-21 19:28:10 +00003734}
3735
David Blaikie3fc2f912013-01-17 05:26:25 +00003736static void DiagnoseBaseOrMemInitializerOrder(
3737 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3738 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00003739 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00003740 return;
Mike Stump11289f42009-09-09 15:08:12 +00003741
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003742 // Don't check initializers order unless the warning is enabled at the
3743 // location of at least one initializer.
3744 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003745 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003746 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003747 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3748 Init->getSourceLocation())
David Blaikie9c902b52011-09-25 23:23:43 +00003749 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003750 ShouldCheckOrder = true;
3751 break;
3752 }
3753 }
3754 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00003755 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003756
John McCallbb7b6582010-04-10 07:37:23 +00003757 // Build the list of bases and members in the order that they'll
3758 // actually be initialized. The explicit initializers should be in
3759 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003760 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00003761
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003762 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3763
John McCallbb7b6582010-04-10 07:37:23 +00003764 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003765 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00003766 ClassDecl->vbases_begin(),
3767 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00003768 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00003769
John McCallbb7b6582010-04-10 07:37:23 +00003770 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003771 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00003772 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00003773 if (Base->isVirtual())
3774 continue;
John McCallbb7b6582010-04-10 07:37:23 +00003775 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00003776 }
Mike Stump11289f42009-09-09 15:08:12 +00003777
John McCallbb7b6582010-04-10 07:37:23 +00003778 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00003779 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregor556e5862011-10-10 17:22:13 +00003780 E = ClassDecl->field_end(); Field != E; ++Field) {
3781 if (Field->isUnnamedBitfield())
3782 continue;
3783
David Blaikieb61b8152013-01-17 08:49:22 +00003784 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00003785 }
3786
John McCallbb7b6582010-04-10 07:37:23 +00003787 unsigned NumIdealInits = IdealInitKeys.size();
3788 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00003789
Alexis Hunt1d792652011-01-08 20:30:50 +00003790 CXXCtorInitializer *PrevInit = 0;
David Blaikie3fc2f912013-01-17 05:26:25 +00003791 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003792 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003793 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00003794
3795 // Scan forward to try to find this initializer in the idealized
3796 // initializers list.
3797 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3798 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003799 break;
John McCallbb7b6582010-04-10 07:37:23 +00003800
3801 // If we didn't find this initializer, it must be because we
3802 // scanned past it on a previous iteration. That can only
3803 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00003804 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00003805 Sema::SemaDiagnosticBuilder D =
3806 SemaRef.Diag(PrevInit->getSourceLocation(),
3807 diag::warn_initializer_out_of_order);
3808
Francois Pichetd583da02010-12-04 09:14:42 +00003809 if (PrevInit->isAnyMemberInitializer())
3810 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003811 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003812 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003813
Francois Pichetd583da02010-12-04 09:14:42 +00003814 if (Init->isAnyMemberInitializer())
3815 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003816 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003817 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003818
3819 // Move back to the initializer's location in the ideal list.
3820 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3821 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003822 break;
John McCallbb7b6582010-04-10 07:37:23 +00003823
3824 assert(IdealIndex != NumIdealInits &&
3825 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003826 }
John McCallbb7b6582010-04-10 07:37:23 +00003827
3828 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003829 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00003830}
3831
John McCall23eebd92010-04-10 09:28:51 +00003832namespace {
3833bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003834 CXXCtorInitializer *Init,
3835 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00003836 if (!PrevInit) {
3837 PrevInit = Init;
3838 return false;
3839 }
3840
Douglas Gregorea306a12013-03-25 23:28:23 +00003841 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00003842 S.Diag(Init->getSourceLocation(),
3843 diag::err_multiple_mem_initialization)
3844 << Field->getDeclName()
3845 << Init->getSourceRange();
3846 else {
John McCall424cec92011-01-19 06:33:43 +00003847 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00003848 assert(BaseClass && "neither field nor base");
3849 S.Diag(Init->getSourceLocation(),
3850 diag::err_multiple_base_initialization)
3851 << QualType(BaseClass, 0)
3852 << Init->getSourceRange();
3853 }
3854 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3855 << 0 << PrevInit->getSourceRange();
3856
3857 return true;
3858}
3859
Alexis Hunt1d792652011-01-08 20:30:50 +00003860typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00003861typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3862
3863bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003864 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00003865 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00003866 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003867 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00003868 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00003869
3870 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00003871 if (Parent->isUnion()) {
3872 UnionEntry &En = Unions[Parent];
3873 if (En.first && En.first != Child) {
3874 S.Diag(Init->getSourceLocation(),
3875 diag::err_multiple_mem_union_initialization)
3876 << Field->getDeclName()
3877 << Init->getSourceRange();
3878 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3879 << 0 << En.second->getSourceRange();
3880 return true;
David Blaikie256ee192011-11-12 20:54:14 +00003881 }
3882 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00003883 En.first = Child;
3884 En.second = Init;
3885 }
David Blaikie0f65d592011-11-17 06:01:57 +00003886 if (!Parent->isAnonymousStructOrUnion())
3887 return false;
John McCall23eebd92010-04-10 09:28:51 +00003888 }
3889
3890 Child = Parent;
3891 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00003892 }
John McCall23eebd92010-04-10 09:28:51 +00003893
3894 return false;
3895}
3896}
3897
Anders Carlssone857b292010-04-02 03:37:03 +00003898/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00003899void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00003900 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00003901 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00003902 bool AnyErrors) {
3903 if (!ConstructorDecl)
3904 return;
3905
3906 AdjustDeclIfTemplate(ConstructorDecl);
3907
3908 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003909 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00003910
3911 if (!Constructor) {
3912 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3913 return;
3914 }
3915
John McCall23eebd92010-04-10 09:28:51 +00003916 // Mapping for the duplicate initializers check.
3917 // For member initializers, this is keyed with a FieldDecl*.
3918 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003919 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00003920
3921 // Mapping for the inconsistent anonymous-union initializers check.
3922 RedundantUnionMap MemberUnions;
3923
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003924 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003925 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003926 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00003927
Abramo Bagnara341d7832010-05-26 18:09:23 +00003928 // Set the source order index.
3929 Init->setSourceOrder(i);
3930
Francois Pichetd583da02010-12-04 09:14:42 +00003931 if (Init->isAnyMemberInitializer()) {
3932 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003933 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3934 CheckRedundantUnionInit(*this, Init, MemberUnions))
3935 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003936 } else if (Init->isBaseInitializer()) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003937 const void *Key =
3938 GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
John McCall23eebd92010-04-10 09:28:51 +00003939 if (CheckRedundantInit(*this, Init, Members[Key]))
3940 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003941 } else {
3942 assert(Init->isDelegatingInitializer());
3943 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00003944 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00003945 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00003946 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00003947 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00003948 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00003949 }
Alexis Hunt6118d662011-05-04 05:57:24 +00003950 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00003951 // Return immediately as the initializer is set.
3952 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003953 }
Anders Carlssone857b292010-04-02 03:37:03 +00003954 }
3955
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003956 if (HadError)
3957 return;
3958
David Blaikie3fc2f912013-01-17 05:26:25 +00003959 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00003960
David Blaikie3fc2f912013-01-17 05:26:25 +00003961 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00003962
Richard Trieuef64e942013-10-25 00:56:00 +00003963 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00003964}
3965
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003966void
John McCalla6309952010-03-16 21:39:52 +00003967Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3968 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00003969 // Ignore dependent contexts. Also ignore unions, since their members never
3970 // have destructors implicitly called.
3971 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00003972 return;
John McCall1064d7e2010-03-16 05:22:47 +00003973
3974 // FIXME: all the access-control diagnostics are positioned on the
3975 // field/base declaration. That's probably good; that said, the
3976 // user might reasonably want to know why the destructor is being
3977 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00003978
Anders Carlssondee9a302009-11-17 04:44:12 +00003979 // Non-static data members.
3980 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3981 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00003982 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00003983 if (Field->isInvalidDecl())
3984 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003985
3986 // Don't destroy incomplete or zero-length arrays.
3987 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3988 continue;
3989
Anders Carlssondee9a302009-11-17 04:44:12 +00003990 QualType FieldType = Context.getBaseElementType(Field->getType());
3991
3992 const RecordType* RT = FieldType->getAs<RecordType>();
3993 if (!RT)
3994 continue;
3995
3996 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003997 if (FieldClassDecl->isInvalidDecl())
3998 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00003999 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004000 continue;
Richard Smith921bd202012-02-26 09:11:52 +00004001 // The destructor for an implicit anonymous union member is never invoked.
4002 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4003 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00004004
Douglas Gregore71edda2010-07-01 22:47:18 +00004005 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004006 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004007 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004008 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00004009 << Field->getDeclName()
4010 << FieldType);
4011
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004012 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004013 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004014 }
4015
John McCall1064d7e2010-03-16 05:22:47 +00004016 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4017
Anders Carlssondee9a302009-11-17 04:44:12 +00004018 // Bases.
4019 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4020 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00004021 // Bases are always records in a well-formed non-dependent class.
4022 const RecordType *RT = Base->getType()->getAs<RecordType>();
4023
4024 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00004025 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00004026 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00004027
John McCall1064d7e2010-03-16 05:22:47 +00004028 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004029 // If our base class is invalid, we probably can't get its dtor anyway.
4030 if (BaseClassDecl->isInvalidDecl())
4031 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004032 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004033 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004034
Douglas Gregore71edda2010-07-01 22:47:18 +00004035 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004036 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004037
4038 // FIXME: caret should be on the start of the class name
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004039 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004040 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00004041 << Base->getType()
John McCall5dadb652012-04-07 03:04:20 +00004042 << Base->getSourceRange(),
4043 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00004044
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004045 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004046 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004047 }
4048
4049 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004050 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
4051 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00004052
4053 // Bases are always records in a well-formed non-dependent class.
John McCalldd1eca32012-04-09 21:51:56 +00004054 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004055
4056 // Ignore direct virtual bases.
4057 if (DirectVirtualBases.count(RT))
4058 continue;
4059
John McCall1064d7e2010-03-16 05:22:47 +00004060 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004061 // If our base class is invalid, we probably can't get its dtor anyway.
4062 if (BaseClassDecl->isInvalidDecl())
4063 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004064 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004065 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004066
Douglas Gregore71edda2010-07-01 22:47:18 +00004067 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004068 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00004069 if (CheckDestructorAccess(
4070 ClassDecl->getLocation(), Dtor,
4071 PDiag(diag::err_access_dtor_vbase)
4072 << Context.getTypeDeclType(ClassDecl) << VBase->getType(),
4073 Context.getTypeDeclType(ClassDecl)) ==
4074 AR_accessible) {
4075 CheckDerivedToBaseConversion(
4076 Context.getTypeDeclType(ClassDecl), VBase->getType(),
4077 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4078 SourceRange(), DeclarationName(), 0);
4079 }
John McCall1064d7e2010-03-16 05:22:47 +00004080
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004081 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004082 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004083 }
4084}
4085
John McCall48871652010-08-21 09:40:31 +00004086void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00004087 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004088 return;
Mike Stump11289f42009-09-09 15:08:12 +00004089
Mike Stump11289f42009-09-09 15:08:12 +00004090 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00004091 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00004092 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00004093 DiagnoseUninitializedFields(*this, Constructor);
4094 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004095}
4096
Mike Stump11289f42009-09-09 15:08:12 +00004097bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00004098 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregorae298422012-05-04 17:09:59 +00004099 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4100 unsigned DiagID;
4101 AbstractDiagSelID SelID;
4102
4103 public:
4104 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4105 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004106
4107 void diagnose(Sema &S, SourceLocation Loc, QualType T) LLVM_OVERRIDE {
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004108 if (Suppressed) return;
Douglas Gregorae298422012-05-04 17:09:59 +00004109 if (SelID == -1)
4110 S.Diag(Loc, DiagID) << T;
4111 else
4112 S.Diag(Loc, DiagID) << SelID << T;
4113 }
4114 } Diagnoser(DiagID, SelID);
4115
4116 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004117}
4118
Anders Carlssoneabf7702009-08-27 00:13:57 +00004119bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregorae298422012-05-04 17:09:59 +00004120 TypeDiagnoser &Diagnoser) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004121 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004122 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004123
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004124 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregorae298422012-05-04 17:09:59 +00004125 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004126
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004127 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004128 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004129 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004130 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00004131
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004132 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregorae298422012-05-04 17:09:59 +00004133 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004134 }
Mike Stump11289f42009-09-09 15:08:12 +00004135
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004136 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004137 if (!RT)
4138 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004139
John McCall67da35c2010-02-04 22:26:26 +00004140 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004141
John McCall02db245d2010-08-18 09:41:07 +00004142 // We can't answer whether something is abstract until it has a
4143 // definition. If it's currently being defined, we'll walk back
4144 // over all the declarations when we have a full definition.
4145 const CXXRecordDecl *Def = RD->getDefinition();
4146 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00004147 return false;
4148
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004149 if (!RD->isAbstract())
4150 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004151
Douglas Gregorae298422012-05-04 17:09:59 +00004152 Diagnoser.diagnose(*this, Loc, T);
John McCall02db245d2010-08-18 09:41:07 +00004153 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00004154
John McCall02db245d2010-08-18 09:41:07 +00004155 return true;
4156}
4157
4158void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4159 // Check if we've already emitted the list of pure virtual functions
4160 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004161 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00004162 return;
Mike Stump11289f42009-09-09 15:08:12 +00004163
Richard Smithbc46e432013-07-22 02:56:56 +00004164 // If the diagnostic is suppressed, don't emit the notes. We're only
4165 // going to emit them once, so try to attach them to a diagnostic we're
4166 // actually going to show.
4167 if (Diags.isLastDiagnosticIgnored())
4168 return;
4169
Douglas Gregor4165bd62010-03-23 23:47:56 +00004170 CXXFinalOverriderMap FinalOverriders;
4171 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00004172
Anders Carlssona2f74f32010-06-03 01:00:02 +00004173 // Keep a set of seen pure methods so we won't diagnose the same method
4174 // more than once.
4175 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4176
Douglas Gregor4165bd62010-03-23 23:47:56 +00004177 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4178 MEnd = FinalOverriders.end();
4179 M != MEnd;
4180 ++M) {
4181 for (OverridingMethods::iterator SO = M->second.begin(),
4182 SOEnd = M->second.end();
4183 SO != SOEnd; ++SO) {
4184 // C++ [class.abstract]p4:
4185 // A class is abstract if it contains or inherits at least one
4186 // pure virtual function for which the final overrider is pure
4187 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00004188
Douglas Gregor4165bd62010-03-23 23:47:56 +00004189 //
4190 if (SO->second.size() != 1)
4191 continue;
4192
4193 if (!SO->second.front().Method->isPure())
4194 continue;
4195
Anders Carlssona2f74f32010-06-03 01:00:02 +00004196 if (!SeenPureMethods.insert(SO->second.front().Method))
4197 continue;
4198
Douglas Gregor4165bd62010-03-23 23:47:56 +00004199 Diag(SO->second.front().Method->getLocation(),
4200 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00004201 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00004202 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004203 }
4204
4205 if (!PureVirtualClassDiagSet)
4206 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4207 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004208}
4209
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004210namespace {
John McCall02db245d2010-08-18 09:41:07 +00004211struct AbstractUsageInfo {
4212 Sema &S;
4213 CXXRecordDecl *Record;
4214 CanQualType AbstractType;
4215 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00004216
John McCall02db245d2010-08-18 09:41:07 +00004217 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4218 : S(S), Record(Record),
4219 AbstractType(S.Context.getCanonicalType(
4220 S.Context.getTypeDeclType(Record))),
4221 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004222
John McCall02db245d2010-08-18 09:41:07 +00004223 void DiagnoseAbstractType() {
4224 if (Invalid) return;
4225 S.DiagnoseAbstractType(Record);
4226 Invalid = true;
4227 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00004228
John McCall02db245d2010-08-18 09:41:07 +00004229 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4230};
4231
4232struct CheckAbstractUsage {
4233 AbstractUsageInfo &Info;
4234 const NamedDecl *Ctx;
4235
4236 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4237 : Info(Info), Ctx(Ctx) {}
4238
4239 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4240 switch (TL.getTypeLocClass()) {
4241#define ABSTRACT_TYPELOC(CLASS, PARENT)
4242#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00004243 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00004244#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004245 }
John McCall02db245d2010-08-18 09:41:07 +00004246 }
Mike Stump11289f42009-09-09 15:08:12 +00004247
John McCall02db245d2010-08-18 09:41:07 +00004248 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4249 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004250 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4251 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00004252 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004253
4254 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00004255 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004256 }
John McCall02db245d2010-08-18 09:41:07 +00004257 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004258
John McCall02db245d2010-08-18 09:41:07 +00004259 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4260 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4261 }
Mike Stump11289f42009-09-09 15:08:12 +00004262
John McCall02db245d2010-08-18 09:41:07 +00004263 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4264 // Visit the type parameters from a permissive context.
4265 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4266 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4267 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4268 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4269 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4270 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004271 }
John McCall02db245d2010-08-18 09:41:07 +00004272 }
Mike Stump11289f42009-09-09 15:08:12 +00004273
John McCall02db245d2010-08-18 09:41:07 +00004274 // Visit pointee types from a permissive context.
4275#define CheckPolymorphic(Type) \
4276 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4277 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4278 }
4279 CheckPolymorphic(PointerTypeLoc)
4280 CheckPolymorphic(ReferenceTypeLoc)
4281 CheckPolymorphic(MemberPointerTypeLoc)
4282 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00004283 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00004284
John McCall02db245d2010-08-18 09:41:07 +00004285 /// Handle all the types we haven't given a more specific
4286 /// implementation for above.
4287 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4288 // Every other kind of type that we haven't called out already
4289 // that has an inner type is either (1) sugar or (2) contains that
4290 // inner type in some way as a subobject.
4291 if (TypeLoc Next = TL.getNextTypeLoc())
4292 return Visit(Next, Sel);
4293
4294 // If there's no inner type and we're in a permissive context,
4295 // don't diagnose.
4296 if (Sel == Sema::AbstractNone) return;
4297
4298 // Check whether the type matches the abstract type.
4299 QualType T = TL.getType();
4300 if (T->isArrayType()) {
4301 Sel = Sema::AbstractArrayType;
4302 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004303 }
John McCall02db245d2010-08-18 09:41:07 +00004304 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4305 if (CT != Info.AbstractType) return;
4306
4307 // It matched; do some magic.
4308 if (Sel == Sema::AbstractArrayType) {
4309 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4310 << T << TL.getSourceRange();
4311 } else {
4312 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4313 << Sel << T << TL.getSourceRange();
4314 }
4315 Info.DiagnoseAbstractType();
4316 }
4317};
4318
4319void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4320 Sema::AbstractDiagSelID Sel) {
4321 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4322}
4323
4324}
4325
4326/// Check for invalid uses of an abstract type in a method declaration.
4327static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4328 CXXMethodDecl *MD) {
4329 // No need to do the check on definitions, which require that
4330 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004331 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00004332 return;
4333
4334 // For safety's sake, just ignore it if we don't have type source
4335 // information. This should never happen for non-implicit methods,
4336 // but...
4337 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4338 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4339}
4340
4341/// Check for invalid uses of an abstract type within a class definition.
4342static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4343 CXXRecordDecl *RD) {
4344 for (CXXRecordDecl::decl_iterator
4345 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4346 Decl *D = *I;
4347 if (D->isImplicit()) continue;
4348
4349 // Methods and method templates.
4350 if (isa<CXXMethodDecl>(D)) {
4351 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4352 } else if (isa<FunctionTemplateDecl>(D)) {
4353 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4354 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4355
4356 // Fields and static variables.
4357 } else if (isa<FieldDecl>(D)) {
4358 FieldDecl *FD = cast<FieldDecl>(D);
4359 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4360 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4361 } else if (isa<VarDecl>(D)) {
4362 VarDecl *VD = cast<VarDecl>(D);
4363 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4364 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4365
4366 // Nested classes and class templates.
4367 } else if (isa<CXXRecordDecl>(D)) {
4368 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4369 } else if (isa<ClassTemplateDecl>(D)) {
4370 CheckAbstractClassUsage(Info,
4371 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4372 }
4373 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004374}
4375
Douglas Gregorc99f1552009-12-03 18:33:45 +00004376/// \brief Perform semantic checks on a class definition that has been
4377/// completing, introducing implicitly-declared members, checking for
4378/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004379void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00004380 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00004381 return;
4382
John McCall02db245d2010-08-18 09:41:07 +00004383 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4384 AbstractUsageInfo Info(*this, Record);
4385 CheckAbstractClassUsage(Info, Record);
4386 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00004387
4388 // If this is not an aggregate type and has no user-declared constructor,
4389 // complain about any non-static data members of reference or const scalar
4390 // type, since they will never get initializers.
4391 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00004392 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4393 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004394 bool Complained = false;
4395 for (RecordDecl::field_iterator F = Record->field_begin(),
4396 FEnd = Record->field_end();
4397 F != FEnd; ++F) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004398 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004399 continue;
4400
Douglas Gregor454a5b62010-04-15 00:00:53 +00004401 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00004402 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004403 if (!Complained) {
4404 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4405 << Record->getTagKind() << Record;
4406 Complained = true;
4407 }
4408
4409 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4410 << F->getType()->isReferenceType()
4411 << F->getDeclName();
4412 }
4413 }
4414 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004415
Anders Carlssone771e762011-01-25 18:08:22 +00004416 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00004417 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00004418
4419 if (Record->getIdentifier()) {
4420 // C++ [class.mem]p13:
4421 // If T is the name of a class, then each of the following shall have a
4422 // name different from T:
4423 // - every member of every anonymous union that is a member of class T.
4424 //
4425 // C++ [class.mem]p14:
4426 // In addition, if class T has a user-declared constructor (12.1), every
4427 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00004428 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4429 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4430 ++I) {
4431 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004432 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4433 isa<IndirectFieldDecl>(D)) {
4434 Diag(D->getLocation(), diag::err_member_name_of_class)
4435 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00004436 break;
4437 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00004438 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00004439 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004440
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004441 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00004442 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004443 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004444 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004445 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4446 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4447 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004448
David Majnemera5433082013-10-18 00:33:31 +00004449 if (Record->isAbstract()) {
4450 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4451 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4452 << FA->isSpelledAsSealed();
4453 DiagnoseAbstractType(Record);
4454 }
David Blaikie348df502012-09-21 03:21:07 +00004455 }
4456
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004457 if (!Record->isDependentType()) {
4458 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4459 MEnd = Record->method_end();
4460 M != MEnd; ++M) {
Richard Smithbd305122012-12-11 01:14:52 +00004461 // See if a method overloads virtual methods in a base
4462 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004463 if (!M->isStatic())
Eli Friedmanaf65120b2013-09-05 23:51:03 +00004464 DiagnoseHiddenVirtualMethods(*M);
Richard Smithbd305122012-12-11 01:14:52 +00004465
4466 // Check whether the explicitly-defaulted special members are valid.
4467 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4468 CheckExplicitlyDefaultedSpecialMember(*M);
4469
4470 // For an explicitly defaulted or deleted special member, we defer
4471 // determining triviality until the class is complete. That time is now!
4472 if (!M->isImplicit() && !M->isUserProvided()) {
4473 CXXSpecialMember CSM = getSpecialMember(*M);
4474 if (CSM != CXXInvalid) {
4475 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4476
4477 // Inform the class that we've finished declaring this member.
4478 Record->finishedDefaultedOrDeletedMember(*M);
4479 }
4480 }
4481 }
Hans Wennborge955e392013-12-17 17:49:22 +00004482
4483 if (Record->hasUserDeclaredDestructor()) {
4484 // The Microsoft ABI requires that we perform the destructor body
4485 // checks (i.e. operator delete() lookup) in any translataion unit, as
4486 // any translation unit may need to emit a deleting destructor.
4487 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4488 !Record->getDestructor()->isDeleted())
4489 CheckDestructor(Record->getDestructor());
4490 }
Richard Smithbd305122012-12-11 01:14:52 +00004491 }
4492
4493 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4494 // function that is not a constructor declares that member function to be
4495 // const. [...] The class of which that function is a member shall be
4496 // a literal type.
4497 //
4498 // If the class has virtual bases, any constexpr members will already have
4499 // been diagnosed by the checks performed on the member declaration, so
4500 // suppress this (less useful) diagnostic.
4501 //
4502 // We delay this until we know whether an explicitly-defaulted (or deleted)
4503 // destructor for the class is trivial.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004504 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smithbd305122012-12-11 01:14:52 +00004505 !Record->isLiteral() && !Record->getNumVBases()) {
4506 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4507 MEnd = Record->method_end();
4508 M != MEnd; ++M) {
4509 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4510 switch (Record->getTemplateSpecializationKind()) {
4511 case TSK_ImplicitInstantiation:
4512 case TSK_ExplicitInstantiationDeclaration:
4513 case TSK_ExplicitInstantiationDefinition:
4514 // If a template instantiates to a non-literal type, but its members
4515 // instantiate to constexpr functions, the template is technically
4516 // ill-formed, but we allow it for sanity.
4517 continue;
4518
4519 case TSK_Undeclared:
4520 case TSK_ExplicitSpecialization:
4521 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4522 diag::err_constexpr_method_non_literal);
4523 break;
4524 }
4525
4526 // Only produce one error per class.
4527 break;
4528 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004529 }
4530 }
Sebastian Redl08905022011-02-05 19:23:19 +00004531
Warren Hunt8f8bad72013-10-11 20:19:00 +00004532 // Check to see if we're trying to lay out a struct using the ms_struct
4533 // attribute that is dynamic.
4534 if (Record->isMsStruct(Context) && Record->isDynamicClass()) {
4535 Diag(Record->getLocation(), diag::warn_pragma_ms_struct_failed);
4536 Record->dropAttr<MsStructAttr>();
4537 }
4538
Richard Smithc2bc61b2013-03-18 21:12:30 +00004539 // Declare inheriting constructors. We do this eagerly here because:
4540 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redl08905022011-02-05 19:23:19 +00004541 // constructors from different classes.
4542 // - The lazy declaration of the other implicit constructors is so as to not
4543 // waste space and performance on classes that are not meant to be
4544 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smithc2bc61b2013-03-18 21:12:30 +00004545 // have inheriting constructors.
4546 DeclareInheritingConstructors(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004547}
4548
Richard Smith41c35d62013-11-27 03:39:20 +00004549/// Look up the special member function that would be called by a special
4550/// member function for a subobject of class type.
4551///
4552/// \param Class The class type of the subobject.
4553/// \param CSM The kind of special member function.
4554/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4555/// \param ConstRHS True if this is a copy operation with a const object
4556/// on its RHS, that is, if the argument to the outer special member
4557/// function is 'const' and this is not a field marked 'mutable'.
4558static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4559 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4560 unsigned FieldQuals, bool ConstRHS) {
4561 unsigned LHSQuals = 0;
4562 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4563 LHSQuals = FieldQuals;
4564
4565 unsigned RHSQuals = FieldQuals;
4566 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4567 RHSQuals = 0;
4568 else if (ConstRHS)
4569 RHSQuals |= Qualifiers::Const;
4570
4571 return S.LookupSpecialMember(Class, CSM,
4572 RHSQuals & Qualifiers::Const,
4573 RHSQuals & Qualifiers::Volatile,
4574 false,
4575 LHSQuals & Qualifiers::Const,
4576 LHSQuals & Qualifiers::Volatile);
4577}
4578
Richard Smithb5800092012-06-10 05:43:50 +00004579/// Is the special member function which would be selected to perform the
4580/// specified operation on the specified class type a constexpr constructor?
4581static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4582 Sema::CXXSpecialMember CSM,
Richard Smith41c35d62013-11-27 03:39:20 +00004583 unsigned Quals, bool ConstRHS) {
Richard Smithb5800092012-06-10 05:43:50 +00004584 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00004585 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00004586 if (!SMOR || !SMOR->getMethod())
4587 // A constructor we wouldn't select can't be "involved in initializing"
4588 // anything.
4589 return true;
4590 return SMOR->getMethod()->isConstexpr();
4591}
4592
4593/// Determine whether the specified special member function would be constexpr
4594/// if it were implicitly defined.
4595static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4596 Sema::CXXSpecialMember CSM,
4597 bool ConstArg) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004598 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00004599 return false;
4600
4601 // C++11 [dcl.constexpr]p4:
4602 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00004603 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00004604 switch (CSM) {
4605 case Sema::CXXDefaultConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004606 // Since default constructor lookup is essentially trivial (and cannot
4607 // involve, for instance, template instantiation), we compute whether a
4608 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4609 //
4610 // This is important for performance; we need to know whether the default
4611 // constructor is constexpr to determine whether the type is a literal type.
4612 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4613
Richard Smithb5800092012-06-10 05:43:50 +00004614 case Sema::CXXCopyConstructor:
4615 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004616 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00004617 break;
4618
4619 case Sema::CXXCopyAssignment:
4620 case Sema::CXXMoveAssignment:
Richard Smith99005e62013-05-07 03:19:20 +00004621 if (!S.getLangOpts().CPlusPlus1y)
4622 return false;
4623 // In C++1y, we need to perform overload resolution.
4624 Ctor = false;
4625 break;
4626
Richard Smithb5800092012-06-10 05:43:50 +00004627 case Sema::CXXDestructor:
4628 case Sema::CXXInvalid:
4629 return false;
4630 }
4631
4632 // -- if the class is a non-empty union, or for each non-empty anonymous
4633 // union member of a non-union class, exactly one non-static data member
4634 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00004635 //
4636 // If we squint, this is guaranteed, since exactly one non-static data member
4637 // will be initialized (if the constructor isn't deleted), we just don't know
4638 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00004639 if (Ctor && ClassDecl->isUnion())
Richard Smith4086a132012-06-10 07:07:24 +00004640 return true;
Richard Smithb5800092012-06-10 05:43:50 +00004641
4642 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00004643 if (Ctor && ClassDecl->getNumVBases())
4644 return false;
4645
4646 // C++1y [class.copy]p26:
4647 // -- [the class] is a literal type, and
4648 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00004649 return false;
4650
4651 // -- every constructor involved in initializing [...] base class
4652 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00004653 // -- the assignment operator selected to copy/move each direct base
4654 // class is a constexpr function, and
Richard Smithb5800092012-06-10 05:43:50 +00004655 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4656 BEnd = ClassDecl->bases_end();
4657 B != BEnd; ++B) {
4658 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4659 if (!BaseType) continue;
4660
4661 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004662 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smithb5800092012-06-10 05:43:50 +00004663 return false;
4664 }
4665
4666 // -- every constructor involved in initializing non-static data members
4667 // [...] shall be a constexpr constructor;
4668 // -- every non-static data member and base class sub-object shall be
4669 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00004670 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00004671 // thereof), the assignment operator selected to copy/move that member is
4672 // a constexpr function
Richard Smithb5800092012-06-10 05:43:50 +00004673 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4674 FEnd = ClassDecl->field_end();
4675 F != FEnd; ++F) {
4676 if (F->isInvalidDecl())
4677 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00004678 QualType BaseType = S.Context.getBaseElementType(F->getType());
4679 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00004680 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004681 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
4682 BaseType.getCVRQualifiers(),
4683 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00004684 return false;
Richard Smithb5800092012-06-10 05:43:50 +00004685 }
4686 }
4687
4688 // All OK, it's constexpr!
4689 return true;
4690}
4691
Richard Smithd3b5c9082012-07-27 04:22:15 +00004692static Sema::ImplicitExceptionSpecification
4693computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4694 switch (S.getSpecialMember(MD)) {
4695 case Sema::CXXDefaultConstructor:
4696 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4697 case Sema::CXXCopyConstructor:
4698 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4699 case Sema::CXXCopyAssignment:
4700 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4701 case Sema::CXXMoveConstructor:
4702 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4703 case Sema::CXXMoveAssignment:
4704 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4705 case Sema::CXXDestructor:
4706 return S.ComputeDefaultedDtorExceptionSpec(MD);
4707 case Sema::CXXInvalid:
4708 break;
4709 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00004710 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4711 "only special members have implicit exception specs");
4712 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00004713}
4714
Richard Smith7f782272012-07-30 23:48:14 +00004715static void
4716updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4717 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4718 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4719 ExceptSpec.getEPI(EPI);
Richard Smith185be182013-04-10 05:48:59 +00004720 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004721 FPT->getParamTypes(), EPI));
Richard Smith7f782272012-07-30 23:48:14 +00004722}
4723
Reid Kleckner78af0702013-08-27 23:08:25 +00004724static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4725 CXXMethodDecl *MD) {
4726 FunctionProtoType::ExtProtoInfo EPI;
4727
4728 // Build an exception specification pointing back at this member.
4729 EPI.ExceptionSpecType = EST_Unevaluated;
4730 EPI.ExceptionSpecDecl = MD;
4731
4732 // Set the calling convention to the default for C++ instance methods.
4733 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4734 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4735 /*IsCXXMethod=*/true));
4736 return EPI;
4737}
4738
Richard Smithd3b5c9082012-07-27 04:22:15 +00004739void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4740 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4741 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4742 return;
4743
Richard Smith7f782272012-07-30 23:48:14 +00004744 // Evaluate the exception specification.
4745 ImplicitExceptionSpecification ExceptSpec =
4746 computeImplicitExceptionSpec(*this, Loc, MD);
4747
4748 // Update the type of the special member to use it.
4749 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4750
4751 // A user-provided destructor can be defined outside the class. When that
4752 // happens, be sure to update the exception specification on both
4753 // declarations.
4754 const FunctionProtoType *CanonicalFPT =
4755 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4756 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4757 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4758 CanonicalFPT, ExceptSpec);
Richard Smithd3b5c9082012-07-27 04:22:15 +00004759}
4760
Richard Smithb9e90b12012-05-15 04:39:51 +00004761void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4762 CXXRecordDecl *RD = MD->getParent();
4763 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004764
Richard Smithb9e90b12012-05-15 04:39:51 +00004765 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4766 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00004767
4768 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00004769 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00004770 bool First = MD == MD->getCanonicalDecl();
4771
4772 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004773
4774 // C++11 [dcl.fct.def.default]p1:
4775 // A function that is explicitly defaulted shall
4776 // -- be a special member function (checked elsewhere),
4777 // -- have the same type (except for ref-qualifiers, and except that a
4778 // copy operation can take a non-const reference) as an implicit
4779 // declaration, and
4780 // -- not have default arguments.
4781 unsigned ExpectedParams = 1;
4782 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4783 ExpectedParams = 0;
4784 if (MD->getNumParams() != ExpectedParams) {
4785 // This also checks for default arguments: a copy or move constructor with a
4786 // default argument is classified as a default constructor, and assignment
4787 // operations and destructors can't have default arguments.
4788 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4789 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00004790 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00004791 } else if (MD->isVariadic()) {
4792 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4793 << CSM << MD->getSourceRange();
4794 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00004795 }
4796
Richard Smithb9e90b12012-05-15 04:39:51 +00004797 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00004798
Richard Smithb5800092012-06-10 05:43:50 +00004799 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00004800 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00004801 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00004802 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00004803 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00004804
Richard Smithb9e90b12012-05-15 04:39:51 +00004805 QualType ReturnType = Context.VoidTy;
4806 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4807 // Check for return type matching.
4808 ReturnType = Type->getResultType();
4809 QualType ExpectedReturnType =
4810 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4811 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4812 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4813 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4814 HadError = true;
4815 }
4816
4817 // A defaulted special member cannot have cv-qualifiers.
4818 if (Type->getTypeQuals()) {
4819 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smith99005e62013-05-07 03:19:20 +00004820 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smithb9e90b12012-05-15 04:39:51 +00004821 HadError = true;
4822 }
4823 }
4824
4825 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00004826 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00004827 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004828 if (ExpectedParams && ArgType->isReferenceType()) {
4829 // Argument must be reference to possibly-const T.
4830 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00004831 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00004832
4833 if (ReferentType.isVolatileQualified()) {
4834 Diag(MD->getLocation(),
4835 diag::err_defaulted_special_member_volatile_param) << CSM;
4836 HadError = true;
4837 }
4838
Richard Smithb5800092012-06-10 05:43:50 +00004839 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00004840 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4841 Diag(MD->getLocation(),
4842 diag::err_defaulted_special_member_copy_const_param)
4843 << (CSM == CXXCopyAssignment);
4844 // FIXME: Explain why this special member can't be const.
4845 } else {
4846 Diag(MD->getLocation(),
4847 diag::err_defaulted_special_member_move_const_param)
4848 << (CSM == CXXMoveAssignment);
4849 }
4850 HadError = true;
4851 }
Richard Smithb9e90b12012-05-15 04:39:51 +00004852 } else if (ExpectedParams) {
4853 // A copy assignment operator can take its argument by value, but a
4854 // defaulted one cannot.
4855 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00004856 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00004857 HadError = true;
4858 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00004859
Richard Smithcc36f692011-12-22 02:22:31 +00004860 // C++11 [dcl.fct.def.default]p2:
4861 // An explicitly-defaulted function may be declared constexpr only if it
4862 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00004863 // Do not apply this rule to members of class templates, since core issue 1358
4864 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00004865 // functions which cannot be constexpr (for non-constructors in C++11 and for
4866 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00004867 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4868 HasConstParam);
Richard Smith99005e62013-05-07 03:19:20 +00004869 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4870 : isa<CXXConstructorDecl>(MD)) &&
4871 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00004872 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4873 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00004874 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00004875 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00004876 }
Richard Smithbd305122012-12-11 01:14:52 +00004877
Richard Smithcc36f692011-12-22 02:22:31 +00004878 // and may have an explicit exception-specification only if it is compatible
4879 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00004880 if (Type->hasExceptionSpec()) {
4881 // Delay the check if this is the first declaration of the special member,
4882 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00004883 if (First) {
4884 // If the exception specification needs to be instantiated, do so now,
4885 // before we clobber it with an EST_Unevaluated specification below.
4886 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4887 InstantiateExceptionSpec(MD->getLocStart(), MD);
4888 Type = MD->getType()->getAs<FunctionProtoType>();
4889 }
Richard Smithbd305122012-12-11 01:14:52 +00004890 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00004891 } else
Richard Smithbd305122012-12-11 01:14:52 +00004892 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4893 }
Richard Smithcc36f692011-12-22 02:22:31 +00004894
4895 // If a function is explicitly defaulted on its first declaration,
4896 if (First) {
4897 // -- it is implicitly considered to be constexpr if the implicit
4898 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00004899 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00004900
Richard Smithb9e90b12012-05-15 04:39:51 +00004901 // -- it is implicitly considered to have the same exception-specification
4902 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00004903 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4904 EPI.ExceptionSpecType = EST_Unevaluated;
4905 EPI.ExceptionSpecDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00004906 MD->setType(Context.getFunctionType(ReturnType,
4907 ArrayRef<QualType>(&ArgType,
4908 ExpectedParams),
4909 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00004910 }
4911
Richard Smithb9e90b12012-05-15 04:39:51 +00004912 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004913 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00004914 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004915 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00004916 // C++11 [dcl.fct.def.default]p4:
4917 // [For a] user-provided explicitly-defaulted function [...] if such a
4918 // function is implicitly defined as deleted, the program is ill-formed.
4919 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4920 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004921 }
4922 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00004923
Richard Smithb9e90b12012-05-15 04:39:51 +00004924 if (HadError)
4925 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00004926}
4927
Richard Smithbd305122012-12-11 01:14:52 +00004928/// Check whether the exception specification provided for an
4929/// explicitly-defaulted special member matches the exception specification
4930/// that would have been generated for an implicit special member, per
4931/// C++11 [dcl.fct.def.default]p2.
4932void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4933 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4934 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00004935 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4936 /*IsCXXMethod=*/true);
4937 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smithbd305122012-12-11 01:14:52 +00004938 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4939 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004940 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00004941
4942 // Ensure that it matches.
4943 CheckEquivalentExceptionSpec(
4944 PDiag(diag::err_incorrect_defaulted_exception_spec)
4945 << getSpecialMember(MD), PDiag(),
4946 ImplicitType, SourceLocation(),
4947 SpecifiedType, MD->getLocation());
4948}
4949
Alp Tokerae3a9442013-10-18 05:54:19 +00004950void Sema::CheckDelayedMemberExceptionSpecs() {
4951 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
4952 2> Checks;
4953 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
Richard Smithbd305122012-12-11 01:14:52 +00004954
Alp Tokerae3a9442013-10-18 05:54:19 +00004955 std::swap(Checks, DelayedDestructorExceptionSpecChecks);
4956 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
4957
4958 // Perform any deferred checking of exception specifications for virtual
4959 // destructors.
4960 for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
4961 const CXXDestructorDecl *Dtor = Checks[i].first;
4962 assert(!Dtor->getParent()->isDependentType() &&
4963 "Should not ever add destructors of templates into the list.");
4964 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
4965 }
4966
4967 // Check that any explicitly-defaulted methods have exception specifications
4968 // compatible with their implicit exception specifications.
4969 for (unsigned I = 0, N = Specs.size(); I != N; ++I)
4970 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
4971 Specs[I].second);
Richard Smithbd305122012-12-11 01:14:52 +00004972}
4973
Richard Smithd951a1d2012-02-18 02:02:13 +00004974namespace {
4975struct SpecialMemberDeletionInfo {
4976 Sema &S;
4977 CXXMethodDecl *MD;
4978 Sema::CXXSpecialMember CSM;
Richard Smith852265f2012-03-30 20:53:28 +00004979 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00004980
4981 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00004982 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00004983 SourceLocation Loc;
4984
4985 bool AllFieldsAreConst;
4986
4987 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith852265f2012-03-30 20:53:28 +00004988 Sema::CXXSpecialMember CSM, bool Diagnose)
4989 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smithd951a1d2012-02-18 02:02:13 +00004990 IsConstructor(false), IsAssignment(false), IsMove(false),
Richard Smith41c35d62013-11-27 03:39:20 +00004991 ConstArg(false), Loc(MD->getLocation()),
Richard Smithd951a1d2012-02-18 02:02:13 +00004992 AllFieldsAreConst(true) {
4993 switch (CSM) {
4994 case Sema::CXXDefaultConstructor:
4995 case Sema::CXXCopyConstructor:
4996 IsConstructor = true;
4997 break;
4998 case Sema::CXXMoveConstructor:
4999 IsConstructor = true;
5000 IsMove = true;
5001 break;
5002 case Sema::CXXCopyAssignment:
5003 IsAssignment = true;
5004 break;
5005 case Sema::CXXMoveAssignment:
5006 IsAssignment = true;
5007 IsMove = true;
5008 break;
5009 case Sema::CXXDestructor:
5010 break;
5011 case Sema::CXXInvalid:
5012 llvm_unreachable("invalid special member kind");
5013 }
5014
5015 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00005016 if (const ReferenceType *RT =
5017 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5018 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00005019 }
5020 }
5021
5022 bool inUnion() const { return MD->getParent()->isUnion(); }
5023
5024 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00005025 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00005026 unsigned Quals, bool IsMutable) {
5027 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5028 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00005029 }
5030
Richard Smith852265f2012-03-30 20:53:28 +00005031 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00005032
Richard Smith852265f2012-03-30 20:53:28 +00005033 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00005034 bool shouldDeleteForField(FieldDecl *FD);
5035 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00005036
Richard Smithaf136f82012-07-18 03:51:16 +00005037 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5038 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00005039 bool shouldDeleteForSubobjectCall(Subobject Subobj,
5040 Sema::SpecialMemberOverloadResult *SMOR,
5041 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00005042
5043 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00005044};
5045}
5046
John McCalld4274212012-04-09 20:53:23 +00005047/// Is the given special member inaccessible when used on the given
5048/// sub-object.
5049bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5050 CXXMethodDecl *target) {
5051 /// If we're operating on a base class, the object type is the
5052 /// type of this special member.
5053 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005054 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00005055 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5056 objectTy = S.Context.getTypeDeclType(MD->getParent());
5057 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5058
5059 // If we're operating on a field, the object type is the type of the field.
5060 } else {
5061 objectTy = S.Context.getTypeDeclType(target->getParent());
5062 }
5063
5064 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5065}
5066
Richard Smith852265f2012-03-30 20:53:28 +00005067/// Check whether we should delete a special member due to the implicit
5068/// definition containing a call to a special member of a subobject.
5069bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5070 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5071 bool IsDtorCallInCtor) {
5072 CXXMethodDecl *Decl = SMOR->getMethod();
5073 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5074
5075 int DiagKind = -1;
5076
5077 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5078 DiagKind = !Decl ? 0 : 1;
5079 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5080 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00005081 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00005082 DiagKind = 3;
5083 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5084 !Decl->isTrivial()) {
5085 // A member of a union must have a trivial corresponding special member.
5086 // As a weird special case, a destructor call from a union's constructor
5087 // must be accessible and non-deleted, but need not be trivial. Such a
5088 // destructor is never actually called, but is semantically checked as
5089 // if it were.
5090 DiagKind = 4;
5091 }
5092
5093 if (DiagKind == -1)
5094 return false;
5095
5096 if (Diagnose) {
5097 if (Field) {
5098 S.Diag(Field->getLocation(),
5099 diag::note_deleted_special_member_class_subobject)
5100 << CSM << MD->getParent() << /*IsField*/true
5101 << Field << DiagKind << IsDtorCallInCtor;
5102 } else {
5103 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5104 S.Diag(Base->getLocStart(),
5105 diag::note_deleted_special_member_class_subobject)
5106 << CSM << MD->getParent() << /*IsField*/false
5107 << Base->getType() << DiagKind << IsDtorCallInCtor;
5108 }
5109
5110 if (DiagKind == 1)
5111 S.NoteDeletedFunction(Decl);
5112 // FIXME: Explain inaccessibility if DiagKind == 3.
5113 }
5114
5115 return true;
5116}
5117
Richard Smith921bd202012-02-26 09:11:52 +00005118/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00005119/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00005120bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00005121 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00005122 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00005123 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00005124
5125 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00005126 // -- any direct or virtual base class, or non-static data member with no
5127 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00005128 // either M has no default constructor or overload resolution as applied
5129 // to M's default constructor results in an ambiguity or in a function
5130 // that is deleted or inaccessible
5131 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5132 // -- a direct or virtual base class B that cannot be copied/moved because
5133 // overload resolution, as applied to B's corresponding special member,
5134 // results in an ambiguity or a function that is deleted or inaccessible
5135 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00005136 // C++11 [class.dtor]p5:
5137 // -- any direct or virtual base class [...] has a type with a destructor
5138 // that is deleted or inaccessible
5139 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005140 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00005141 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5142 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005143 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005144
Richard Smith852265f2012-03-30 20:53:28 +00005145 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5146 // -- any direct or virtual base class or non-static data member has a
5147 // type with a destructor that is deleted or inaccessible
5148 if (IsConstructor) {
5149 Sema::SpecialMemberOverloadResult *SMOR =
5150 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5151 false, false, false, false, false);
5152 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5153 return true;
5154 }
5155
Richard Smith921bd202012-02-26 09:11:52 +00005156 return false;
5157}
5158
5159/// Check whether we should delete a special member function due to the class
5160/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00005161bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005162 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smithaf136f82012-07-18 03:51:16 +00005163 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00005164}
5165
5166/// Check whether we should delete a special member function due to the class
5167/// having a particular non-static data member.
5168bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5169 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5170 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5171
5172 if (CSM == Sema::CXXDefaultConstructor) {
5173 // For a default constructor, all references must be initialized in-class
5174 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00005175 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5176 if (Diagnose)
5177 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5178 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005179 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005180 }
Richard Smith619ecdc2012-02-27 06:07:25 +00005181 // C++11 [class.ctor]p5: any non-variant non-static data member of
5182 // const-qualified type (or array thereof) with no
5183 // brace-or-equal-initializer does not have a user-provided default
5184 // constructor.
5185 if (!inUnion() && FieldType.isConstQualified() &&
5186 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00005187 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5188 if (Diagnose)
5189 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005190 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00005191 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005192 }
5193
5194 if (inUnion() && !FieldType.isConstQualified())
5195 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005196 } else if (CSM == Sema::CXXCopyConstructor) {
5197 // For a copy constructor, data members must not be of rvalue reference
5198 // type.
Richard Smith852265f2012-03-30 20:53:28 +00005199 if (FieldType->isRValueReferenceType()) {
5200 if (Diagnose)
5201 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5202 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00005203 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005204 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005205 } else if (IsAssignment) {
5206 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00005207 if (FieldType->isReferenceType()) {
5208 if (Diagnose)
5209 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5210 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005211 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005212 }
5213 if (!FieldRecord && FieldType.isConstQualified()) {
5214 // C++11 [class.copy]p23:
5215 // -- a non-static data member of const non-class type (or array thereof)
5216 if (Diagnose)
5217 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005218 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00005219 return true;
5220 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005221 }
5222
5223 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005224 // Some additional restrictions exist on the variant members.
5225 if (!inUnion() && FieldRecord->isUnion() &&
5226 FieldRecord->isAnonymousStructOrUnion()) {
5227 bool AllVariantFieldsAreConst = true;
5228
Richard Smith5704fe82012-03-29 19:00:10 +00005229 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smithd951a1d2012-02-18 02:02:13 +00005230 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
5231 UE = FieldRecord->field_end();
5232 UI != UE; ++UI) {
5233 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00005234
5235 if (!UnionFieldType.isConstQualified())
5236 AllVariantFieldsAreConst = false;
5237
Richard Smith921bd202012-02-26 09:11:52 +00005238 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5239 if (UnionFieldRecord &&
Richard Smithaf136f82012-07-18 03:51:16 +00005240 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
5241 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00005242 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005243 }
5244
5245 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00005246 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith852265f2012-03-30 20:53:28 +00005247 FieldRecord->field_begin() != FieldRecord->field_end()) {
5248 if (Diagnose)
5249 S.Diag(FieldRecord->getLocation(),
5250 diag::note_deleted_default_ctor_all_const)
5251 << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00005252 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005253 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005254
Richard Smith5704fe82012-03-29 19:00:10 +00005255 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00005256 // This is technically non-conformant, but sanity demands it.
5257 return false;
5258 }
5259
Richard Smithaf136f82012-07-18 03:51:16 +00005260 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5261 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00005262 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005263 }
5264
5265 return false;
5266}
5267
5268/// C++11 [class.ctor] p5:
5269/// A defaulted default constructor for a class X is defined as deleted if
5270/// X is a union and all of its variant members are of const-qualified type.
5271bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00005272 // This is a silly definition, because it gives an empty union a deleted
5273 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00005274 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5275 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
5276 if (Diagnose)
5277 S.Diag(MD->getParent()->getLocation(),
5278 diag::note_deleted_default_ctor_all_const)
5279 << MD->getParent() << /*not anonymous union*/0;
5280 return true;
5281 }
5282 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005283}
5284
5285/// Determine whether a defaulted special member function should be defined as
5286/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5287/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00005288bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5289 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00005290 if (MD->isInvalidDecl())
5291 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00005292 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00005293 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005294 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00005295 return false;
5296
Richard Smithd951a1d2012-02-18 02:02:13 +00005297 // C++11 [expr.lambda.prim]p19:
5298 // The closure type associated with a lambda-expression has a
5299 // deleted (8.4.3) default constructor and a deleted copy
5300 // assignment operator.
5301 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00005302 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5303 if (Diagnose)
5304 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00005305 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005306 }
5307
Richard Smith6f1e2c62012-04-02 20:59:25 +00005308 // For an anonymous struct or union, the copy and assignment special members
5309 // will never be used, so skip the check. For an anonymous union declared at
5310 // namespace scope, the constructor and destructor are used.
5311 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5312 RD->isAnonymousStructOrUnion())
5313 return false;
5314
Richard Smith852265f2012-03-30 20:53:28 +00005315 // C++11 [class.copy]p7, p18:
5316 // If the class definition declares a move constructor or move assignment
5317 // operator, an implicitly declared copy constructor or copy assignment
5318 // operator is defined as deleted.
5319 if (MD->isImplicit() &&
5320 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5321 CXXMethodDecl *UserDeclaredMove = 0;
5322
5323 // In Microsoft mode, a user-declared move only causes the deletion of the
5324 // corresponding copy operation, not both copy operations.
5325 if (RD->hasUserDeclaredMoveConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005326 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00005327 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005328
5329 // Find any user-declared move constructor.
5330 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
5331 E = RD->ctor_end(); I != E; ++I) {
5332 if (I->isMoveConstructor()) {
5333 UserDeclaredMove = *I;
5334 break;
5335 }
5336 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005337 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005338 } else if (RD->hasUserDeclaredMoveAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005339 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00005340 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005341
5342 // Find any user-declared move assignment operator.
5343 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
5344 E = RD->method_end(); I != E; ++I) {
5345 if (I->isMoveAssignmentOperator()) {
5346 UserDeclaredMove = *I;
5347 break;
5348 }
5349 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005350 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005351 }
5352
5353 if (UserDeclaredMove) {
5354 Diag(UserDeclaredMove->getLocation(),
5355 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00005356 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00005357 << UserDeclaredMove->isMoveAssignmentOperator();
5358 return true;
5359 }
5360 }
Alexis Huntd6da8762011-10-10 06:18:57 +00005361
Richard Smith6f1e2c62012-04-02 20:59:25 +00005362 // Do access control from the special member function
5363 ContextRAII MethodContext(*this, MD);
5364
Richard Smith921bd202012-02-26 09:11:52 +00005365 // C++11 [class.dtor]p5:
5366 // -- for a virtual destructor, lookup of the non-array deallocation function
5367 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00005368 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith921bd202012-02-26 09:11:52 +00005369 FunctionDecl *OperatorDelete = 0;
5370 DeclarationName Name =
5371 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5372 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00005373 OperatorDelete, false)) {
5374 if (Diagnose)
5375 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00005376 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005377 }
Richard Smith921bd202012-02-26 09:11:52 +00005378 }
5379
Richard Smith852265f2012-03-30 20:53:28 +00005380 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00005381
Alexis Huntea6f0322011-05-11 22:34:38 +00005382 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smithd951a1d2012-02-18 02:02:13 +00005383 BE = RD->bases_end(); BI != BE; ++BI)
5384 if (!BI->isVirtual() &&
Richard Smith852265f2012-03-30 20:53:28 +00005385 SMI.shouldDeleteForBase(BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005386 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005387
Richard Smithd1627032013-07-22 18:06:23 +00005388 // Per DR1611, do not consider virtual bases of constructors of abstract
5389 // classes, since we are not going to construct them.
Richard Smithbc46e432013-07-22 02:56:56 +00005390 if (!RD->isAbstract() || !SMI.IsConstructor) {
5391 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
5392 BE = RD->vbases_end();
5393 BI != BE; ++BI)
5394 if (SMI.shouldDeleteForBase(BI))
5395 return true;
5396 }
Alexis Huntea6f0322011-05-11 22:34:38 +00005397
5398 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smithd951a1d2012-02-18 02:02:13 +00005399 FE = RD->field_end(); FI != FE; ++FI)
5400 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie40ed2972012-06-06 20:45:41 +00005401 SMI.shouldDeleteForField(*FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00005402 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005403
Richard Smithd951a1d2012-02-18 02:02:13 +00005404 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00005405 return true;
5406
5407 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005408}
5409
Richard Smith92f241f2012-12-08 02:53:02 +00005410/// Perform lookup for a special member of the specified kind, and determine
5411/// whether it is trivial. If the triviality can be determined without the
5412/// lookup, skip it. This is intended for use when determining whether a
5413/// special member of a containing object is trivial, and thus does not ever
5414/// perform overload resolution for default constructors.
5415///
5416/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5417/// member that was most likely to be intended to be trivial, if any.
5418static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5419 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00005420 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00005421 if (Selected)
5422 *Selected = 0;
5423
5424 switch (CSM) {
5425 case Sema::CXXInvalid:
5426 llvm_unreachable("not a special member");
5427
5428 case Sema::CXXDefaultConstructor:
5429 // C++11 [class.ctor]p5:
5430 // A default constructor is trivial if:
5431 // - all the [direct subobjects] have trivial default constructors
5432 //
5433 // Note, no overload resolution is performed in this case.
5434 if (RD->hasTrivialDefaultConstructor())
5435 return true;
5436
5437 if (Selected) {
5438 // If there's a default constructor which could have been trivial, dig it
5439 // out. Otherwise, if there's any user-provided default constructor, point
5440 // to that as an example of why there's not a trivial one.
5441 CXXConstructorDecl *DefCtor = 0;
5442 if (RD->needsImplicitDefaultConstructor())
5443 S.DeclareImplicitDefaultConstructor(RD);
5444 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5445 CE = RD->ctor_end(); CI != CE; ++CI) {
5446 if (!CI->isDefaultConstructor())
5447 continue;
5448 DefCtor = *CI;
5449 if (!DefCtor->isUserProvided())
5450 break;
5451 }
5452
5453 *Selected = DefCtor;
5454 }
5455
5456 return false;
5457
5458 case Sema::CXXDestructor:
5459 // C++11 [class.dtor]p5:
5460 // A destructor is trivial if:
5461 // - all the direct [subobjects] have trivial destructors
5462 if (RD->hasTrivialDestructor())
5463 return true;
5464
5465 if (Selected) {
5466 if (RD->needsImplicitDestructor())
5467 S.DeclareImplicitDestructor(RD);
5468 *Selected = RD->getDestructor();
5469 }
5470
5471 return false;
5472
5473 case Sema::CXXCopyConstructor:
5474 // C++11 [class.copy]p12:
5475 // A copy constructor is trivial if:
5476 // - the constructor selected to copy each direct [subobject] is trivial
5477 if (RD->hasTrivialCopyConstructor()) {
5478 if (Quals == Qualifiers::Const)
5479 // We must either select the trivial copy constructor or reach an
5480 // ambiguity; no need to actually perform overload resolution.
5481 return true;
5482 } else if (!Selected) {
5483 return false;
5484 }
5485 // In C++98, we are not supposed to perform overload resolution here, but we
5486 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5487 // cases like B as having a non-trivial copy constructor:
5488 // struct A { template<typename T> A(T&); };
5489 // struct B { mutable A a; };
5490 goto NeedOverloadResolution;
5491
5492 case Sema::CXXCopyAssignment:
5493 // C++11 [class.copy]p25:
5494 // A copy assignment operator is trivial if:
5495 // - the assignment operator selected to copy each direct [subobject] is
5496 // trivial
5497 if (RD->hasTrivialCopyAssignment()) {
5498 if (Quals == Qualifiers::Const)
5499 return true;
5500 } else if (!Selected) {
5501 return false;
5502 }
5503 // In C++98, we are not supposed to perform overload resolution here, but we
5504 // treat that as a language defect.
5505 goto NeedOverloadResolution;
5506
5507 case Sema::CXXMoveConstructor:
5508 case Sema::CXXMoveAssignment:
5509 NeedOverloadResolution:
5510 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005511 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00005512
5513 // The standard doesn't describe how to behave if the lookup is ambiguous.
5514 // We treat it as not making the member non-trivial, just like the standard
5515 // mandates for the default constructor. This should rarely matter, because
5516 // the member will also be deleted.
5517 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5518 return true;
5519
5520 if (!SMOR->getMethod()) {
5521 assert(SMOR->getKind() ==
5522 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5523 return false;
5524 }
5525
5526 // We deliberately don't check if we found a deleted special member. We're
5527 // not supposed to!
5528 if (Selected)
5529 *Selected = SMOR->getMethod();
5530 return SMOR->getMethod()->isTrivial();
5531 }
5532
5533 llvm_unreachable("unknown special method kind");
5534}
5535
Benjamin Kramer3e350262013-02-15 12:30:38 +00005536static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smith92f241f2012-12-08 02:53:02 +00005537 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5538 CI != CE; ++CI)
5539 if (!CI->isImplicit())
5540 return *CI;
5541
5542 // Look for constructor templates.
5543 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5544 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5545 if (CXXConstructorDecl *CD =
5546 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5547 return CD;
5548 }
5549
5550 return 0;
5551}
5552
5553/// The kind of subobject we are checking for triviality. The values of this
5554/// enumeration are used in diagnostics.
5555enum TrivialSubobjectKind {
5556 /// The subobject is a base class.
5557 TSK_BaseClass,
5558 /// The subobject is a non-static data member.
5559 TSK_Field,
5560 /// The object is actually the complete object.
5561 TSK_CompleteObject
5562};
5563
5564/// Check whether the special member selected for a given type would be trivial.
5565static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00005566 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00005567 Sema::CXXSpecialMember CSM,
5568 TrivialSubobjectKind Kind,
5569 bool Diagnose) {
5570 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5571 if (!SubRD)
5572 return true;
5573
5574 CXXMethodDecl *Selected;
5575 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Richard Smith41c35d62013-11-27 03:39:20 +00005576 ConstRHS, Diagnose ? &Selected : 0))
Richard Smith92f241f2012-12-08 02:53:02 +00005577 return true;
5578
5579 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00005580 if (ConstRHS)
5581 SubType.addConst();
5582
Richard Smith92f241f2012-12-08 02:53:02 +00005583 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5584 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5585 << Kind << SubType.getUnqualifiedType();
5586 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5587 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5588 } else if (!Selected)
5589 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5590 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5591 else if (Selected->isUserProvided()) {
5592 if (Kind == TSK_CompleteObject)
5593 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5594 << Kind << SubType.getUnqualifiedType() << CSM;
5595 else {
5596 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5597 << Kind << SubType.getUnqualifiedType() << CSM;
5598 S.Diag(Selected->getLocation(), diag::note_declared_at);
5599 }
5600 } else {
5601 if (Kind != TSK_CompleteObject)
5602 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5603 << Kind << SubType.getUnqualifiedType() << CSM;
5604
5605 // Explain why the defaulted or deleted special member isn't trivial.
5606 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5607 }
5608 }
5609
5610 return false;
5611}
5612
5613/// Check whether the members of a class type allow a special member to be
5614/// trivial.
5615static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5616 Sema::CXXSpecialMember CSM,
5617 bool ConstArg, bool Diagnose) {
5618 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5619 FE = RD->field_end(); FI != FE; ++FI) {
5620 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5621 continue;
5622
5623 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5624
5625 // Pretend anonymous struct or union members are members of this class.
5626 if (FI->isAnonymousStructOrUnion()) {
5627 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5628 CSM, ConstArg, Diagnose))
5629 return false;
5630 continue;
5631 }
5632
5633 // C++11 [class.ctor]p5:
5634 // A default constructor is trivial if [...]
5635 // -- no non-static data member of its class has a
5636 // brace-or-equal-initializer
5637 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5638 if (Diagnose)
5639 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5640 return false;
5641 }
5642
5643 // Objective C ARC 4.3.5:
5644 // [...] nontrivally ownership-qualified types are [...] not trivially
5645 // default constructible, copy constructible, move constructible, copy
5646 // assignable, move assignable, or destructible [...]
5647 if (S.getLangOpts().ObjCAutoRefCount &&
5648 FieldType.hasNonTrivialObjCLifetime()) {
5649 if (Diagnose)
5650 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5651 << RD << FieldType.getObjCLifetime();
5652 return false;
5653 }
5654
Richard Smith41c35d62013-11-27 03:39:20 +00005655 bool ConstRHS = ConstArg && !FI->isMutable();
5656 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
5657 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005658 return false;
5659 }
5660
5661 return true;
5662}
5663
5664/// Diagnose why the specified class does not have a trivial special member of
5665/// the given kind.
5666void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5667 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00005668
Richard Smith41c35d62013-11-27 03:39:20 +00005669 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
5670 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00005671 TSK_CompleteObject, /*Diagnose*/true);
5672}
5673
5674/// Determine whether a defaulted or deleted special member function is trivial,
5675/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5676/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5677bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5678 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00005679 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5680
5681 CXXRecordDecl *RD = MD->getParent();
5682
5683 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00005684
Richard Smith2002bfe2013-11-04 02:02:27 +00005685 // C++11 [class.copy]p12, p25: [DR1593]
5686 // A [special member] is trivial if [...] its parameter-type-list is
5687 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00005688 switch (CSM) {
5689 case CXXDefaultConstructor:
5690 case CXXDestructor:
5691 // Trivial default constructors and destructors cannot have parameters.
5692 break;
5693
5694 case CXXCopyConstructor:
5695 case CXXCopyAssignment: {
5696 // Trivial copy operations always have const, non-volatile parameter types.
5697 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00005698 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005699 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5700 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5701 if (Diagnose)
5702 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5703 << Param0->getSourceRange() << Param0->getType()
5704 << Context.getLValueReferenceType(
5705 Context.getRecordType(RD).withConst());
5706 return false;
5707 }
5708 break;
5709 }
5710
5711 case CXXMoveConstructor:
5712 case CXXMoveAssignment: {
5713 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00005714 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005715 const RValueReferenceType *RT =
5716 Param0->getType()->getAs<RValueReferenceType>();
5717 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5718 if (Diagnose)
5719 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5720 << Param0->getSourceRange() << Param0->getType()
5721 << Context.getRValueReferenceType(Context.getRecordType(RD));
5722 return false;
5723 }
5724 break;
5725 }
5726
5727 case CXXInvalid:
5728 llvm_unreachable("not a special member");
5729 }
5730
Richard Smith92f241f2012-12-08 02:53:02 +00005731 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5732 if (Diagnose)
5733 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5734 diag::note_nontrivial_default_arg)
5735 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5736 return false;
5737 }
5738 if (MD->isVariadic()) {
5739 if (Diagnose)
5740 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5741 return false;
5742 }
5743
5744 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5745 // A copy/move [constructor or assignment operator] is trivial if
5746 // -- the [member] selected to copy/move each direct base class subobject
5747 // is trivial
5748 //
5749 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5750 // A [default constructor or destructor] is trivial if
5751 // -- all the direct base classes have trivial [default constructors or
5752 // destructors]
5753 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5754 BE = RD->bases_end(); BI != BE; ++BI)
Richard Smith41c35d62013-11-27 03:39:20 +00005755 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(), BI->getType(),
5756 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005757 return false;
5758
5759 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5760 // A copy/move [constructor or assignment operator] for a class X is
5761 // trivial if
5762 // -- for each non-static data member of X that is of class type (or array
5763 // thereof), the constructor selected to copy/move that member is
5764 // trivial
5765 //
5766 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5767 // A [default constructor or destructor] is trivial if
5768 // -- for all of the non-static data members of its class that are of class
5769 // type (or array thereof), each such class has a trivial [default
5770 // constructor or destructor]
5771 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5772 return false;
5773
5774 // C++11 [class.dtor]p5:
5775 // A destructor is trivial if [...]
5776 // -- the destructor is not virtual
5777 if (CSM == CXXDestructor && MD->isVirtual()) {
5778 if (Diagnose)
5779 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5780 return false;
5781 }
5782
5783 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5784 // A [special member] for class X is trivial if [...]
5785 // -- class X has no virtual functions and no virtual base classes
5786 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5787 if (!Diagnose)
5788 return false;
5789
5790 if (RD->getNumVBases()) {
5791 // Check for virtual bases. We already know that the corresponding
5792 // member in all bases is trivial, so vbases must all be direct.
5793 CXXBaseSpecifier &BS = *RD->vbases_begin();
5794 assert(BS.isVirtual());
5795 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5796 return false;
5797 }
5798
5799 // Must have a virtual method.
5800 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5801 ME = RD->method_end(); MI != ME; ++MI) {
5802 if (MI->isVirtual()) {
5803 SourceLocation MLoc = MI->getLocStart();
5804 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5805 return false;
5806 }
5807 }
5808
5809 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5810 }
5811
5812 // Looks like it's trivial!
5813 return true;
5814}
5815
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005816/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00005817namespace {
5818 struct FindHiddenVirtualMethodData {
5819 Sema *S;
5820 CXXMethodDecl *Method;
5821 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005822 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00005823 };
5824}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005825
David Blaikie282c92a2012-10-19 00:53:08 +00005826/// \brief Check whether any most overriden method from MD in Methods
5827static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5828 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5829 if (MD->size_overridden_methods() == 0)
5830 return Methods.count(MD->getCanonicalDecl());
5831 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5832 E = MD->end_overridden_methods();
5833 I != E; ++I)
5834 if (CheckMostOverridenMethods(*I, Methods))
5835 return true;
5836 return false;
5837}
5838
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005839/// \brief Member lookup function that determines whether a given C++
5840/// method overloads virtual methods in a base class without overriding any,
5841/// to be used with CXXRecordDecl::lookupInBases().
5842static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5843 CXXBasePath &Path,
5844 void *UserData) {
5845 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5846
5847 FindHiddenVirtualMethodData &Data
5848 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5849
5850 DeclarationName Name = Data.Method->getDeclName();
5851 assert(Name.getNameKind() == DeclarationName::Identifier);
5852
5853 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005854 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005855 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00005856 !Path.Decls.empty();
5857 Path.Decls = Path.Decls.slice(1)) {
5858 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005859 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00005860 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005861 foundSameNameMethod = true;
5862 // Interested only in hidden virtual methods.
5863 if (!MD->isVirtual())
5864 continue;
5865 // If the method we are checking overrides a method from its base
5866 // don't warn about the other overloaded methods.
5867 if (!Data.S->IsOverload(Data.Method, MD, false))
5868 return true;
5869 // Collect the overload only if its hidden.
David Blaikie282c92a2012-10-19 00:53:08 +00005870 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005871 overloadedMethods.push_back(MD);
5872 }
5873 }
5874
5875 if (foundSameNameMethod)
5876 Data.OverloadedMethods.append(overloadedMethods.begin(),
5877 overloadedMethods.end());
5878 return foundSameNameMethod;
5879}
5880
David Blaikie282c92a2012-10-19 00:53:08 +00005881/// \brief Add the most overriden methods from MD to Methods
5882static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5883 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5884 if (MD->size_overridden_methods() == 0)
5885 Methods.insert(MD->getCanonicalDecl());
5886 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5887 E = MD->end_overridden_methods();
5888 I != E; ++I)
5889 AddMostOverridenMethods(*I, Methods);
5890}
5891
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005892/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005893/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005894void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5895 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00005896 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005897 return;
5898
5899 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5900 /*bool RecordPaths=*/false,
5901 /*bool DetectVirtual=*/false);
5902 FindHiddenVirtualMethodData Data;
5903 Data.Method = MD;
5904 Data.S = this;
5905
5906 // Keep the base methods that were overriden or introduced in the subclass
5907 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005908 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00005909 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5910 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5911 NamedDecl *ND = *I;
5912 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00005913 ND = shad->getTargetDecl();
5914 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5915 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005916 }
5917
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005918 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5919 OverloadedMethods = Data.OverloadedMethods;
5920}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005921
Eli Friedmanaf65120b2013-09-05 23:51:03 +00005922void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
5923 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5924 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
5925 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
5926 PartialDiagnostic PD = PDiag(
5927 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5928 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5929 Diag(overloadedMD->getLocation(), PD);
5930 }
5931}
5932
5933/// \brief Diagnose methods which overload virtual methods in a base class
5934/// without overriding any.
5935void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
5936 if (MD->isInvalidDecl())
5937 return;
5938
5939 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5940 MD->getLocation()) == DiagnosticsEngine::Ignored)
5941 return;
5942
5943 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5944 FindHiddenVirtualMethods(MD, OverloadedMethods);
5945 if (!OverloadedMethods.empty()) {
5946 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5947 << MD << (OverloadedMethods.size() > 1);
5948
5949 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005950 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00005951}
5952
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005953void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00005954 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005955 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00005956 SourceLocation RBrac,
5957 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005958 if (!TagDecl)
5959 return;
Mike Stump11289f42009-09-09 15:08:12 +00005960
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005961 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00005962
Rafael Espindola06e1b132012-07-12 04:32:30 +00005963 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5964 if (l->getKind() != AttributeList::AT_Visibility)
5965 continue;
5966 l->setInvalid();
5967 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5968 l->getName();
5969 }
5970
David Blaikie751c5582011-09-22 02:58:26 +00005971 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00005972 // strict aliasing violation!
5973 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00005974 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00005975
Douglas Gregor0be31a22010-07-02 17:43:08 +00005976 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00005977 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005978}
5979
Douglas Gregor05379422008-11-03 17:51:48 +00005980/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5981/// special functions, such as the default constructor, copy
5982/// constructor, or destructor, to the given C++ class (C++
5983/// [special]p1). This routine can only be executed just before the
5984/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00005985void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005986 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00005987 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005988
Richard Smith6b02d462012-12-08 08:32:28 +00005989 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005990 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005991
Richard Smith6b02d462012-12-08 08:32:28 +00005992 // If the properties or semantics of the copy constructor couldn't be
5993 // determined while the class was being declared, force a declaration
5994 // of it now.
5995 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5996 DeclareImplicitCopyConstructor(ClassDecl);
5997 }
5998
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005999 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006000 ++ASTContext::NumImplicitMoveConstructors;
6001
Richard Smith6b02d462012-12-08 08:32:28 +00006002 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6003 DeclareImplicitMoveConstructor(ClassDecl);
6004 }
6005
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006006 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6007 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00006008
6009 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006010 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00006011 // it shows up in the right place in the vtable and that we diagnose
6012 // problems with the implicit exception specification.
6013 if (ClassDecl->isDynamicClass() ||
6014 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006015 DeclareImplicitCopyAssignment(ClassDecl);
6016 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006017
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006018 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006019 ++ASTContext::NumImplicitMoveAssignmentOperators;
6020
6021 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00006022 if (ClassDecl->isDynamicClass() ||
6023 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00006024 DeclareImplicitMoveAssignment(ClassDecl);
6025 }
6026
Douglas Gregor7454c562010-07-02 20:37:36 +00006027 if (!ClassDecl->hasUserDeclaredDestructor()) {
6028 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00006029
6030 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00006031 // have to declare the destructor immediately. This ensures that, e.g., it
6032 // shows up in the right place in the vtable and that we diagnose problems
6033 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00006034 if (ClassDecl->isDynamicClass() ||
6035 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00006036 DeclareImplicitDestructor(ClassDecl);
6037 }
Douglas Gregor05379422008-11-03 17:51:48 +00006038}
6039
Francois Pichet1c229c02011-04-22 22:18:13 +00006040void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
6041 if (!D)
6042 return;
6043
6044 int NumParamList = D->getNumTemplateParameterLists();
6045 for (int i = 0; i < NumParamList; i++) {
6046 TemplateParameterList* Params = D->getTemplateParameterList(i);
6047 for (TemplateParameterList::iterator Param = Params->begin(),
6048 ParamEnd = Params->end();
6049 Param != ParamEnd; ++Param) {
6050 NamedDecl *Named = cast<NamedDecl>(*Param);
6051 if (Named->getDeclName()) {
6052 S->AddDecl(Named);
6053 IdResolver.AddDecl(Named);
6054 }
6055 }
6056 }
6057}
6058
John McCall48871652010-08-21 09:40:31 +00006059void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00006060 if (!D)
6061 return;
6062
6063 TemplateParameterList *Params = 0;
6064 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
6065 Params = Template->getTemplateParameters();
6066 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
6067 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6068 Params = PartialSpec->getTemplateParameters();
6069 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006070 return;
6071
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006072 for (TemplateParameterList::iterator Param = Params->begin(),
6073 ParamEnd = Params->end();
6074 Param != ParamEnd; ++Param) {
6075 NamedDecl *Named = cast<NamedDecl>(*Param);
6076 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00006077 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006078 IdResolver.AddDecl(Named);
6079 }
6080 }
6081}
6082
John McCall48871652010-08-21 09:40:31 +00006083void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006084 if (!RecordD) return;
6085 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00006086 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00006087 PushDeclContext(S, Record);
6088}
6089
John McCall48871652010-08-21 09:40:31 +00006090void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006091 if (!RecordD) return;
6092 PopDeclContext();
6093}
6094
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006095/// This is used to implement the constant expression evaluation part of the
6096/// attribute enable_if extension. There is nothing in standard C++ which would
6097/// require reentering parameters.
6098void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6099 if (!Param)
6100 return;
6101
6102 S->AddDecl(Param);
6103 if (Param->getDeclName())
6104 IdResolver.AddDecl(Param);
6105}
6106
Douglas Gregor4d87df52008-12-16 21:30:33 +00006107/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6108/// parsing a top-level (non-nested) C++ class, and we are now
6109/// parsing those parts of the given Method declaration that could
6110/// not be parsed earlier (C++ [class.mem]p2), such as default
6111/// arguments. This action should enter the scope of the given
6112/// Method declaration as if we had just parsed the qualified method
6113/// name. However, it should not bring the parameters into scope;
6114/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00006115void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006116}
6117
6118/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6119/// C++ method declaration. We're (re-)introducing the given
6120/// function parameter into scope for use in parsing later parts of
6121/// the method declaration. For example, we could see an
6122/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00006123void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006124 if (!ParamD)
6125 return;
Mike Stump11289f42009-09-09 15:08:12 +00006126
John McCall48871652010-08-21 09:40:31 +00006127 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00006128
6129 // If this parameter has an unparsed default argument, clear it out
6130 // to make way for the parsed default argument.
6131 if (Param->hasUnparsedDefaultArg())
6132 Param->setDefaultArg(0);
6133
John McCall48871652010-08-21 09:40:31 +00006134 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006135 if (Param->getDeclName())
6136 IdResolver.AddDecl(Param);
6137}
6138
6139/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6140/// processing the delayed method declaration for Method. The method
6141/// declaration is now considered finished. There may be a separate
6142/// ActOnStartOfFunctionDef action later (not necessarily
6143/// immediately!) for this method, if it was also defined inside the
6144/// class body.
John McCall48871652010-08-21 09:40:31 +00006145void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006146 if (!MethodD)
6147 return;
Mike Stump11289f42009-09-09 15:08:12 +00006148
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006149 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00006150
John McCall48871652010-08-21 09:40:31 +00006151 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006152
6153 // Now that we have our default arguments, check the constructor
6154 // again. It could produce additional diagnostics or affect whether
6155 // the class has implicitly-declared destructors, among other
6156 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006157 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6158 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006159
6160 // Check the default arguments, which we may have added.
6161 if (!Method->isInvalidDecl())
6162 CheckCXXDefaultArguments(Method);
6163}
6164
Douglas Gregor831c93f2008-11-05 20:51:48 +00006165/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00006166/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00006167/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006168/// emit diagnostics and set the invalid bit to true. In any case, the type
6169/// will be updated to reflect a well-formed type for the constructor and
6170/// returned.
6171QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006172 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006173 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006174
6175 // C++ [class.ctor]p3:
6176 // A constructor shall not be virtual (10.3) or static (9.4). A
6177 // constructor can be invoked for a const, volatile or const
6178 // volatile object. A constructor shall not be declared const,
6179 // volatile, or const volatile (9.3.2).
6180 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006181 if (!D.isInvalidType())
6182 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6183 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6184 << SourceRange(D.getIdentifierLoc());
6185 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006186 }
John McCall8e7d6562010-08-26 03:08:43 +00006187 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006188 if (!D.isInvalidType())
6189 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6190 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6191 << SourceRange(D.getIdentifierLoc());
6192 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006193 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006194 }
Mike Stump11289f42009-09-09 15:08:12 +00006195
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006196 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006197 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00006198 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006199 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6200 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006201 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006202 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6203 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006204 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006205 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6206 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00006207 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006208 }
Mike Stump11289f42009-09-09 15:08:12 +00006209
Douglas Gregordb9d6642011-01-26 05:01:58 +00006210 // C++0x [class.ctor]p4:
6211 // A constructor shall not be declared with a ref-qualifier.
6212 if (FTI.hasRefQualifier()) {
6213 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6214 << FTI.RefQualifierIsLValueRef
6215 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6216 D.setInvalidType();
6217 }
6218
Douglas Gregor831c93f2008-11-05 20:51:48 +00006219 // Rebuild the function type "R" without any type qualifiers (in
6220 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00006221 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00006222 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006223 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
6224 return R;
6225
6226 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6227 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006228 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00006229
6230 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006231}
6232
Douglas Gregor4d87df52008-12-16 21:30:33 +00006233/// CheckConstructor - Checks a fully-formed constructor for
6234/// well-formedness, issuing any diagnostics required. Returns true if
6235/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006236void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00006237 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006238 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6239 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006240 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006241
6242 // C++ [class.copy]p3:
6243 // A declaration of a constructor for a class X is ill-formed if
6244 // its first parameter is of type (optionally cv-qualified) X and
6245 // either there are no other parameters or else all other
6246 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006247 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00006248 ((Constructor->getNumParams() == 1) ||
6249 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00006250 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6251 Constructor->getTemplateSpecializationKind()
6252 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006253 QualType ParamType = Constructor->getParamDecl(0)->getType();
6254 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6255 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00006256 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00006257 const char *ConstRef
6258 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6259 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00006260 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00006261 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00006262
6263 // FIXME: Rather that making the constructor invalid, we should endeavor
6264 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006265 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006266 }
6267 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00006268}
6269
John McCalldeb646e2010-08-04 01:04:25 +00006270/// CheckDestructor - Checks a fully-formed destructor definition for
6271/// well-formedness, issuing any diagnostics required. Returns true
6272/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00006273bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006274 CXXRecordDecl *RD = Destructor->getParent();
6275
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006276 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006277 SourceLocation Loc;
6278
6279 if (!Destructor->isImplicit())
6280 Loc = Destructor->getLocation();
6281 else
6282 Loc = RD->getLocation();
6283
6284 // If we have a virtual destructor, look up the deallocation function
6285 FunctionDecl *OperatorDelete = 0;
6286 DeclarationName Name =
6287 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006288 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00006289 return true;
Richard Smithf03bd302013-12-05 08:30:59 +00006290 // If there's no class-specific operator delete, look up the global
6291 // non-array delete.
6292 if (!OperatorDelete)
6293 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall1e5d75d2010-07-03 18:33:00 +00006294
Eli Friedmanfa0df832012-02-02 03:46:19 +00006295 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00006296
6297 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006298 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00006299
6300 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006301}
6302
Mike Stump11289f42009-09-09 15:08:12 +00006303static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00006304FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
6305 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6306 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00006307 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00006308}
6309
Douglas Gregor831c93f2008-11-05 20:51:48 +00006310/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6311/// the well-formednes of the destructor declarator @p D with type @p
6312/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006313/// emit diagnostics and set the declarator to invalid. Even if this happens,
6314/// will be updated to reflect a well-formed type for the destructor and
6315/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00006316QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006317 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006318 // C++ [class.dtor]p1:
6319 // [...] A typedef-name that names a class is a class-name
6320 // (7.1.3); however, a typedef-name that names a class shall not
6321 // be used as the identifier in the declarator for a destructor
6322 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00006323 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00006324 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00006325 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00006326 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00006327 else if (const TemplateSpecializationType *TST =
6328 DeclaratorType->getAs<TemplateSpecializationType>())
6329 if (TST->isTypeAlias())
6330 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6331 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006332
6333 // C++ [class.dtor]p2:
6334 // A destructor is used to destroy objects of its class type. A
6335 // destructor takes no parameters, and no return type can be
6336 // specified for it (not even void). The address of a destructor
6337 // shall not be taken. A destructor shall not be static. A
6338 // destructor can be invoked for a const, volatile or const
6339 // volatile object. A destructor shall not be declared const,
6340 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00006341 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006342 if (!D.isInvalidType())
6343 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6344 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00006345 << SourceRange(D.getIdentifierLoc())
6346 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6347
John McCall8e7d6562010-08-26 03:08:43 +00006348 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006349 }
Chris Lattner38378bf2009-04-25 08:28:21 +00006350 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006351 // Destructors don't have return types, but the parser will
6352 // happily parse something like:
6353 //
6354 // class X {
6355 // float ~X();
6356 // };
6357 //
6358 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00006359 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6360 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6361 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00006362 }
Mike Stump11289f42009-09-09 15:08:12 +00006363
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006364 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006365 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006366 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006367 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6368 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006369 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006370 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6371 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006372 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006373 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6374 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00006375 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006376 }
6377
Douglas Gregordb9d6642011-01-26 05:01:58 +00006378 // C++0x [class.dtor]p2:
6379 // A destructor shall not be declared with a ref-qualifier.
6380 if (FTI.hasRefQualifier()) {
6381 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6382 << FTI.RefQualifierIsLValueRef
6383 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6384 D.setInvalidType();
6385 }
6386
Douglas Gregor831c93f2008-11-05 20:51:48 +00006387 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00006388 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006389 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6390
6391 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00006392 FTI.freeArgs();
6393 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006394 }
6395
Mike Stump11289f42009-09-09 15:08:12 +00006396 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00006397 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006398 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00006399 D.setInvalidType();
6400 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006401
6402 // Rebuild the function type "R" without any type qualifiers or
6403 // parameters (in case any of the errors above fired) and with
6404 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00006405 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00006406 if (!D.isInvalidType())
6407 return R;
6408
Douglas Gregor95755162010-07-01 05:10:53 +00006409 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006410 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6411 EPI.Variadic = false;
6412 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006413 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006414 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006415}
6416
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006417/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6418/// well-formednes of the conversion function declarator @p D with
6419/// type @p R. If there are any errors in the declarator, this routine
6420/// will emit diagnostics and return true. Otherwise, it will return
6421/// false. Either way, the type @p R will be updated to reflect a
6422/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006423void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00006424 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006425 // C++ [class.conv.fct]p1:
6426 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00006427 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00006428 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00006429 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006430 if (!D.isInvalidType())
6431 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00006432 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6433 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006434 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006435 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006436 }
John McCall212fa2e2010-04-13 00:04:31 +00006437
6438 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6439
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006440 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006441 // Conversion functions don't have return types, but the parser will
6442 // happily parse something like:
6443 //
6444 // class X {
6445 // float operator bool();
6446 // };
6447 //
6448 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00006449 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6450 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6451 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00006452 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006453 }
6454
John McCall212fa2e2010-04-13 00:04:31 +00006455 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6456
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006457 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00006458 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006459 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6460
6461 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006462 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006463 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00006464 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006465 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006466 D.setInvalidType();
6467 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006468
John McCall212fa2e2010-04-13 00:04:31 +00006469 // Diagnose "&operator bool()" and other such nonsense. This
6470 // is actually a gcc extension which we don't support.
6471 if (Proto->getResultType() != ConvType) {
6472 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6473 << Proto->getResultType();
6474 D.setInvalidType();
6475 ConvType = Proto->getResultType();
6476 }
6477
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006478 // C++ [class.conv.fct]p4:
6479 // The conversion-type-id shall not represent a function type nor
6480 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006481 if (ConvType->isArrayType()) {
6482 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6483 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006484 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006485 } else if (ConvType->isFunctionType()) {
6486 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6487 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006488 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006489 }
6490
6491 // Rebuild the function type "R" without any parameters (in case any
6492 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00006493 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00006494 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006495 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006496
Douglas Gregor5fb53972009-01-14 15:45:31 +00006497 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006498 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00006499 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006500 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006501 diag::warn_cxx98_compat_explicit_conversion_functions :
6502 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00006503 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006504}
6505
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006506/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6507/// the declaration of the given C++ conversion function. This routine
6508/// is responsible for recording the conversion function in the C++
6509/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00006510Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006511 assert(Conversion && "Expected to receive a conversion function declaration");
6512
Douglas Gregor4287b372008-12-12 08:25:50 +00006513 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006514
6515 // Make sure we aren't redeclaring the conversion function.
6516 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006517
6518 // C++ [class.conv.fct]p1:
6519 // [...] A conversion function is never used to convert a
6520 // (possibly cv-qualified) object to the (possibly cv-qualified)
6521 // same object type (or a reference to it), to a (possibly
6522 // cv-qualified) base class of that type (or a reference to it),
6523 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00006524 // FIXME: Suppress this warning if the conversion function ends up being a
6525 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00006526 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006527 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006528 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006529 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006530 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6531 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00006532 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006533 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006534 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6535 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006536 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006537 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006538 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006539 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006540 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006541 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006542 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006543 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006544 }
6545
Douglas Gregor457104e2010-09-29 04:25:11 +00006546 if (FunctionTemplateDecl *ConversionTemplate
6547 = Conversion->getDescribedFunctionTemplate())
6548 return ConversionTemplate;
6549
John McCall48871652010-08-21 09:40:31 +00006550 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006551}
6552
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006553//===----------------------------------------------------------------------===//
6554// Namespace Handling
6555//===----------------------------------------------------------------------===//
6556
Richard Smith45bb8852012-10-04 22:13:39 +00006557/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6558/// reopened.
6559static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6560 SourceLocation Loc,
6561 IdentifierInfo *II, bool *IsInline,
6562 NamespaceDecl *PrevNS) {
6563 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00006564
Richard Smithf501cc32012-10-05 01:46:25 +00006565 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6566 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6567 // inline namespaces, with the intention of bringing names into namespace std.
6568 //
6569 // We support this just well enough to get that case working; this is not
6570 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00006571 if (*IsInline && II && II->getName().startswith("__atomic") &&
6572 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00006573 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00006574 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6575 NS = NS->getPreviousDecl())
6576 NS->setInline(*IsInline);
6577 // Patch up the lookup table for the containing namespace. This isn't really
6578 // correct, but it's good enough for this particular case.
6579 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6580 E = PrevNS->decls_end(); I != E; ++I)
6581 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6582 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6583 return;
6584 }
6585
6586 if (PrevNS->isInline())
6587 // The user probably just forgot the 'inline', so suggest that it
6588 // be added back.
6589 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6590 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6591 else
6592 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6593 << IsInline;
6594
6595 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6596 *IsInline = PrevNS->isInline();
6597}
John McCallb1be5232010-08-26 09:15:37 +00006598
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006599/// ActOnStartNamespaceDef - This is called at the start of a namespace
6600/// definition.
John McCall48871652010-08-21 09:40:31 +00006601Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00006602 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006603 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00006604 SourceLocation IdentLoc,
6605 IdentifierInfo *II,
6606 SourceLocation LBrace,
6607 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006608 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6609 // For anonymous namespace, take the location of the left brace.
6610 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00006611 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00006612 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00006613 bool IsStd = false;
6614 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006615 Scope *DeclRegionScope = NamespcScope->getParent();
6616
Douglas Gregore57e7522012-01-07 09:11:48 +00006617 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006618 if (II) {
6619 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00006620 // The identifier in an original-namespace-definition shall not
6621 // have been previously defined in the declarative region in
6622 // which the original-namespace-definition appears. The
6623 // identifier in an original-namespace-definition is the name of
6624 // the namespace. Subsequently in that declarative region, it is
6625 // treated as an original-namespace-name.
6626 //
6627 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006628 // look through using directives, just look for any ordinary names.
6629
6630 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00006631 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6632 Decl::IDNS_Namespace;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006633 NamedDecl *PrevDecl = 0;
David Blaikieff7d47a2012-12-19 00:45:41 +00006634 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6635 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6636 ++I) {
6637 if ((*I)->getIdentifierNamespace() & IDNS) {
6638 PrevDecl = *I;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006639 break;
6640 }
6641 }
6642
Douglas Gregore57e7522012-01-07 09:11:48 +00006643 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6644
6645 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00006646 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00006647 if (IsInline != PrevNS->isInline())
6648 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6649 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00006650 } else if (PrevDecl) {
6651 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006652 Diag(Loc, diag::err_redefinition_different_kind)
6653 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00006654 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006655 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00006656 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00006657 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00006658 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00006659 // This is the first "real" definition of the namespace "std", so update
6660 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006661 PrevNS = getStdNamespace();
6662 IsStd = true;
6663 AddToKnown = !IsInline;
6664 } else {
6665 // We've seen this namespace for the first time.
6666 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00006667 }
Douglas Gregor91f84212008-12-11 16:49:14 +00006668 } else {
John McCall4fa53422009-10-01 00:25:31 +00006669 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00006670
6671 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00006672 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00006673 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00006674 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006675 } else {
6676 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00006677 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006678 }
6679
Richard Smith45bb8852012-10-04 22:13:39 +00006680 if (PrevNS && IsInline != PrevNS->isInline())
6681 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6682 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00006683 }
6684
6685 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6686 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006687 if (IsInvalid)
6688 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00006689
6690 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00006691
Douglas Gregore57e7522012-01-07 09:11:48 +00006692 // FIXME: Should we be merging attributes?
6693 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006694 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00006695
6696 if (IsStd)
6697 StdNamespace = Namespc;
6698 if (AddToKnown)
6699 KnownNamespaces[Namespc] = false;
6700
6701 if (II) {
6702 PushOnScopeChains(Namespc, DeclRegionScope);
6703 } else {
6704 // Link the anonymous namespace into its parent.
6705 DeclContext *Parent = CurContext->getRedeclContext();
6706 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6707 TU->setAnonymousNamespace(Namespc);
6708 } else {
6709 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00006710 }
John McCall4fa53422009-10-01 00:25:31 +00006711
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00006712 CurContext->addDecl(Namespc);
6713
John McCall4fa53422009-10-01 00:25:31 +00006714 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6715 // behaves as if it were replaced by
6716 // namespace unique { /* empty body */ }
6717 // using namespace unique;
6718 // namespace unique { namespace-body }
6719 // where all occurrences of 'unique' in a translation unit are
6720 // replaced by the same identifier and this identifier differs
6721 // from all other identifiers in the entire program.
6722
6723 // We just create the namespace with an empty name and then add an
6724 // implicit using declaration, just like the standard suggests.
6725 //
6726 // CodeGen enforces the "universally unique" aspect by giving all
6727 // declarations semantically contained within an anonymous
6728 // namespace internal linkage.
6729
Douglas Gregore57e7522012-01-07 09:11:48 +00006730 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00006731 UsingDirectiveDecl* UD
Nick Lewycky38115822012-11-04 20:21:54 +00006732 = UsingDirectiveDecl::Create(Context, Parent,
John McCall0db42252009-12-16 02:06:49 +00006733 /* 'using' */ LBrace,
6734 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00006735 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00006736 /* identifier */ SourceLocation(),
6737 Namespc,
Nick Lewycky38115822012-11-04 20:21:54 +00006738 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00006739 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00006740 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00006741 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006742 }
6743
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00006744 ActOnDocumentableDecl(Namespc);
6745
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006746 // Although we could have an invalid decl (i.e. the namespace name is a
6747 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00006748 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6749 // for the namespace has the declarations that showed up in that particular
6750 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00006751 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00006752 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006753}
6754
Sebastian Redla6602e92009-11-23 15:34:23 +00006755/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6756/// is a namespace alias, returns the namespace it points to.
6757static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6758 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6759 return AD->getNamespace();
6760 return dyn_cast_or_null<NamespaceDecl>(D);
6761}
6762
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006763/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6764/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00006765void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006766 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6767 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006768 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006769 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00006770 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006771 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006772}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006773
John McCall28a0cf72010-08-25 07:42:41 +00006774CXXRecordDecl *Sema::getStdBadAlloc() const {
6775 return cast_or_null<CXXRecordDecl>(
6776 StdBadAlloc.get(Context.getExternalSource()));
6777}
6778
6779NamespaceDecl *Sema::getStdNamespace() const {
6780 return cast_or_null<NamespaceDecl>(
6781 StdNamespace.get(Context.getExternalSource()));
6782}
6783
Douglas Gregorcdf87022010-06-29 17:53:46 +00006784/// \brief Retrieve the special "std" namespace, which may require us to
6785/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006786NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00006787 if (!StdNamespace) {
6788 // The "std" namespace has not yet been defined, so build one implicitly.
6789 StdNamespace = NamespaceDecl::Create(Context,
6790 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006791 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006792 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006793 &PP.getIdentifierTable().get("std"),
6794 /*PrevDecl=*/0);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006795 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006796 }
6797
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006798 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006799}
6800
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006801bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006802 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006803 "Looking for std::initializer_list outside of C++.");
6804
6805 // We're looking for implicit instantiations of
6806 // template <typename E> class std::initializer_list.
6807
6808 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6809 return false;
6810
Sebastian Redl43144e72012-01-17 22:49:58 +00006811 ClassTemplateDecl *Template = 0;
6812 const TemplateArgument *Arguments = 0;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006813
Sebastian Redl43144e72012-01-17 22:49:58 +00006814 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006815
Sebastian Redl43144e72012-01-17 22:49:58 +00006816 ClassTemplateSpecializationDecl *Specialization =
6817 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6818 if (!Specialization)
6819 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006820
Sebastian Redl43144e72012-01-17 22:49:58 +00006821 Template = Specialization->getSpecializedTemplate();
6822 Arguments = Specialization->getTemplateArgs().data();
6823 } else if (const TemplateSpecializationType *TST =
6824 Ty->getAs<TemplateSpecializationType>()) {
6825 Template = dyn_cast_or_null<ClassTemplateDecl>(
6826 TST->getTemplateName().getAsTemplateDecl());
6827 Arguments = TST->getArgs();
6828 }
6829 if (!Template)
6830 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006831
6832 if (!StdInitializerList) {
6833 // Haven't recognized std::initializer_list yet, maybe this is it.
6834 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6835 if (TemplateClass->getIdentifier() !=
6836 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00006837 !getStdNamespace()->InEnclosingNamespaceSetOf(
6838 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006839 return false;
6840 // This is a template called std::initializer_list, but is it the right
6841 // template?
6842 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006843 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006844 return false;
6845 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6846 return false;
6847
6848 // It's the right template.
6849 StdInitializerList = Template;
6850 }
6851
6852 if (Template != StdInitializerList)
6853 return false;
6854
6855 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00006856 if (Element)
6857 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006858 return true;
6859}
6860
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006861static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6862 NamespaceDecl *Std = S.getStdNamespace();
6863 if (!Std) {
6864 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6865 return 0;
6866 }
6867
6868 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6869 Loc, Sema::LookupOrdinaryName);
6870 if (!S.LookupQualifiedName(Result, Std)) {
6871 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6872 return 0;
6873 }
6874 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6875 if (!Template) {
6876 Result.suppressDiagnostics();
6877 // We found something weird. Complain about the first thing we found.
6878 NamedDecl *Found = *Result.begin();
6879 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6880 return 0;
6881 }
6882
6883 // We found some template called std::initializer_list. Now verify that it's
6884 // correct.
6885 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006886 if (Params->getMinRequiredArguments() != 1 ||
6887 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006888 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6889 return 0;
6890 }
6891
6892 return Template;
6893}
6894
6895QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6896 if (!StdInitializerList) {
6897 StdInitializerList = LookupStdInitializerList(*this, Loc);
6898 if (!StdInitializerList)
6899 return QualType();
6900 }
6901
6902 TemplateArgumentListInfo Args(Loc, Loc);
6903 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6904 Context.getTrivialTypeSourceInfo(Element,
6905 Loc)));
6906 return Context.getCanonicalType(
6907 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6908}
6909
Sebastian Redlbe24ec22012-01-17 22:50:14 +00006910bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6911 // C++ [dcl.init.list]p2:
6912 // A constructor is an initializer-list constructor if its first parameter
6913 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6914 // std::initializer_list<E> for some type E, and either there are no other
6915 // parameters or else all other parameters have default arguments.
6916 if (Ctor->getNumParams() < 1 ||
6917 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6918 return false;
6919
6920 QualType ArgType = Ctor->getParamDecl(0)->getType();
6921 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6922 ArgType = RT->getPointeeType().getUnqualifiedType();
6923
6924 return isStdInitializerList(ArgType, 0);
6925}
6926
Douglas Gregora172e082011-03-26 22:25:30 +00006927/// \brief Determine whether a using statement is in a context where it will be
6928/// apply in all contexts.
6929static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6930 switch (CurContext->getDeclKind()) {
6931 case Decl::TranslationUnit:
6932 return true;
6933 case Decl::LinkageSpec:
6934 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6935 default:
6936 return false;
6937 }
6938}
6939
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006940namespace {
6941
6942// Callback to only accept typo corrections that are namespaces.
6943class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00006944public:
6945 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
6946 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006947 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006948 return false;
6949 }
6950};
6951
6952}
6953
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006954static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6955 CXXScopeSpec &SS,
6956 SourceLocation IdentLoc,
6957 IdentifierInfo *Ident) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006958 NamespaceValidatorCCC Validator;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006959 R.clear();
6960 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006961 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00006962 Validator)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006963 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00006964 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6965 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006966 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00006967 S.diagnoseTypo(Corrected,
6968 S.PDiag(diag::err_using_directive_member_suggest)
6969 << Ident << DC << DroppedSpecifier << SS.getRange(),
6970 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006971 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00006972 S.diagnoseTypo(Corrected,
6973 S.PDiag(diag::err_using_directive_suggest) << Ident,
6974 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00006975 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00006976 R.addDecl(Corrected.getCorrectionDecl());
6977 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006978 }
6979 return false;
6980}
6981
John McCall48871652010-08-21 09:40:31 +00006982Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00006983 SourceLocation UsingLoc,
6984 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00006985 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00006986 SourceLocation IdentLoc,
6987 IdentifierInfo *NamespcName,
6988 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00006989 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6990 assert(NamespcName && "Invalid NamespcName.");
6991 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00006992
6993 // This can only happen along a recovery path.
6994 while (S->getFlags() & Scope::TemplateParamScope)
6995 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00006996 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00006997
Douglas Gregor889ceb72009-02-03 19:21:40 +00006998 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00006999 NestedNameSpecifier *Qualifier = 0;
7000 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00007001 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007002
Douglas Gregor34074322009-01-14 22:20:51 +00007003 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00007004 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7005 LookupParsedName(R, S, &SS);
7006 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00007007 return 0;
John McCall27b18f82009-11-17 02:14:36 +00007008
Douglas Gregorcdf87022010-06-29 17:53:46 +00007009 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007010 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007011 // Allow "using namespace std;" or "using namespace ::std;" even if
7012 // "std" hasn't been defined yet, for GCC compatibility.
7013 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7014 NamespcName->isStr("std")) {
7015 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007016 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00007017 R.resolveKind();
7018 }
7019 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007020 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007021 }
7022
John McCall9f3059a2009-10-09 21:13:30 +00007023 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00007024 NamedDecl *Named = R.getFoundDecl();
7025 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7026 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00007027 // C++ [namespace.udir]p1:
7028 // A using-directive specifies that the names in the nominated
7029 // namespace can be used in the scope in which the
7030 // using-directive appears after the using-directive. During
7031 // unqualified name lookup (3.4.1), the names appear as if they
7032 // were declared in the nearest enclosing namespace which
7033 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00007034 // namespace. [Note: in this context, "contains" means "contains
7035 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00007036
7037 // Find enclosing context containing both using-directive and
7038 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00007039 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007040 DeclContext *CommonAncestor = cast<DeclContext>(NS);
7041 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7042 CommonAncestor = CommonAncestor->getParent();
7043
Sebastian Redla6602e92009-11-23 15:34:23 +00007044 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00007045 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00007046 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007047
Douglas Gregora172e082011-03-26 22:25:30 +00007048 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00007049 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007050 Diag(IdentLoc, diag::warn_using_directive_in_header);
7051 }
7052
Douglas Gregor889ceb72009-02-03 19:21:40 +00007053 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007054 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00007055 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00007056 }
7057
Richard Smith54ecd982013-02-20 19:22:51 +00007058 if (UDir)
7059 ProcessDeclAttributeList(S, UDir, AttrList);
7060
John McCall48871652010-08-21 09:40:31 +00007061 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00007062}
7063
7064void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00007065 // If the scope has an associated entity and the using directive is at
7066 // namespace or translation unit scope, add the UsingDirectiveDecl into
7067 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007068 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00007069 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007070 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007071 else
Richard Smith05afe5e2012-03-13 03:12:56 +00007072 // Otherwise, it is at block sope. The using-directives will affect lookup
7073 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00007074 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007075}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007076
Douglas Gregorfec52632009-06-20 00:51:54 +00007077
John McCall48871652010-08-21 09:40:31 +00007078Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00007079 AccessSpecifier AS,
7080 bool HasUsingKeyword,
7081 SourceLocation UsingLoc,
7082 CXXScopeSpec &SS,
7083 UnqualifiedId &Name,
7084 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007085 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00007086 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00007087 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00007088
Douglas Gregor220f4272009-11-04 16:30:06 +00007089 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00007090 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00007091 case UnqualifiedId::IK_Identifier:
7092 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00007093 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00007094 case UnqualifiedId::IK_ConversionFunctionId:
7095 break;
7096
7097 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00007098 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00007099 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007100 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007101 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00007102 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00007103 diag::err_using_decl_constructor)
7104 << SS.getRange();
7105
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007106 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00007107
John McCall48871652010-08-21 09:40:31 +00007108 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007109
7110 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007111 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00007112 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00007113 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007114
7115 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007116 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00007117 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00007118 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00007119 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007120
7121 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7122 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00007123 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00007124 return 0;
John McCall3969e302009-12-08 07:46:18 +00007125
Richard Smithc2bc61b2013-03-18 21:12:30 +00007126 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00007127 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00007128 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00007129 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7130 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00007131 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00007132 }
7133
Douglas Gregorc4356532010-12-16 00:46:58 +00007134 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7135 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7136 return 0;
7137
John McCall3f746822009-11-17 05:59:44 +00007138 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007139 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007140 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007141 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00007142 if (UD)
7143 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00007144
John McCall48871652010-08-21 09:40:31 +00007145 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00007146}
7147
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007148/// \brief Determine whether a using declaration considers the given
7149/// declarations as "equivalent", e.g., if they are redeclarations of
7150/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00007151static bool
7152IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7153 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007154 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007155
Richard Smithdda56e42011-04-15 14:24:37 +00007156 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00007157 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007158 return Context.hasSameType(TD1->getUnderlyingType(),
7159 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007160
7161 return false;
7162}
7163
7164
John McCall84d87672009-12-10 09:41:52 +00007165/// Determines whether to create a using shadow decl for a particular
7166/// decl, given the set of decls existing prior to this using lookup.
7167bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00007168 const LookupResult &Previous,
7169 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00007170 // Diagnose finding a decl which is not from a base class of the
7171 // current class. We do this now because there are cases where this
7172 // function will silently decide not to build a shadow decl, which
7173 // will pre-empt further diagnostics.
7174 //
7175 // We don't need to do this in C++0x because we do the check once on
7176 // the qualifier.
7177 //
7178 // FIXME: diagnose the following if we care enough:
7179 // struct A { int foo; };
7180 // struct B : A { using A::foo; };
7181 // template <class T> struct C : A {};
7182 // template <class T> struct D : C<T> { using B::foo; } // <---
7183 // This is invalid (during instantiation) in C++03 because B::foo
7184 // resolves to the using decl in B, which is not a base class of D<T>.
7185 // We can't diagnose it immediately because C<T> is an unknown
7186 // specialization. The UsingShadowDecl in D<T> then points directly
7187 // to A::foo, which will look well-formed when we instantiate.
7188 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007189 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00007190 DeclContext *OrigDC = Orig->getDeclContext();
7191
7192 // Handle enums and anonymous structs.
7193 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7194 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7195 while (OrigRec->isAnonymousStructOrUnion())
7196 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7197
7198 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7199 if (OrigDC == CurContext) {
7200 Diag(Using->getLocation(),
7201 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007202 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007203 Diag(Orig->getLocation(), diag::note_using_decl_target);
7204 return true;
7205 }
7206
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007207 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00007208 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007209 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00007210 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007211 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007212 Diag(Orig->getLocation(), diag::note_using_decl_target);
7213 return true;
7214 }
7215 }
7216
7217 if (Previous.empty()) return false;
7218
7219 NamedDecl *Target = Orig;
7220 if (isa<UsingShadowDecl>(Target))
7221 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7222
John McCalla17e83e2009-12-11 02:33:26 +00007223 // If the target happens to be one of the previous declarations, we
7224 // don't have a conflict.
7225 //
7226 // FIXME: but we might be increasing its access, in which case we
7227 // should redeclare it.
7228 NamedDecl *NonTag = 0, *Tag = 0;
Richard Smithfd8634a2013-10-23 02:17:46 +00007229 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00007230 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7231 I != E; ++I) {
7232 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007233 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7234 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7235 PrevShadow = Shadow;
7236 FoundEquivalentDecl = true;
7237 }
John McCalla17e83e2009-12-11 02:33:26 +00007238
7239 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7240 }
7241
Richard Smithfd8634a2013-10-23 02:17:46 +00007242 if (FoundEquivalentDecl)
7243 return false;
7244
Alp Tokera2794f92014-01-22 07:29:52 +00007245 if (FunctionDecl *FD = Target->getAsFunction()) {
John McCall84d87672009-12-10 09:41:52 +00007246 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00007247 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00007248 case Ovl_Overload:
7249 return false;
7250
7251 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00007252 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007253 break;
7254
7255 // We found a decl with the exact signature.
7256 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007257 // If we're in a record, we want to hide the target, so we
7258 // return true (without a diagnostic) to tell the caller not to
7259 // build a shadow decl.
7260 if (CurContext->isRecord())
7261 return true;
7262
7263 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00007264 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007265 break;
7266 }
7267
7268 Diag(Target->getLocation(), diag::note_using_decl_target);
7269 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7270 return true;
7271 }
7272
7273 // Target is not a function.
7274
John McCall84d87672009-12-10 09:41:52 +00007275 if (isa<TagDecl>(Target)) {
7276 // No conflict between a tag and a non-tag.
7277 if (!Tag) return false;
7278
John McCalle29c5cd2009-12-10 19:51:03 +00007279 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007280 Diag(Target->getLocation(), diag::note_using_decl_target);
7281 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7282 return true;
7283 }
7284
7285 // No conflict between a tag and a non-tag.
7286 if (!NonTag) return false;
7287
John McCalle29c5cd2009-12-10 19:51:03 +00007288 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007289 Diag(Target->getLocation(), diag::note_using_decl_target);
7290 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7291 return true;
7292}
7293
John McCall3f746822009-11-17 05:59:44 +00007294/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00007295UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00007296 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00007297 NamedDecl *Orig,
7298 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00007299
7300 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00007301 NamedDecl *Target = Orig;
7302 if (isa<UsingShadowDecl>(Target)) {
7303 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7304 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00007305 }
Richard Smithfd8634a2013-10-23 02:17:46 +00007306
John McCall3f746822009-11-17 05:59:44 +00007307 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00007308 = UsingShadowDecl::Create(Context, CurContext,
7309 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00007310 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00007311
Douglas Gregor457104e2010-09-29 04:25:11 +00007312 Shadow->setAccess(UD->getAccess());
7313 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7314 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007315
7316 Shadow->setPreviousDecl(PrevDecl);
7317
John McCall3f746822009-11-17 05:59:44 +00007318 if (S)
John McCall3969e302009-12-08 07:46:18 +00007319 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00007320 else
John McCall3969e302009-12-08 07:46:18 +00007321 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00007322
John McCall3969e302009-12-08 07:46:18 +00007323
John McCall84d87672009-12-10 09:41:52 +00007324 return Shadow;
7325}
John McCall3969e302009-12-08 07:46:18 +00007326
John McCall84d87672009-12-10 09:41:52 +00007327/// Hides a using shadow declaration. This is required by the current
7328/// using-decl implementation when a resolvable using declaration in a
7329/// class is followed by a declaration which would hide or override
7330/// one or more of the using decl's targets; for example:
7331///
7332/// struct Base { void foo(int); };
7333/// struct Derived : Base {
7334/// using Base::foo;
7335/// void foo(int);
7336/// };
7337///
7338/// The governing language is C++03 [namespace.udecl]p12:
7339///
7340/// When a using-declaration brings names from a base class into a
7341/// derived class scope, member functions in the derived class
7342/// override and/or hide member functions with the same name and
7343/// parameter types in a base class (rather than conflicting).
7344///
7345/// There are two ways to implement this:
7346/// (1) optimistically create shadow decls when they're not hidden
7347/// by existing declarations, or
7348/// (2) don't create any shadow decls (or at least don't make them
7349/// visible) until we've fully parsed/instantiated the class.
7350/// The problem with (1) is that we might have to retroactively remove
7351/// a shadow decl, which requires several O(n) operations because the
7352/// decl structures are (very reasonably) not designed for removal.
7353/// (2) avoids this but is very fiddly and phase-dependent.
7354void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00007355 if (Shadow->getDeclName().getNameKind() ==
7356 DeclarationName::CXXConversionFunctionName)
7357 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7358
John McCall84d87672009-12-10 09:41:52 +00007359 // Remove it from the DeclContext...
7360 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007361
John McCall84d87672009-12-10 09:41:52 +00007362 // ...and the scope, if applicable...
7363 if (S) {
John McCall48871652010-08-21 09:40:31 +00007364 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00007365 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007366 }
7367
John McCall84d87672009-12-10 09:41:52 +00007368 // ...and the using decl.
7369 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7370
7371 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00007372 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00007373}
7374
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007375namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007376class UsingValidatorCCC : public CorrectionCandidateCallback {
7377public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007378 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7379 bool RequireMember)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007380 : HasTypenameKeyword(HasTypenameKeyword),
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007381 IsInstantiation(IsInstantiation), RequireMember(RequireMember) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007382
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007383 bool ValidateCandidate(const TypoCorrection &Candidate) LLVM_OVERRIDE {
7384 NamedDecl *ND = Candidate.getCorrectionDecl();
7385
7386 // Keywords are not valid here.
7387 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007388 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007389
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007390 if (RequireMember && !isa<FieldDecl>(ND) && !isa<CXXMethodDecl>(ND) &&
7391 !isa<TypeDecl>(ND))
7392 return false;
7393
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007394 // Completely unqualified names are invalid for a 'using' declaration.
7395 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7396 return false;
7397
7398 if (isa<TypeDecl>(ND))
7399 return HasTypenameKeyword || !IsInstantiation;
7400
7401 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007402 }
7403
7404private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007405 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007406 bool IsInstantiation;
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007407 bool RequireMember;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007408};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007409} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007410
John McCalle61f2ba2009-11-18 02:36:19 +00007411/// Builds a using declaration.
7412///
7413/// \param IsInstantiation - Whether this call arises from an
7414/// instantiation of an unresolved using declaration. We treat
7415/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00007416NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7417 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007418 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007419 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00007420 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007421 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007422 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00007423 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00007424 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007425 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00007426 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00007427
Anders Carlssonf038fc22009-08-28 05:49:21 +00007428 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00007429
Anders Carlsson59140b32009-08-28 03:16:11 +00007430 if (SS.isEmpty()) {
7431 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00007432 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00007433 }
Mike Stump11289f42009-09-09 15:08:12 +00007434
John McCall84d87672009-12-10 09:41:52 +00007435 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007436 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00007437 ForRedeclaration);
7438 Previous.setHideTags(false);
7439 if (S) {
7440 LookupName(Previous, S);
7441
7442 // It is really dumb that we have to do this.
7443 LookupResult::Filter F = Previous.makeFilter();
7444 while (F.hasNext()) {
7445 NamedDecl *D = F.next();
7446 if (!isDeclInScope(D, CurContext, S))
7447 F.erase();
7448 }
7449 F.done();
7450 } else {
7451 assert(IsInstantiation && "no scope in non-instantiation");
7452 assert(CurContext->isRecord() && "scope not record in instantiation");
7453 LookupQualifiedName(Previous, CurContext);
7454 }
7455
John McCall84d87672009-12-10 09:41:52 +00007456 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007457 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7458 SS, IdentLoc, Previous))
John McCall84d87672009-12-10 09:41:52 +00007459 return 0;
7460
7461 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00007462 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7463 return 0;
7464
John McCall84c16cf2009-11-12 03:15:40 +00007465 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007466 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007467 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00007468 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007469 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00007470 // FIXME: not all declaration name kinds are legal here
7471 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7472 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007473 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007474 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00007475 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007476 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7477 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00007478 }
John McCallb96ec562009-12-04 22:46:56 +00007479 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007480 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007481 NameInfo, HasTypenameKeyword);
Anders Carlssonf038fc22009-08-28 05:49:21 +00007482 }
John McCallb96ec562009-12-04 22:46:56 +00007483 D->setAccess(AS);
7484 CurContext->addDecl(D);
7485
7486 if (!LookupContext) return D;
7487 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00007488
John McCall0b66eb32010-05-01 00:40:08 +00007489 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00007490 UD->setInvalidDecl();
7491 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00007492 }
7493
Richard Smith23d55872012-04-02 01:30:27 +00007494 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redl08905022011-02-05 19:23:19 +00007495 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smith23d55872012-04-02 01:30:27 +00007496 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlc1f8e492011-03-12 13:44:32 +00007497 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00007498 return UD;
7499 }
7500
7501 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00007502
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007503 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00007504
John McCall3969e302009-12-08 07:46:18 +00007505 // Unlike most lookups, we don't always want to hide tag
7506 // declarations: tag names are visible through the using declaration
7507 // even if hidden by ordinary names, *except* in a dependent context
7508 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00007509 if (!IsInstantiation)
7510 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00007511
John McCall5dadb652012-04-07 03:04:20 +00007512 // For the purposes of this lookup, we have a base object type
7513 // equal to that of the current context.
7514 if (CurContext->isRecord()) {
7515 R.setBaseObjectType(
7516 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7517 }
7518
John McCall27b18f82009-11-17 02:14:36 +00007519 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00007520
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007521 // Try to correct typos if possible.
John McCall9f3059a2009-10-09 21:13:30 +00007522 if (R.empty()) {
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007523 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation,
7524 CurContext->isRecord());
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007525 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7526 R.getLookupKind(), S, &SS, CCC)){
7527 // We reject any correction for which ND would be NULL.
7528 NamedDecl *ND = Corrected.getCorrectionDecl();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007529 R.setLookupName(Corrected.getCorrection());
7530 R.addDecl(ND);
Richard Smithf9b15102013-08-17 00:46:16 +00007531 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007532 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00007533 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7534 << NameInfo.getName() << LookupContext << 0
7535 << SS.getRange());
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007536 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007537 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007538 << NameInfo.getName() << LookupContext << SS.getRange();
7539 UD->setInvalidDecl();
7540 return UD;
7541 }
Douglas Gregorfec52632009-06-20 00:51:54 +00007542 }
7543
John McCallb96ec562009-12-04 22:46:56 +00007544 if (R.isAmbiguous()) {
7545 UD->setInvalidDecl();
7546 return UD;
7547 }
Mike Stump11289f42009-09-09 15:08:12 +00007548
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007549 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00007550 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00007551 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007552 Diag(IdentLoc, diag::err_using_typename_non_type);
7553 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7554 Diag((*I)->getUnderlyingDecl()->getLocation(),
7555 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00007556 UD->setInvalidDecl();
7557 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00007558 }
7559 } else {
7560 // If we asked for a non-typename and we got a type, error out,
7561 // but only if this is an instantiation of an unresolved using
7562 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00007563 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007564 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7565 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00007566 UD->setInvalidDecl();
7567 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00007568 }
Anders Carlsson59140b32009-08-28 03:16:11 +00007569 }
7570
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007571 // C++0x N2914 [namespace.udecl]p6:
7572 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00007573 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007574 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7575 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00007576 UD->setInvalidDecl();
7577 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007578 }
Mike Stump11289f42009-09-09 15:08:12 +00007579
John McCall84d87672009-12-10 09:41:52 +00007580 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithfd8634a2013-10-23 02:17:46 +00007581 UsingShadowDecl *PrevDecl = 0;
7582 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7583 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00007584 }
John McCall3f746822009-11-17 05:59:44 +00007585
7586 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00007587}
7588
Sebastian Redl08905022011-02-05 19:23:19 +00007589/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00007590bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007591 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00007592
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007593 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00007594 assert(SourceType &&
7595 "Using decl naming constructor doesn't have type in scope spec.");
7596 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7597
7598 // Check whether the named type is a direct base class.
7599 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7600 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7601 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7602 BaseIt != BaseE; ++BaseIt) {
7603 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7604 if (CanonicalSourceType == BaseType)
7605 break;
Richard Smith23d55872012-04-02 01:30:27 +00007606 if (BaseIt->getType()->isDependentType())
7607 break;
Sebastian Redl08905022011-02-05 19:23:19 +00007608 }
7609
7610 if (BaseIt == BaseE) {
7611 // Did not find SourceType in the bases.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007612 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00007613 diag::err_using_decl_constructor_not_in_direct_base)
7614 << UD->getNameInfo().getSourceRange()
7615 << QualType(SourceType, 0) << TargetClass;
7616 return true;
7617 }
7618
Richard Smith23d55872012-04-02 01:30:27 +00007619 if (!CurContext->isDependentContext())
7620 BaseIt->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00007621
7622 return false;
7623}
7624
John McCall84d87672009-12-10 09:41:52 +00007625/// Checks that the given using declaration is not an invalid
7626/// redeclaration. Note that this is checking only for the using decl
7627/// itself, not for any ill-formedness among the UsingShadowDecls.
7628bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007629 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00007630 const CXXScopeSpec &SS,
7631 SourceLocation NameLoc,
7632 const LookupResult &Prev) {
7633 // C++03 [namespace.udecl]p8:
7634 // C++0x [namespace.udecl]p10:
7635 // A using-declaration is a declaration and can therefore be used
7636 // repeatedly where (and only where) multiple declarations are
7637 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00007638 //
John McCall032092f2010-11-29 18:01:58 +00007639 // That's in non-member contexts.
7640 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00007641 return false;
7642
Aaron Ballman4a979672014-01-03 13:56:08 +00007643 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall84d87672009-12-10 09:41:52 +00007644
7645 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7646 NamedDecl *D = *I;
7647
7648 bool DTypename;
7649 NestedNameSpecifier *DQual;
7650 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007651 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007652 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007653 } else if (UnresolvedUsingValueDecl *UD
7654 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7655 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007656 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007657 } else if (UnresolvedUsingTypenameDecl *UD
7658 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7659 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007660 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007661 } else continue;
7662
7663 // using decls differ if one says 'typename' and the other doesn't.
7664 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007665 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00007666
7667 // using decls differ if they name different scopes (but note that
7668 // template instantiation can cause this check to trigger when it
7669 // didn't before instantiation).
7670 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7671 Context.getCanonicalNestedNameSpecifier(DQual))
7672 continue;
7673
7674 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00007675 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00007676 return true;
7677 }
7678
7679 return false;
7680}
7681
John McCall3969e302009-12-08 07:46:18 +00007682
John McCallb96ec562009-12-04 22:46:56 +00007683/// Checks that the given nested-name qualifier used in a using decl
7684/// in the current context is appropriately related to the current
7685/// scope. If an error is found, diagnoses it and returns true.
7686bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7687 const CXXScopeSpec &SS,
7688 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00007689 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007690
John McCall3969e302009-12-08 07:46:18 +00007691 if (!CurContext->isRecord()) {
7692 // C++03 [namespace.udecl]p3:
7693 // C++0x [namespace.udecl]p8:
7694 // A using-declaration for a class member shall be a member-declaration.
7695
7696 // If we weren't able to compute a valid scope, it must be a
7697 // dependent class scope.
7698 if (!NamedContext || NamedContext->isRecord()) {
7699 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7700 << SS.getRange();
7701 return true;
7702 }
7703
7704 // Otherwise, everything is known to be fine.
7705 return false;
7706 }
7707
7708 // The current scope is a record.
7709
7710 // If the named context is dependent, we can't decide much.
7711 if (!NamedContext) {
7712 // FIXME: in C++0x, we can diagnose if we can prove that the
7713 // nested-name-specifier does not refer to a base class, which is
7714 // still possible in some cases.
7715
7716 // Otherwise we have to conservatively report that things might be
7717 // okay.
7718 return false;
7719 }
7720
7721 if (!NamedContext->isRecord()) {
7722 // Ideally this would point at the last name in the specifier,
7723 // but we don't have that level of source info.
7724 Diag(SS.getRange().getBegin(),
7725 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00007726 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00007727 return true;
7728 }
7729
Douglas Gregor7c842292010-12-21 07:41:49 +00007730 if (!NamedContext->isDependentContext() &&
7731 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7732 return true;
7733
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007734 if (getLangOpts().CPlusPlus11) {
John McCall3969e302009-12-08 07:46:18 +00007735 // C++0x [namespace.udecl]p3:
7736 // In a using-declaration used as a member-declaration, the
7737 // nested-name-specifier shall name a base class of the class
7738 // being defined.
7739
7740 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7741 cast<CXXRecordDecl>(NamedContext))) {
7742 if (CurContext == NamedContext) {
7743 Diag(NameLoc,
7744 diag::err_using_decl_nested_name_specifier_is_current_class)
7745 << SS.getRange();
7746 return true;
7747 }
7748
7749 Diag(SS.getRange().getBegin(),
7750 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00007751 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00007752 << cast<CXXRecordDecl>(CurContext)
7753 << SS.getRange();
7754 return true;
7755 }
7756
7757 return false;
7758 }
7759
7760 // C++03 [namespace.udecl]p4:
7761 // A using-declaration used as a member-declaration shall refer
7762 // to a member of a base class of the class being defined [etc.].
7763
7764 // Salient point: SS doesn't have to name a base class as long as
7765 // lookup only finds members from base classes. Therefore we can
7766 // diagnose here only if we can prove that that can't happen,
7767 // i.e. if the class hierarchies provably don't intersect.
7768
7769 // TODO: it would be nice if "definitely valid" results were cached
7770 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7771 // need to be repeated.
7772
7773 struct UserData {
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00007774 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall3969e302009-12-08 07:46:18 +00007775
7776 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7777 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7778 Data->Bases.insert(Base);
7779 return true;
7780 }
7781
7782 bool hasDependentBases(const CXXRecordDecl *Class) {
7783 return !Class->forallBases(collect, this);
7784 }
7785
7786 /// Returns true if the base is dependent or is one of the
7787 /// accumulated base classes.
7788 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7789 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7790 return !Data->Bases.count(Base);
7791 }
7792
7793 bool mightShareBases(const CXXRecordDecl *Class) {
7794 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7795 }
7796 };
7797
7798 UserData Data;
7799
7800 // Returns false if we find a dependent base.
7801 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7802 return false;
7803
7804 // Returns false if the class has a dependent base or if it or one
7805 // of its bases is present in the base set of the current context.
7806 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7807 return false;
7808
7809 Diag(SS.getRange().getBegin(),
7810 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00007811 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00007812 << cast<CXXRecordDecl>(CurContext)
7813 << SS.getRange();
7814
7815 return true;
John McCallb96ec562009-12-04 22:46:56 +00007816}
7817
Richard Smithdda56e42011-04-15 14:24:37 +00007818Decl *Sema::ActOnAliasDeclaration(Scope *S,
7819 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00007820 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00007821 SourceLocation UsingLoc,
7822 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00007823 AttributeList *AttrList,
Richard Smithdda56e42011-04-15 14:24:37 +00007824 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00007825 // Skip up to the relevant declaration scope.
7826 while (S->getFlags() & Scope::TemplateParamScope)
7827 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00007828 assert((S->getFlags() & Scope::DeclScope) &&
7829 "got alias-declaration outside of declaration scope");
7830
7831 if (Type.isInvalid())
7832 return 0;
7833
7834 bool Invalid = false;
7835 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7836 TypeSourceInfo *TInfo = 0;
Nick Lewycky82e47802011-05-02 01:07:19 +00007837 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00007838
7839 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7840 return 0;
7841
7842 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00007843 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00007844 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00007845 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7846 TInfo->getTypeLoc().getBeginLoc());
7847 }
Richard Smithdda56e42011-04-15 14:24:37 +00007848
7849 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7850 LookupName(Previous, S);
7851
7852 // Warn about shadowing the name of a template parameter.
7853 if (Previous.isSingleResult() &&
7854 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00007855 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00007856 Previous.clear();
7857 }
7858
7859 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7860 "name in alias declaration must be an identifier");
7861 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7862 Name.StartLocation,
7863 Name.Identifier, TInfo);
7864
7865 NewTD->setAccess(AS);
7866
7867 if (Invalid)
7868 NewTD->setInvalidDecl();
7869
Richard Smith54ecd982013-02-20 19:22:51 +00007870 ProcessDeclAttributeList(S, NewTD, AttrList);
7871
Richard Smith3f1b5d02011-05-05 21:57:07 +00007872 CheckTypedefForVariablyModifiedType(S, NewTD);
7873 Invalid |= NewTD->isInvalidDecl();
7874
Richard Smithdda56e42011-04-15 14:24:37 +00007875 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00007876
7877 NamedDecl *NewND;
7878 if (TemplateParamLists.size()) {
7879 TypeAliasTemplateDecl *OldDecl = 0;
7880 TemplateParameterList *OldTemplateParams = 0;
7881
7882 if (TemplateParamLists.size() != 1) {
7883 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007884 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7885 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00007886 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00007887 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00007888
7889 // Only consider previous declarations in the same scope.
7890 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7891 /*ExplicitInstantiationOrSpecialization*/false);
7892 if (!Previous.empty()) {
7893 Redeclaration = true;
7894
7895 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7896 if (!OldDecl && !Invalid) {
7897 Diag(UsingLoc, diag::err_redefinition_different_kind)
7898 << Name.Identifier;
7899
7900 NamedDecl *OldD = Previous.getRepresentativeDecl();
7901 if (OldD->getLocation().isValid())
7902 Diag(OldD->getLocation(), diag::note_previous_definition);
7903
7904 Invalid = true;
7905 }
7906
7907 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7908 if (TemplateParameterListsAreEqual(TemplateParams,
7909 OldDecl->getTemplateParameters(),
7910 /*Complain=*/true,
7911 TPL_TemplateMatch))
7912 OldTemplateParams = OldDecl->getTemplateParameters();
7913 else
7914 Invalid = true;
7915
7916 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7917 if (!Invalid &&
7918 !Context.hasSameType(OldTD->getUnderlyingType(),
7919 NewTD->getUnderlyingType())) {
7920 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7921 // but we can't reasonably accept it.
7922 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7923 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7924 if (OldTD->getLocation().isValid())
7925 Diag(OldTD->getLocation(), diag::note_previous_definition);
7926 Invalid = true;
7927 }
7928 }
7929 }
7930
7931 // Merge any previous default template arguments into our parameters,
7932 // and check the parameter list.
7933 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7934 TPC_TypeAliasTemplate))
7935 return 0;
7936
7937 TypeAliasTemplateDecl *NewDecl =
7938 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7939 Name.Identifier, TemplateParams,
7940 NewTD);
7941
7942 NewDecl->setAccess(AS);
7943
7944 if (Invalid)
7945 NewDecl->setInvalidDecl();
7946 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00007947 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00007948
7949 NewND = NewDecl;
7950 } else {
7951 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7952 NewND = NewTD;
7953 }
Richard Smithdda56e42011-04-15 14:24:37 +00007954
7955 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00007956 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00007957
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00007958 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00007959 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00007960}
7961
John McCall48871652010-08-21 09:40:31 +00007962Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00007963 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00007964 SourceLocation AliasLoc,
7965 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007966 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00007967 SourceLocation IdentLoc,
7968 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00007969
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007970 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00007971 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7972 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007973
Anders Carlssondca83c42009-03-28 06:23:46 +00007974 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00007975 NamedDecl *PrevDecl
7976 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7977 ForRedeclaration);
7978 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7979 PrevDecl = 0;
7980
7981 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007982 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00007983 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007984 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00007985 // FIXME: At some point, we'll want to create the (redundant)
7986 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00007987 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00007988 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00007989 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00007990 }
Mike Stump11289f42009-09-09 15:08:12 +00007991
Anders Carlssondca83c42009-03-28 06:23:46 +00007992 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7993 diag::err_redefinition_different_kind;
7994 Diag(AliasLoc, DiagID) << Alias;
7995 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00007996 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00007997 }
7998
John McCall27b18f82009-11-17 02:14:36 +00007999 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00008000 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00008001
John McCall9f3059a2009-10-09 21:13:30 +00008002 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008003 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00008004 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00008005 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00008006 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00008007 }
Mike Stump11289f42009-09-09 15:08:12 +00008008
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008009 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00008010 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00008011 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00008012 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00008013
John McCalld8d0d432010-02-16 06:53:13 +00008014 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00008015 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00008016}
8017
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008018Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008019Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8020 CXXMethodDecl *MD) {
8021 CXXRecordDecl *ClassDecl = MD->getParent();
8022
Douglas Gregor6d880b12010-07-01 22:31:05 +00008023 // C++ [except.spec]p14:
8024 // An implicitly declared special member function (Clause 12) shall have an
8025 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00008026 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008027 if (ClassDecl->isInvalidDecl())
8028 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00008029
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008030 // Direct base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00008031 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8032 BEnd = ClassDecl->bases_end();
8033 B != BEnd; ++B) {
8034 if (B->isVirtual()) // Handled below.
8035 continue;
8036
Douglas Gregor9672f922010-07-03 00:47:00 +00008037 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8038 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008039 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8040 // If this is a deleted function, add it anyway. This might be conformant
8041 // with the standard. This might not. I'm not sure. It might not matter.
8042 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008043 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008044 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008045 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008046
8047 // Virtual base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00008048 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8049 BEnd = ClassDecl->vbases_end();
8050 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008051 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8052 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008053 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8054 // If this is a deleted function, add it anyway. This might be conformant
8055 // with the standard. This might not. I'm not sure. It might not matter.
8056 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008057 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008058 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008059 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008060
8061 // Field constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00008062 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8063 FEnd = ClassDecl->field_end();
8064 F != FEnd; ++F) {
Richard Smith938f40b2011-06-11 17:19:42 +00008065 if (F->hasInClassInitializer()) {
8066 if (Expr *E = F->getInClassInitializer())
8067 ExceptSpec.CalledExpr(E);
8068 else if (!F->isInvalidDecl())
Richard Smithd3b5c9082012-07-27 04:22:15 +00008069 // DR1351:
8070 // If the brace-or-equal-initializer of a non-static data member
8071 // invokes a defaulted default constructor of its class or of an
8072 // enclosing class in a potentially evaluated subexpression, the
8073 // program is ill-formed.
8074 //
8075 // This resolution is unworkable: the exception specification of the
8076 // default constructor can be needed in an unevaluated context, in
8077 // particular, in the operand of a noexcept-expression, and we can be
8078 // unable to compute an exception specification for an enclosed class.
8079 //
8080 // We do not allow an in-class initializer to require the evaluation
8081 // of the exception specification for any in-class initializer whose
8082 // definition is not lexically complete.
8083 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith938f40b2011-06-11 17:19:42 +00008084 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00008085 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00008086 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8087 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8088 // If this is a deleted function, add it anyway. This might be conformant
8089 // with the standard. This might not. I'm not sure. It might not matter.
8090 // In particular, the problem is that this function never gets called. It
8091 // might just be ill-formed because this function attempts to refer to
8092 // a deleted function here.
8093 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008094 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008095 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008096 }
John McCalldb40c7f2010-12-14 08:05:40 +00008097
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008098 return ExceptSpec;
8099}
8100
Richard Smithc2bc61b2013-03-18 21:12:30 +00008101Sema::ImplicitExceptionSpecification
Richard Smithb7151b92013-04-10 06:11:48 +00008102Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8103 CXXRecordDecl *ClassDecl = CD->getParent();
8104
8105 // C++ [except.spec]p14:
8106 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00008107 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00008108 if (ClassDecl->isInvalidDecl())
8109 return ExceptSpec;
8110
8111 // Inherited constructor.
8112 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8113 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8114 // FIXME: Copying or moving the parameters could add extra exceptions to the
8115 // set, as could the default arguments for the inherited constructor. This
8116 // will be addressed when we implement the resolution of core issue 1351.
8117 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8118
8119 // Direct base-class constructors.
8120 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8121 BEnd = ClassDecl->bases_end();
8122 B != BEnd; ++B) {
8123 if (B->isVirtual()) // Handled below.
8124 continue;
8125
8126 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8127 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8128 if (BaseClassDecl == InheritedDecl)
8129 continue;
8130 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8131 if (Constructor)
8132 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8133 }
8134 }
8135
8136 // Virtual base-class constructors.
8137 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8138 BEnd = ClassDecl->vbases_end();
8139 B != BEnd; ++B) {
8140 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8141 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8142 if (BaseClassDecl == InheritedDecl)
8143 continue;
8144 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8145 if (Constructor)
8146 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8147 }
8148 }
8149
8150 // Field constructors.
8151 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8152 FEnd = ClassDecl->field_end();
8153 F != FEnd; ++F) {
8154 if (F->hasInClassInitializer()) {
8155 if (Expr *E = F->getInClassInitializer())
8156 ExceptSpec.CalledExpr(E);
8157 else if (!F->isInvalidDecl())
8158 Diag(CD->getLocation(),
8159 diag::err_in_class_initializer_references_def_ctor) << CD;
8160 } else if (const RecordType *RecordTy
8161 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8162 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8163 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8164 if (Constructor)
8165 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8166 }
8167 }
8168
Richard Smithc2bc61b2013-03-18 21:12:30 +00008169 return ExceptSpec;
8170}
8171
Richard Smith8bf22e52012-11-29 01:34:07 +00008172namespace {
8173/// RAII object to register a special member as being currently declared.
8174struct DeclaringSpecialMember {
8175 Sema &S;
8176 Sema::SpecialMemberDecl D;
8177 bool WasAlreadyBeingDeclared;
8178
8179 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8180 : S(S), D(RD, CSM) {
8181 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8182 if (WasAlreadyBeingDeclared)
8183 // This almost never happens, but if it does, ensure that our cache
8184 // doesn't contain a stale result.
8185 S.SpecialMemberCache.clear();
8186
8187 // FIXME: Register a note to be produced if we encounter an error while
8188 // declaring the special member.
8189 }
8190 ~DeclaringSpecialMember() {
8191 if (!WasAlreadyBeingDeclared)
8192 S.SpecialMembersBeingDeclared.erase(D);
8193 }
8194
8195 /// \brief Are we already trying to declare this special member?
8196 bool isAlreadyBeingDeclared() const {
8197 return WasAlreadyBeingDeclared;
8198 }
8199};
8200}
8201
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008202CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8203 CXXRecordDecl *ClassDecl) {
8204 // C++ [class.ctor]p5:
8205 // A default constructor for a class X is a constructor of class X
8206 // that can be called without an argument. If there is no
8207 // user-declared constructor for class X, a default constructor is
8208 // implicitly declared. An implicitly-declared default constructor
8209 // is an inline public member of its class.
Richard Smith7d125a12012-11-27 21:20:31 +00008210 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008211 "Should not build implicit default constructor!");
8212
Richard Smith8bf22e52012-11-29 01:34:07 +00008213 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8214 if (DSM.isAlreadyBeingDeclared())
8215 return 0;
8216
Richard Smithb5800092012-06-10 05:43:50 +00008217 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8218 CXXDefaultConstructor,
8219 false);
8220
Douglas Gregor6d880b12010-07-01 22:31:05 +00008221 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008222 CanQualType ClassType
8223 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008224 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008225 DeclarationName Name
8226 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008227 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00008228 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +00008229 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +00008230 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +00008231 Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008232 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00008233 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008234 DefaultCon->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008235
8236 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008237 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008238 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008239
Richard Smith6b02d462012-12-08 08:32:28 +00008240 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8241 // constructors is easy to compute.
8242 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8243
8244 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008245 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008246
Douglas Gregor9672f922010-07-03 00:47:00 +00008247 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00008248 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00008249
Douglas Gregor0be31a22010-07-02 17:43:08 +00008250 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00008251 PushOnScopeChains(DefaultCon, S, false);
8252 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008253
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008254 return DefaultCon;
8255}
8256
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008257void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8258 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008259 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008260 !Constructor->doesThisDeclarationHaveABody() &&
8261 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008262 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008263
Anders Carlsson423f5d82010-04-23 16:04:08 +00008264 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00008265 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00008266
Eli Friedmaneaf34142012-10-18 20:14:08 +00008267 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008268 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00008269 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008270 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008271 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008272 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00008273 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00008274 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00008275 }
Douglas Gregor73193272010-09-20 16:48:21 +00008276
8277 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008278 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +00008279
Eli Friedman276dd182013-09-05 00:02:25 +00008280 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +00008281 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008282
8283 if (ASTMutationListener *L = getASTMutationListener()) {
8284 L->CompletedImplicitDefinition(Constructor);
8285 }
Richard Trieuef64e942013-10-25 00:56:00 +00008286
8287 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008288}
8289
Richard Smith938f40b2011-06-11 17:19:42 +00008290void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008291 // Perform any delayed checks on exception specifications.
8292 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +00008293}
8294
Richard Smith185be182013-04-10 05:48:59 +00008295namespace {
8296/// Information on inheriting constructors to declare.
8297class InheritingConstructorInfo {
8298public:
8299 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8300 : SemaRef(SemaRef), Derived(Derived) {
8301 // Mark the constructors that we already have in the derived class.
8302 //
8303 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8304 // unless there is a user-declared constructor with the same signature in
8305 // the class where the using-declaration appears.
8306 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8307 }
8308
8309 void inheritAll(CXXRecordDecl *RD) {
8310 visitAll(RD, &InheritingConstructorInfo::inherit);
8311 }
8312
8313private:
8314 /// Information about an inheriting constructor.
8315 struct InheritingConstructor {
8316 InheritingConstructor()
8317 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
8318
8319 /// If \c true, a constructor with this signature is already declared
8320 /// in the derived class.
8321 bool DeclaredInDerived;
8322
8323 /// The constructor which is inherited.
8324 const CXXConstructorDecl *BaseCtor;
8325
8326 /// The derived constructor we declared.
8327 CXXConstructorDecl *DerivedCtor;
8328 };
8329
8330 /// Inheriting constructors with a given canonical type. There can be at
8331 /// most one such non-template constructor, and any number of templated
8332 /// constructors.
8333 struct InheritingConstructorsForType {
8334 InheritingConstructor NonTemplate;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008335 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8336 Templates;
Richard Smith185be182013-04-10 05:48:59 +00008337
8338 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8339 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8340 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8341 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8342 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8343 false, S.TPL_TemplateMatch))
8344 return Templates[I].second;
8345 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8346 return Templates.back().second;
Sebastian Redl08905022011-02-05 19:23:19 +00008347 }
Richard Smith185be182013-04-10 05:48:59 +00008348
8349 return NonTemplate;
8350 }
8351 };
8352
8353 /// Get or create the inheriting constructor record for a constructor.
8354 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8355 QualType CtorType) {
8356 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8357 .getEntry(SemaRef, Ctor);
8358 }
8359
8360 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8361
8362 /// Process all constructors for a class.
8363 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8364 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
8365 CtorE = RD->ctor_end();
8366 CtorIt != CtorE; ++CtorIt)
8367 (this->*Callback)(*CtorIt);
8368 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8369 I(RD->decls_begin()), E(RD->decls_end());
8370 I != E; ++I) {
8371 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8372 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8373 (this->*Callback)(CD);
Sebastian Redl08905022011-02-05 19:23:19 +00008374 }
8375 }
Richard Smith185be182013-04-10 05:48:59 +00008376
8377 /// Note that a constructor (or constructor template) was declared in Derived.
8378 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8379 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8380 }
8381
8382 /// Inherit a single constructor.
8383 void inherit(const CXXConstructorDecl *Ctor) {
8384 const FunctionProtoType *CtorType =
8385 Ctor->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00008386 ArrayRef<QualType> ArgTypes(CtorType->getParamTypes());
Richard Smith185be182013-04-10 05:48:59 +00008387 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8388
8389 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8390
8391 // Core issue (no number yet): the ellipsis is always discarded.
8392 if (EPI.Variadic) {
8393 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8394 SemaRef.Diag(Ctor->getLocation(),
8395 diag::note_using_decl_constructor_ellipsis);
8396 EPI.Variadic = false;
8397 }
8398
8399 // Declare a constructor for each number of parameters.
8400 //
8401 // C++11 [class.inhctor]p1:
8402 // The candidate set of inherited constructors from the class X named in
8403 // the using-declaration consists of [... modulo defects ...] for each
8404 // constructor or constructor template of X, the set of constructors or
8405 // constructor templates that results from omitting any ellipsis parameter
8406 // specification and successively omitting parameters with a default
8407 // argument from the end of the parameter-type-list
Richard Smith3c626ed2013-04-17 19:00:52 +00008408 unsigned MinParams = minParamsToInherit(Ctor);
8409 unsigned Params = Ctor->getNumParams();
8410 if (Params >= MinParams) {
8411 do
8412 declareCtor(UsingLoc, Ctor,
8413 SemaRef.Context.getFunctionType(
8414 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
8415 while (Params > MinParams &&
8416 Ctor->getParamDecl(--Params)->hasDefaultArg());
8417 }
Richard Smith185be182013-04-10 05:48:59 +00008418 }
8419
8420 /// Find the using-declaration which specified that we should inherit the
8421 /// constructors of \p Base.
8422 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8423 // No fancy lookup required; just look for the base constructor name
8424 // directly within the derived class.
8425 ASTContext &Context = SemaRef.Context;
8426 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8427 Context.getCanonicalType(Context.getRecordType(Base)));
8428 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8429 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8430 }
8431
8432 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8433 // C++11 [class.inhctor]p3:
8434 // [F]or each constructor template in the candidate set of inherited
8435 // constructors, a constructor template is implicitly declared
8436 if (Ctor->getDescribedFunctionTemplate())
8437 return 0;
8438
8439 // For each non-template constructor in the candidate set of inherited
8440 // constructors other than a constructor having no parameters or a
8441 // copy/move constructor having a single parameter, a constructor is
8442 // implicitly declared [...]
8443 if (Ctor->getNumParams() == 0)
8444 return 1;
8445 if (Ctor->isCopyOrMoveConstructor())
8446 return 2;
8447
8448 // Per discussion on core reflector, never inherit a constructor which
8449 // would become a default, copy, or move constructor of Derived either.
8450 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8451 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8452 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8453 }
8454
8455 /// Declare a single inheriting constructor, inheriting the specified
8456 /// constructor, with the given type.
8457 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8458 QualType DerivedType) {
8459 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8460
8461 // C++11 [class.inhctor]p3:
8462 // ... a constructor is implicitly declared with the same constructor
8463 // characteristics unless there is a user-declared constructor with
8464 // the same signature in the class where the using-declaration appears
8465 if (Entry.DeclaredInDerived)
8466 return;
8467
8468 // C++11 [class.inhctor]p7:
8469 // If two using-declarations declare inheriting constructors with the
8470 // same signature, the program is ill-formed
8471 if (Entry.DerivedCtor) {
8472 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8473 // Only diagnose this once per constructor.
8474 if (Entry.DerivedCtor->isInvalidDecl())
8475 return;
8476 Entry.DerivedCtor->setInvalidDecl();
8477
8478 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8479 SemaRef.Diag(BaseCtor->getLocation(),
8480 diag::note_using_decl_constructor_conflict_current_ctor);
8481 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8482 diag::note_using_decl_constructor_conflict_previous_ctor);
8483 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8484 diag::note_using_decl_constructor_conflict_previous_using);
8485 } else {
8486 // Core issue (no number): if the same inheriting constructor is
8487 // produced by multiple base class constructors from the same base
8488 // class, the inheriting constructor is defined as deleted.
8489 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8490 }
8491
8492 return;
8493 }
8494
8495 ASTContext &Context = SemaRef.Context;
8496 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8497 Context.getCanonicalType(Context.getRecordType(Derived)));
8498 DeclarationNameInfo NameInfo(Name, UsingLoc);
8499
8500 TemplateParameterList *TemplateParams = 0;
8501 if (const FunctionTemplateDecl *FTD =
8502 BaseCtor->getDescribedFunctionTemplate()) {
8503 TemplateParams = FTD->getTemplateParameters();
8504 // We're reusing template parameters from a different DeclContext. This
8505 // is questionable at best, but works out because the template depth in
8506 // both places is guaranteed to be 0.
8507 // FIXME: Rebuild the template parameters in the new context, and
8508 // transform the function type to refer to them.
8509 }
8510
8511 // Build type source info pointing at the using-declaration. This is
8512 // required by template instantiation.
8513 TypeSourceInfo *TInfo =
8514 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8515 FunctionProtoTypeLoc ProtoLoc =
8516 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8517
8518 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8519 Context, Derived, UsingLoc, NameInfo, DerivedType,
8520 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8521 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8522
8523 // Build an unevaluated exception specification for this constructor.
8524 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8525 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8526 EPI.ExceptionSpecType = EST_Unevaluated;
8527 EPI.ExceptionSpecDecl = DerivedCtor;
8528 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00008529 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +00008530
8531 // Build the parameter declarations.
8532 SmallVector<ParmVarDecl *, 16> ParamDecls;
Alp Toker9cacbab2014-01-20 20:26:09 +00008533 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +00008534 TypeSourceInfo *TInfo =
Alp Toker9cacbab2014-01-20 20:26:09 +00008535 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
Richard Smith185be182013-04-10 05:48:59 +00008536 ParmVarDecl *PD = ParmVarDecl::Create(
8537 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
Alp Toker9cacbab2014-01-20 20:26:09 +00008538 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/0);
Richard Smith185be182013-04-10 05:48:59 +00008539 PD->setScopeInfo(0, I);
8540 PD->setImplicit();
8541 ParamDecls.push_back(PD);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00008542 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +00008543 }
8544
8545 // Set up the new constructor.
8546 DerivedCtor->setAccess(BaseCtor->getAccess());
8547 DerivedCtor->setParams(ParamDecls);
8548 DerivedCtor->setInheritedConstructor(BaseCtor);
8549 if (BaseCtor->isDeleted())
8550 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8551
8552 // If this is a constructor template, build the template declaration.
8553 if (TemplateParams) {
8554 FunctionTemplateDecl *DerivedTemplate =
8555 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8556 TemplateParams, DerivedCtor);
8557 DerivedTemplate->setAccess(BaseCtor->getAccess());
8558 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8559 Derived->addDecl(DerivedTemplate);
8560 } else {
8561 Derived->addDecl(DerivedCtor);
8562 }
8563
8564 Entry.BaseCtor = BaseCtor;
8565 Entry.DerivedCtor = DerivedCtor;
8566 }
8567
8568 Sema &SemaRef;
8569 CXXRecordDecl *Derived;
8570 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8571 MapType Map;
8572};
8573}
8574
8575void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8576 // Defer declaring the inheriting constructors until the class is
8577 // instantiated.
8578 if (ClassDecl->isDependentContext())
Sebastian Redl08905022011-02-05 19:23:19 +00008579 return;
8580
Richard Smith185be182013-04-10 05:48:59 +00008581 // Find base classes from which we might inherit constructors.
8582 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8583 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8584 BaseE = ClassDecl->bases_end();
8585 BaseIt != BaseE; ++BaseIt)
8586 if (BaseIt->getInheritConstructors())
8587 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smithc2bc61b2013-03-18 21:12:30 +00008588
Richard Smith185be182013-04-10 05:48:59 +00008589 // Go no further if we're not inheriting any constructors.
8590 if (InheritedBases.empty())
8591 return;
Sebastian Redl08905022011-02-05 19:23:19 +00008592
Richard Smith185be182013-04-10 05:48:59 +00008593 // Declare the inherited constructors.
8594 InheritingConstructorInfo ICI(*this, ClassDecl);
8595 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8596 ICI.inheritAll(InheritedBases[I]);
Sebastian Redl08905022011-02-05 19:23:19 +00008597}
8598
Richard Smithc2bc61b2013-03-18 21:12:30 +00008599void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8600 CXXConstructorDecl *Constructor) {
8601 CXXRecordDecl *ClassDecl = Constructor->getParent();
8602 assert(Constructor->getInheritedConstructor() &&
8603 !Constructor->doesThisDeclarationHaveABody() &&
8604 !Constructor->isDeleted());
8605
8606 SynthesizedFunctionScope Scope(*this, Constructor);
8607 DiagnosticErrorTrap Trap(Diags);
8608 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8609 Trap.hasErrorOccurred()) {
8610 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8611 << Context.getTagDeclType(ClassDecl);
8612 Constructor->setInvalidDecl();
8613 return;
8614 }
8615
8616 SourceLocation Loc = Constructor->getLocation();
8617 Constructor->setBody(new (Context) CompoundStmt(Loc));
8618
Eli Friedman276dd182013-09-05 00:02:25 +00008619 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +00008620 MarkVTableUsed(CurrentLocation, ClassDecl);
8621
8622 if (ASTMutationListener *L = getASTMutationListener()) {
8623 L->CompletedImplicitDefinition(Constructor);
8624 }
8625}
8626
8627
Alexis Huntf91729462011-05-12 22:46:25 +00008628Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008629Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8630 CXXRecordDecl *ClassDecl = MD->getParent();
8631
Douglas Gregorf1203042010-07-01 19:09:28 +00008632 // C++ [except.spec]p14:
8633 // An implicitly declared special member function (Clause 12) shall have
8634 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +00008635 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008636 if (ClassDecl->isInvalidDecl())
8637 return ExceptSpec;
8638
Douglas Gregorf1203042010-07-01 19:09:28 +00008639 // Direct base-class destructors.
8640 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8641 BEnd = ClassDecl->bases_end();
8642 B != BEnd; ++B) {
8643 if (B->isVirtual()) // Handled below.
8644 continue;
8645
8646 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00008647 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008648 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008649 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008650
Douglas Gregorf1203042010-07-01 19:09:28 +00008651 // Virtual base-class destructors.
8652 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8653 BEnd = ClassDecl->vbases_end();
8654 B != BEnd; ++B) {
8655 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00008656 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008657 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008658 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008659
Douglas Gregorf1203042010-07-01 19:09:28 +00008660 // Field destructors.
8661 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8662 FEnd = ClassDecl->field_end();
8663 F != FEnd; ++F) {
8664 if (const RecordType *RecordTy
8665 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00008666 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008667 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008668 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008669
Alexis Huntf91729462011-05-12 22:46:25 +00008670 return ExceptSpec;
8671}
8672
8673CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8674 // C++ [class.dtor]p2:
8675 // If a class has no user-declared destructor, a destructor is
8676 // declared implicitly. An implicitly-declared destructor is an
8677 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +00008678 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +00008679
Richard Smith8bf22e52012-11-29 01:34:07 +00008680 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8681 if (DSM.isAlreadyBeingDeclared())
8682 return 0;
8683
Douglas Gregor7454c562010-07-02 20:37:36 +00008684 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00008685 CanQualType ClassType
8686 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008687 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00008688 DeclarationName Name
8689 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008690 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00008691 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +00008692 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8693 QualType(), 0, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008694 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00008695 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00008696 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00008697 Destructor->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008698
8699 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008700 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008701 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008702
Richard Smith6b02d462012-12-08 08:32:28 +00008703 AddOverriddenMethods(ClassDecl, Destructor);
8704
8705 // We don't need to use SpecialMemberIsTrivial here; triviality for
8706 // destructors is easy to compute.
8707 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8708
8709 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008710 SetDeclDeleted(Destructor, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008711
Douglas Gregor7454c562010-07-02 20:37:36 +00008712 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00008713 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +00008714
Douglas Gregor7454c562010-07-02 20:37:36 +00008715 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00008716 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00008717 PushOnScopeChains(Destructor, S, false);
8718 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +00008719
Douglas Gregorf1203042010-07-01 19:09:28 +00008720 return Destructor;
8721}
8722
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008723void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00008724 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008725 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +00008726 !Destructor->doesThisDeclarationHaveABody() &&
8727 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008728 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00008729 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008730 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008731
Douglas Gregor54818f02010-05-12 16:39:35 +00008732 if (Destructor->isInvalidDecl())
8733 return;
8734
Eli Friedmaneaf34142012-10-18 20:14:08 +00008735 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008736
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008737 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00008738 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8739 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00008740
Douglas Gregor54818f02010-05-12 16:39:35 +00008741 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008742 Diag(CurrentLocation, diag::note_member_synthesized_at)
8743 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8744
8745 Destructor->setInvalidDecl();
8746 return;
8747 }
8748
Douglas Gregor73193272010-09-20 16:48:21 +00008749 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008750 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +00008751 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008752 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008753
8754 if (ASTMutationListener *L = getASTMutationListener()) {
8755 L->CompletedImplicitDefinition(Destructor);
8756 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008757}
8758
Richard Smith84973e52012-04-21 18:42:51 +00008759/// \brief Perform any semantic analysis which needs to be delayed until all
8760/// pending class member declarations have been parsed.
8761void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00008762 // If the context is an invalid C++ class, just suppress these checks.
8763 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8764 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008765 DelayedDefaultedMemberExceptionSpecs.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00008766 DelayedDestructorExceptionSpecChecks.clear();
8767 return;
8768 }
8769 }
Richard Smith84973e52012-04-21 18:42:51 +00008770}
8771
Richard Smithd3b5c9082012-07-27 04:22:15 +00008772void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8773 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008774 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00008775 "adjusting dtor exception specs was introduced in c++11");
8776
Sebastian Redl623ea822011-05-19 05:13:44 +00008777 // C++11 [class.dtor]p3:
8778 // A declaration of a destructor that does not have an exception-
8779 // specification is implicitly considered to have the same exception-
8780 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008781 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +00008782 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008783 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +00008784 return;
8785
Chandler Carruth9a797572011-09-20 04:55:26 +00008786 // Replace the destructor's type, building off the existing one. Fortunately,
8787 // the only thing of interest in the destructor type is its extended info.
8788 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008789 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8790 EPI.ExceptionSpecType = EST_Unevaluated;
8791 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008792 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +00008793
Sebastian Redl623ea822011-05-19 05:13:44 +00008794 // FIXME: If the destructor has a body that could throw, and the newly created
8795 // spec doesn't allow exceptions, we should emit a warning, because this
8796 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +00008797 // However, we don't have a body or an exception specification yet, so it
8798 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +00008799}
8800
Pavel Labath58934982013-08-30 08:52:28 +00008801namespace {
8802/// \brief An abstract base class for all helper classes used in building the
8803// copy/move operators. These classes serve as factory functions and help us
8804// avoid using the same Expr* in the AST twice.
8805class ExprBuilder {
8806 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8807 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8808
8809protected:
8810 static Expr *assertNotNull(Expr *E) {
8811 assert(E && "Expression construction must not fail.");
8812 return E;
8813 }
8814
8815public:
8816 ExprBuilder() {}
8817 virtual ~ExprBuilder() {}
8818
8819 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8820};
8821
8822class RefBuilder: public ExprBuilder {
8823 VarDecl *Var;
8824 QualType VarType;
8825
8826public:
8827 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8828 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take());
8829 }
8830
8831 RefBuilder(VarDecl *Var, QualType VarType)
8832 : Var(Var), VarType(VarType) {}
8833};
8834
8835class ThisBuilder: public ExprBuilder {
8836public:
8837 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8838 return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>());
8839 }
8840};
8841
8842class CastBuilder: public ExprBuilder {
8843 const ExprBuilder &Builder;
8844 QualType Type;
8845 ExprValueKind Kind;
8846 const CXXCastPath &Path;
8847
8848public:
8849 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8850 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8851 CK_UncheckedDerivedToBase, Kind,
8852 &Path).take());
8853 }
8854
8855 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8856 const CXXCastPath &Path)
8857 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8858};
8859
8860class DerefBuilder: public ExprBuilder {
8861 const ExprBuilder &Builder;
8862
8863public:
8864 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8865 return assertNotNull(
8866 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take());
8867 }
8868
8869 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8870};
8871
8872class MemberBuilder: public ExprBuilder {
8873 const ExprBuilder &Builder;
8874 QualType Type;
8875 CXXScopeSpec SS;
8876 bool IsArrow;
8877 LookupResult &MemberLookup;
8878
8879public:
8880 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8881 return assertNotNull(S.BuildMemberReferenceExpr(
8882 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0,
8883 MemberLookup, 0).take());
8884 }
8885
8886 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
8887 LookupResult &MemberLookup)
8888 : Builder(Builder), Type(Type), IsArrow(IsArrow),
8889 MemberLookup(MemberLookup) {}
8890};
8891
8892class MoveCastBuilder: public ExprBuilder {
8893 const ExprBuilder &Builder;
8894
8895public:
8896 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8897 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
8898 }
8899
8900 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8901};
8902
8903class LvalueConvBuilder: public ExprBuilder {
8904 const ExprBuilder &Builder;
8905
8906public:
8907 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8908 return assertNotNull(
8909 S.DefaultLvalueConversion(Builder.build(S, Loc)).take());
8910 }
8911
8912 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8913};
8914
8915class SubscriptBuilder: public ExprBuilder {
8916 const ExprBuilder &Base;
8917 const ExprBuilder &Index;
8918
8919public:
8920 virtual Expr *build(Sema &S, SourceLocation Loc) const
8921 LLVM_OVERRIDE {
8922 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
8923 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take());
8924 }
8925
8926 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
8927 : Base(Base), Index(Index) {}
8928};
8929
8930} // end anonymous namespace
8931
Richard Smith41ae3282012-11-14 00:50:40 +00008932/// When generating a defaulted copy or move assignment operator, if a field
8933/// should be copied with __builtin_memcpy rather than via explicit assignments,
8934/// do so. This optimization only applies for arrays of scalars, and for arrays
8935/// of class type where the selected copy/move-assignment operator is trivial.
8936static StmtResult
8937buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00008938 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +00008939 // Compute the size of the memory buffer to be copied.
8940 QualType SizeType = S.Context.getSizeType();
8941 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8942 S.Context.getTypeSizeInChars(T).getQuantity());
8943
8944 // Take the address of the field references for "from" and "to". We
8945 // directly construct UnaryOperators here because semantic analysis
8946 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +00008947 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00008948 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8949 S.Context.getPointerType(From->getType()),
8950 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +00008951 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00008952 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8953 S.Context.getPointerType(To->getType()),
8954 VK_RValue, OK_Ordinary, Loc);
8955
8956 const Type *E = T->getBaseElementTypeUnsafe();
8957 bool NeedsCollectableMemCpy =
8958 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8959
8960 // Create a reference to the __builtin_objc_memmove_collectable function
8961 StringRef MemCpyName = NeedsCollectableMemCpy ?
8962 "__builtin_objc_memmove_collectable" :
8963 "__builtin_memcpy";
8964 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8965 Sema::LookupOrdinaryName);
8966 S.LookupName(R, S.TUScope, true);
8967
8968 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8969 if (!MemCpy)
8970 // Something went horribly wrong earlier, and we will have complained
8971 // about it.
8972 return StmtError();
8973
8974 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8975 VK_RValue, Loc, 0);
8976 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8977
8978 Expr *CallArgs[] = {
8979 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8980 };
8981 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8982 Loc, CallArgs, Loc);
8983
8984 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8985 return S.Owned(Call.takeAs<Stmt>());
8986}
8987
Sebastian Redl22653ba2011-08-30 19:58:05 +00008988/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00008989/// \c To.
8990///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008991/// This routine is used to copy/move the members of a class with an
8992/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00008993/// copied are arrays, this routine builds for loops to copy them.
8994///
8995/// \param S The Sema object used for type-checking.
8996///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008997/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00008998///
Sebastian Redl22653ba2011-08-30 19:58:05 +00008999/// \param T The type of the expressions being copied/moved. Both expressions
9000/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009001///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009002/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009003///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009004/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009005///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009006/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009007/// Otherwise, it's a non-static member subobject.
9008///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009009/// \param Copying Whether we're copying or moving.
9010///
Douglas Gregorb139cd52010-05-01 20:49:11 +00009011/// \param Depth Internal parameter recording the depth of the recursion.
9012///
Richard Smith41ae3282012-11-14 00:50:40 +00009013/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9014/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +00009015static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +00009016buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009017 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009018 bool CopyingBaseSubobject, bool Copying,
9019 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +00009020 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00009021 // Each subobject is assigned in the manner appropriate to its type:
9022 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00009023 // - if the subobject is of class type, as if by a call to operator= with
9024 // the subobject as the object expression and the corresponding
9025 // subobject of x as a single function argument (as if by explicit
9026 // qualification; that is, ignoring any possible virtual overriding
9027 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +00009028 //
9029 // C++03 [class.copy]p13:
9030 // - if the subobject is of class type, the copy assignment operator for
9031 // the class is used (as if by explicit qualification; that is,
9032 // ignoring any possible virtual overriding functions in more derived
9033 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009034 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9035 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +00009036
Douglas Gregorb139cd52010-05-01 20:49:11 +00009037 // Look for operator=.
9038 DeclarationName Name
9039 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9040 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9041 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009042
Richard Smith52c0b582012-11-13 00:54:12 +00009043 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9044 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009045 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +00009046 LookupResult::Filter F = OpLookup.makeFilter();
9047 while (F.hasNext()) {
9048 NamedDecl *D = F.next();
9049 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9050 if (Method->isCopyAssignmentOperator() ||
9051 (!Copying && Method->isMoveAssignmentOperator()))
9052 continue;
9053
9054 F.erase();
9055 }
9056 F.done();
John McCallab8c2732010-03-16 06:11:48 +00009057 }
Richard Smith52c0b582012-11-13 00:54:12 +00009058
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009059 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +00009060 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009061 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +00009062 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009063 // ambiguities), we need to cast "this" to that subobject type; to
9064 // ensure that we don't go through the virtual call mechanism, we need
9065 // to qualify the operator= name with the base class (see below). However,
9066 // this means that if the base class has a protected copy assignment
9067 // operator, the protected member access check will fail. So, we
9068 // rewrite "protected" access to "public" access in this case, since we
9069 // know by construction that we're calling from a derived class.
9070 if (CopyingBaseSubobject) {
9071 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9072 L != LEnd; ++L) {
9073 if (L.getAccess() == AS_protected)
9074 L.setAccess(AS_public);
9075 }
9076 }
Richard Smith52c0b582012-11-13 00:54:12 +00009077
Douglas Gregorb139cd52010-05-01 20:49:11 +00009078 // Create the nested-name-specifier that will be used to qualify the
9079 // reference to operator=; this is required to suppress the virtual
9080 // call mechanism.
9081 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00009082 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +00009083 SS.MakeTrivial(S.Context,
9084 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00009085 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00009086 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009087
Douglas Gregorb139cd52010-05-01 20:49:11 +00009088 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00009089 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +00009090 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9091 SS, /*TemplateKWLoc=*/SourceLocation(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00009092 /*FirstQualifierInScope=*/0,
9093 OpLookup,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009094 /*TemplateArgs=*/0,
9095 /*SuppressQualifierCheck=*/true);
9096 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009097 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009098
Douglas Gregorb139cd52010-05-01 20:49:11 +00009099 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00009100
Pavel Labath58934982013-08-30 08:52:28 +00009101 Expr *FromInst = From.build(S, Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009102 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00009103 OpEqualRef.takeAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +00009104 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009105 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009106 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009107
Richard Smith41ae3282012-11-14 00:50:40 +00009108 // If we built a call to a trivial 'operator=' while copying an array,
9109 // bail out. We'll replace the whole shebang with a memcpy.
9110 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9111 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9112 return StmtResult((Stmt*)0);
9113
Richard Smith52c0b582012-11-13 00:54:12 +00009114 // Convert to an expression-statement, and clean up any produced
9115 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +00009116 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009117 }
John McCallab8c2732010-03-16 06:11:48 +00009118
Richard Smith52c0b582012-11-13 00:54:12 +00009119 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +00009120 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +00009121 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009122 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +00009123 ExprResult Assignment = S.CreateBuiltinBinOp(
9124 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009125 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009126 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +00009127 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009128 }
Richard Smith52c0b582012-11-13 00:54:12 +00009129
9130 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +00009131 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +00009132
Douglas Gregorb139cd52010-05-01 20:49:11 +00009133 // Construct a loop over the array bounds, e.g.,
9134 //
9135 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9136 //
9137 // that will copy each of the array elements.
9138 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +00009139
Douglas Gregorb139cd52010-05-01 20:49:11 +00009140 // Create the iteration variable.
9141 IdentifierInfo *IterationVarName = 0;
9142 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009143 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009144 llvm::raw_svector_ostream OS(Str);
9145 OS << "__i" << Depth;
9146 IterationVarName = &S.Context.Idents.get(OS.str());
9147 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00009148 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009149 IterationVarName, SizeType,
9150 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009151 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +00009152
Douglas Gregorb139cd52010-05-01 20:49:11 +00009153 // Initialize the iteration variable to zero.
9154 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009155 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009156
Pavel Labath58934982013-08-30 08:52:28 +00009157 // Creates a reference to the iteration variable.
9158 RefBuilder IterationVarRef(IterationVar, SizeType);
9159 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +00009160
Douglas Gregorb139cd52010-05-01 20:49:11 +00009161 // Create the DeclStmt that holds the iteration variable.
9162 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009163
Douglas Gregorb139cd52010-05-01 20:49:11 +00009164 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +00009165 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9166 MoveCastBuilder FromIndexMove(FromIndexCopy);
9167 const ExprBuilder *FromIndex;
9168 if (Copying)
9169 FromIndex = &FromIndexCopy;
9170 else
9171 FromIndex = &FromIndexMove;
9172
9173 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009174
9175 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +00009176 StmtResult Copy =
9177 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +00009178 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +00009179 Copying, Depth + 1);
9180 // Bail out if copying fails or if we determined that we should use memcpy.
9181 if (Copy.isInvalid() || !Copy.get())
9182 return Copy;
9183
9184 // Create the comparison against the array bound.
9185 llvm::APInt Upper
9186 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9187 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +00009188 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +00009189 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9190 BO_NE, S.Context.BoolTy,
9191 VK_RValue, OK_Ordinary, Loc, false);
9192
9193 // Create the pre-increment of the iteration variable.
9194 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +00009195 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9196 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009197
Douglas Gregorb139cd52010-05-01 20:49:11 +00009198 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00009199 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009200 S.MakeFullExpr(Comparison),
Richard Smith945f8d32013-01-14 22:39:08 +00009201 0, S.MakeFullDiscardedValueExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00009202 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009203}
9204
Richard Smith41ae3282012-11-14 00:50:40 +00009205static StmtResult
9206buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009207 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009208 bool CopyingBaseSubobject, bool Copying) {
9209 // Maybe we should use a memcpy?
9210 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9211 T.isTriviallyCopyableType(S.Context))
9212 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9213
9214 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9215 CopyingBaseSubobject,
9216 Copying, 0));
9217
9218 // If we ended up picking a trivial assignment operator for an array of a
9219 // non-trivially-copyable class type, just emit a memcpy.
9220 if (!Result.isInvalid() && !Result.get())
9221 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9222
9223 return Result;
9224}
9225
Richard Smithd3b5c9082012-07-27 04:22:15 +00009226Sema::ImplicitExceptionSpecification
9227Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9228 CXXRecordDecl *ClassDecl = MD->getParent();
9229
9230 ImplicitExceptionSpecification ExceptSpec(*this);
9231 if (ClassDecl->isInvalidDecl())
9232 return ExceptSpec;
9233
9234 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00009235 assert(T->getNumParams() == 1 && "not a copy assignment op");
9236 unsigned ArgQuals =
9237 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009238
Douglas Gregor68e11362010-07-01 17:48:08 +00009239 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +00009240 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +00009241 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00009242
9243 // It is unspecified whether or not an implicit copy assignment operator
9244 // attempts to deduplicate calls to assignment operators of virtual bases are
9245 // made. As such, this exception specification is effectively unspecified.
9246 // Based on a similar decision made for constness in C++0x, we're erring on
9247 // the side of assuming such calls to be made regardless of whether they
9248 // actually happen.
Douglas Gregor68e11362010-07-01 17:48:08 +00009249 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9250 BaseEnd = ClassDecl->bases_end();
9251 Base != BaseEnd; ++Base) {
Alexis Hunt491ec602011-06-21 23:42:56 +00009252 if (Base->isVirtual())
9253 continue;
9254
Douglas Gregor330b9cf2010-07-02 21:50:04 +00009255 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00009256 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009257 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9258 ArgQuals, false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009259 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00009260 }
Alexis Hunt491ec602011-06-21 23:42:56 +00009261
9262 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9263 BaseEnd = ClassDecl->vbases_end();
9264 Base != BaseEnd; ++Base) {
9265 CXXRecordDecl *BaseClassDecl
9266 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9267 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9268 ArgQuals, false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009269 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +00009270 }
9271
Douglas Gregor68e11362010-07-01 17:48:08 +00009272 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9273 FieldEnd = ClassDecl->field_end();
9274 Field != FieldEnd;
9275 ++Field) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009276 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00009277 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9278 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +00009279 LookupCopyingAssignment(FieldClassDecl,
9280 ArgQuals | FieldType.getCVRQualifiers(),
9281 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009282 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009283 }
Douglas Gregor68e11362010-07-01 17:48:08 +00009284 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009285
Richard Smithd3b5c9082012-07-27 04:22:15 +00009286 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +00009287}
9288
9289CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9290 // Note: The following rules are largely analoguous to the copy
9291 // constructor rules. Note that virtual bases are not taken into account
9292 // for determining the argument type of the operator. Note also that
9293 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +00009294 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +00009295
Richard Smith8bf22e52012-11-29 01:34:07 +00009296 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9297 if (DSM.isAlreadyBeingDeclared())
9298 return 0;
9299
Alexis Hunt119f3652011-05-14 05:23:20 +00009300 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9301 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +00009302 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9303 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +00009304 ArgType = ArgType.withConst();
9305 ArgType = Context.getLValueReferenceType(ArgType);
9306
Richard Smith99005e62013-05-07 03:19:20 +00009307 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9308 CXXCopyAssignment,
9309 Const);
9310
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009311 // An implicitly-declared copy assignment operator is an inline public
9312 // member of its class.
9313 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009314 SourceLocation ClassLoc = ClassDecl->getLocation();
9315 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009316 CXXMethodDecl *CopyAssignment =
9317 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9318 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
9319 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009320 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00009321 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009322 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009323
9324 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009325 FunctionProtoType::ExtProtoInfo EPI =
9326 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009327 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009328
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009329 // Add the parameter to the operator.
9330 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00009331 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009332 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00009333 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00009334 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +00009335
Richard Smith6b02d462012-12-08 08:32:28 +00009336 AddOverriddenMethods(ClassDecl, CopyAssignment);
9337
9338 CopyAssignment->setTrivial(
9339 ClassDecl->needsOverloadResolutionForCopyAssignment()
9340 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9341 : ClassDecl->hasTrivialCopyAssignment());
9342
Richard Smith852265f2012-03-30 20:53:28 +00009343 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smithb4d2a152013-04-02 19:38:47 +00009344 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +00009345
Richard Smith6b02d462012-12-08 08:32:28 +00009346 // Note that we have added this copy-assignment operator.
9347 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9348
9349 if (Scope *S = getScopeForContext(ClassDecl))
9350 PushOnScopeChains(CopyAssignment, S, false);
9351 ClassDecl->addDecl(CopyAssignment);
9352
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009353 return CopyAssignment;
9354}
9355
Richard Smithd577fbb2013-06-13 03:23:42 +00009356/// Diagnose an implicit copy operation for a class which is odr-used, but
9357/// which is deprecated because the class has a user-declared copy constructor,
9358/// copy assignment operator, or destructor.
9359static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9360 SourceLocation UseLoc) {
9361 assert(CopyOp->isImplicit());
9362
9363 CXXRecordDecl *RD = CopyOp->getParent();
9364 CXXMethodDecl *UserDeclaredOperation = 0;
9365
9366 // In Microsoft mode, assignment operations don't affect constructors and
9367 // vice versa.
9368 if (RD->hasUserDeclaredDestructor()) {
9369 UserDeclaredOperation = RD->getDestructor();
9370 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9371 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009372 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009373 // Find any user-declared copy constructor.
9374 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
9375 E = RD->ctor_end(); I != E; ++I) {
9376 if (I->isCopyConstructor()) {
9377 UserDeclaredOperation = *I;
9378 break;
9379 }
9380 }
9381 assert(UserDeclaredOperation);
9382 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9383 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009384 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009385 // Find any user-declared move assignment operator.
9386 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
9387 E = RD->method_end(); I != E; ++I) {
9388 if (I->isCopyAssignmentOperator()) {
9389 UserDeclaredOperation = *I;
9390 break;
9391 }
9392 }
9393 assert(UserDeclaredOperation);
9394 }
9395
9396 if (UserDeclaredOperation) {
9397 S.Diag(UserDeclaredOperation->getLocation(),
9398 diag::warn_deprecated_copy_operation)
9399 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9400 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9401 S.Diag(UseLoc, diag::note_member_synthesized_at)
9402 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9403 : Sema::CXXCopyAssignment)
9404 << RD;
9405 }
9406}
9407
Douglas Gregorb139cd52010-05-01 20:49:11 +00009408void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9409 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00009410 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009411 CopyAssignOperator->isOverloadedOperator() &&
9412 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009413 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9414 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009415 "DefineImplicitCopyAssignment called for wrong function");
9416
9417 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9418
9419 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9420 CopyAssignOperator->setInvalidDecl();
9421 return;
9422 }
Richard Smithd577fbb2013-06-13 03:23:42 +00009423
9424 // C++11 [class.copy]p18:
9425 // The [definition of an implicitly declared copy assignment operator] is
9426 // deprecated if the class has a user-declared copy constructor or a
9427 // user-declared destructor.
9428 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9429 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9430
Eli Friedman276dd182013-09-05 00:02:25 +00009431 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009432
Eli Friedmaneaf34142012-10-18 20:14:08 +00009433 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009434 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009435
9436 // C++0x [class.copy]p30:
9437 // The implicitly-defined or explicitly-defaulted copy assignment operator
9438 // for a non-union class X performs memberwise copy assignment of its
9439 // subobjects. The direct base classes of X are assigned first, in the
9440 // order of their declaration in the base-specifier-list, and then the
9441 // immediate non-static data members of X are assigned, in the order in
9442 // which they were declared in the class definition.
9443
9444 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009445 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009446
9447 // The parameter for the "other" object, which we are copying from.
9448 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9449 Qualifiers OtherQuals = Other->getType().getQualifiers();
9450 QualType OtherRefType = Other->getType();
9451 if (const LValueReferenceType *OtherRef
9452 = OtherRefType->getAs<LValueReferenceType>()) {
9453 OtherRefType = OtherRef->getPointeeType();
9454 OtherQuals = OtherRefType.getQualifiers();
9455 }
9456
9457 // Our location for everything implicitly-generated.
9458 SourceLocation Loc = CopyAssignOperator->getLocation();
9459
Pavel Labath58934982013-08-30 08:52:28 +00009460 // Builds a DeclRefExpr for the "other" object.
9461 RefBuilder OtherRef(Other, OtherRefType);
9462
9463 // Builds the "this" pointer.
9464 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009465
9466 // Assign base classes.
9467 bool Invalid = false;
9468 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9469 E = ClassDecl->bases_end(); Base != E; ++Base) {
9470 // Form the assignment:
9471 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9472 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009473 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009474 Invalid = true;
9475 continue;
9476 }
9477
John McCallcf142162010-08-07 06:22:56 +00009478 CXXCastPath BasePath;
9479 BasePath.push_back(Base);
9480
Douglas Gregorb139cd52010-05-01 20:49:11 +00009481 // Construct the "from" expression, which is an implicit cast to the
9482 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009483 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9484 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009485
9486 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009487 DerefBuilder DerefThis(This);
9488 CastBuilder To(DerefThis,
9489 Context.getCVRQualifiedType(
9490 BaseType, CopyAssignOperator->getTypeQualifiers()),
9491 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009492
9493 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +00009494 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +00009495 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009496 /*CopyingBaseSubobject=*/true,
9497 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009498 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009499 Diag(CurrentLocation, diag::note_member_synthesized_at)
9500 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9501 CopyAssignOperator->setInvalidDecl();
9502 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009503 }
9504
9505 // Success! Record the copy.
9506 Statements.push_back(Copy.takeAs<Expr>());
9507 }
9508
Douglas Gregorb139cd52010-05-01 20:49:11 +00009509 // Assign non-static members.
9510 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9511 FieldEnd = ClassDecl->field_end();
9512 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009513 if (Field->isUnnamedBitfield())
9514 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009515
9516 if (Field->isInvalidDecl()) {
9517 Invalid = true;
9518 continue;
9519 }
9520
Douglas Gregorb139cd52010-05-01 20:49:11 +00009521 // Check for members of reference type; we can't copy those.
9522 if (Field->getType()->isReferenceType()) {
9523 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9524 << Context.getTagDeclType(ClassDecl) << 0 << 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 }
9531
9532 // Check for members of const-qualified, non-class type.
9533 QualType BaseType = Context.getBaseElementType(Field->getType());
9534 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9535 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9536 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9537 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009538 Diag(CurrentLocation, diag::note_member_synthesized_at)
9539 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009540 Invalid = true;
9541 continue;
9542 }
John McCall1b1a1db2011-06-17 00:18:42 +00009543
9544 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009545 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9546 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009547
9548 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00009549 if (FieldType->isIncompleteArrayType()) {
9550 assert(ClassDecl->hasFlexibleArrayMember() &&
9551 "Incomplete array type is not valid");
9552 continue;
9553 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009554
9555 // Build references to the field in the object we're copying from and to.
9556 CXXScopeSpec SS; // Intentionally empty
9557 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9558 LookupMemberName);
David Blaikie40ed2972012-06-06 20:45:41 +00009559 MemberLookup.addDecl(*Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009560 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +00009561
9562 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9563
9564 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009565
Douglas Gregorb139cd52010-05-01 20:49:11 +00009566 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +00009567 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +00009568 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009569 /*CopyingBaseSubobject=*/false,
9570 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009571 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009572 Diag(CurrentLocation, diag::note_member_synthesized_at)
9573 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9574 CopyAssignOperator->setInvalidDecl();
9575 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009576 }
9577
9578 // Success! Record the copy.
9579 Statements.push_back(Copy.takeAs<Stmt>());
9580 }
9581
9582 if (!Invalid) {
9583 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +00009584 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009585
John McCalldadc5752010-08-24 06:29:42 +00009586 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009587 if (Return.isInvalid())
9588 Invalid = true;
9589 else {
9590 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00009591
9592 if (Trap.hasErrorOccurred()) {
9593 Diag(CurrentLocation, diag::note_member_synthesized_at)
9594 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9595 Invalid = true;
9596 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009597 }
9598 }
9599
9600 if (Invalid) {
9601 CopyAssignOperator->setInvalidDecl();
9602 return;
9603 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009604
9605 StmtResult Body;
9606 {
9607 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009608 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009609 /*isStmtExpr=*/false);
9610 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9611 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009612 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00009613
9614 if (ASTMutationListener *L = getASTMutationListener()) {
9615 L->CompletedImplicitDefinition(CopyAssignOperator);
9616 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009617}
9618
Sebastian Redl22653ba2011-08-30 19:58:05 +00009619Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009620Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9621 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009622
Richard Smithd3b5c9082012-07-27 04:22:15 +00009623 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009624 if (ClassDecl->isInvalidDecl())
9625 return ExceptSpec;
9626
9627 // C++0x [except.spec]p14:
9628 // An implicitly declared special member function (Clause 12) shall have an
9629 // exception-specification. [...]
9630
9631 // It is unspecified whether or not an implicit move assignment operator
9632 // attempts to deduplicate calls to assignment operators of virtual bases are
9633 // made. As such, this exception specification is effectively unspecified.
9634 // Based on a similar decision made for constness in C++0x, we're erring on
9635 // the side of assuming such calls to be made regardless of whether they
9636 // actually happen.
9637 // Note that a move constructor is not implicitly declared when there are
9638 // virtual bases, but it can still be user-declared and explicitly defaulted.
9639 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9640 BaseEnd = ClassDecl->bases_end();
9641 Base != BaseEnd; ++Base) {
9642 if (Base->isVirtual())
9643 continue;
9644
9645 CXXRecordDecl *BaseClassDecl
9646 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9647 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009648 0, false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009649 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009650 }
9651
9652 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9653 BaseEnd = ClassDecl->vbases_end();
9654 Base != BaseEnd; ++Base) {
9655 CXXRecordDecl *BaseClassDecl
9656 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9657 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009658 0, false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009659 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009660 }
9661
9662 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9663 FieldEnd = ClassDecl->field_end();
9664 Field != FieldEnd;
9665 ++Field) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009666 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009667 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +00009668 if (CXXMethodDecl *MoveAssign =
9669 LookupMovingAssignment(FieldClassDecl,
9670 FieldType.getCVRQualifiers(),
9671 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009672 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009673 }
9674 }
9675
9676 return ExceptSpec;
9677}
9678
9679CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009680 assert(ClassDecl->needsImplicitMoveAssignment());
9681
Richard Smith8bf22e52012-11-29 01:34:07 +00009682 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9683 if (DSM.isAlreadyBeingDeclared())
9684 return 0;
9685
Sebastian Redl22653ba2011-08-30 19:58:05 +00009686 // Note: The following rules are largely analoguous to the move
9687 // constructor rules.
9688
Sebastian Redl22653ba2011-08-30 19:58:05 +00009689 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9690 QualType RetType = Context.getLValueReferenceType(ArgType);
9691 ArgType = Context.getRValueReferenceType(ArgType);
9692
Richard Smith99005e62013-05-07 03:19:20 +00009693 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9694 CXXMoveAssignment,
9695 false);
9696
Sebastian Redl22653ba2011-08-30 19:58:05 +00009697 // An implicitly-declared move assignment operator is an inline public
9698 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +00009699 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9700 SourceLocation ClassLoc = ClassDecl->getLocation();
9701 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009702 CXXMethodDecl *MoveAssignment =
9703 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9704 /*TInfo=*/0, /*StorageClass=*/SC_None,
9705 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009706 MoveAssignment->setAccess(AS_public);
9707 MoveAssignment->setDefaulted();
9708 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009709
Richard Smithd3b5c9082012-07-27 04:22:15 +00009710 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009711 FunctionProtoType::ExtProtoInfo EPI =
9712 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009713 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009714
Sebastian Redl22653ba2011-08-30 19:58:05 +00009715 // Add the parameter to the operator.
9716 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9717 ClassLoc, ClassLoc, /*Id=*/0,
9718 ArgType, /*TInfo=*/0,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009719 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00009720 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009721
Richard Smith6b02d462012-12-08 08:32:28 +00009722 AddOverriddenMethods(ClassDecl, MoveAssignment);
9723
9724 MoveAssignment->setTrivial(
9725 ClassDecl->needsOverloadResolutionForMoveAssignment()
9726 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9727 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009728
Richard Smithd951a1d2012-02-18 02:02:13 +00009729 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +00009730 ClassDecl->setImplicitMoveAssignmentIsDeleted();
9731 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009732 }
9733
Richard Smith6b02d462012-12-08 08:32:28 +00009734 // Note that we have added this copy-assignment operator.
9735 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9736
Sebastian Redl22653ba2011-08-30 19:58:05 +00009737 if (Scope *S = getScopeForContext(ClassDecl))
9738 PushOnScopeChains(MoveAssignment, S, false);
9739 ClassDecl->addDecl(MoveAssignment);
9740
Sebastian Redl22653ba2011-08-30 19:58:05 +00009741 return MoveAssignment;
9742}
9743
Richard Smithb2504bd2013-11-04 04:26:14 +00009744/// Check if we're implicitly defining a move assignment operator for a class
9745/// with virtual bases. Such a move assignment might move-assign the virtual
9746/// base multiple times.
9747static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
9748 SourceLocation CurrentLocation) {
9749 assert(!Class->isDependentContext() && "should not define dependent move");
9750
9751 // Only a virtual base could get implicitly move-assigned multiple times.
9752 // Only a non-trivial move assignment can observe this. We only want to
9753 // diagnose if we implicitly define an assignment operator that assigns
9754 // two base classes, both of which move-assign the same virtual base.
9755 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
9756 Class->getNumBases() < 2)
9757 return;
9758
9759 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
9760 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
9761 VBaseMap VBases;
9762
9763 for (CXXRecordDecl::base_class_iterator BI = Class->bases_begin(),
9764 BE = Class->bases_end();
9765 BI != BE; ++BI) {
9766 Worklist.push_back(&*BI);
9767 while (!Worklist.empty()) {
9768 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
9769 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
9770
9771 // If the base has no non-trivial move assignment operators,
9772 // we don't care about moves from it.
9773 if (!Base->hasNonTrivialMoveAssignment())
9774 continue;
9775
9776 // If there's nothing virtual here, skip it.
9777 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
9778 continue;
9779
9780 // If we're not actually going to call a move assignment for this base,
9781 // or the selected move assignment is trivial, skip it.
9782 Sema::SpecialMemberOverloadResult *SMOR =
9783 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
9784 /*ConstArg*/false, /*VolatileArg*/false,
9785 /*RValueThis*/true, /*ConstThis*/false,
9786 /*VolatileThis*/false);
9787 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
9788 !SMOR->getMethod()->isMoveAssignmentOperator())
9789 continue;
9790
9791 if (BaseSpec->isVirtual()) {
9792 // We're going to move-assign this virtual base, and its move
9793 // assignment operator is not trivial. If this can happen for
9794 // multiple distinct direct bases of Class, diagnose it. (If it
9795 // only happens in one base, we'll diagnose it when synthesizing
9796 // that base class's move assignment operator.)
9797 CXXBaseSpecifier *&Existing =
9798 VBases.insert(std::make_pair(Base->getCanonicalDecl(), BI))
9799 .first->second;
9800 if (Existing && Existing != BI) {
9801 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
9802 << Class << Base;
9803 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
9804 << (Base->getCanonicalDecl() ==
9805 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9806 << Base << Existing->getType() << Existing->getSourceRange();
9807 S.Diag(BI->getLocStart(), diag::note_vbase_moved_here)
9808 << (Base->getCanonicalDecl() ==
9809 BI->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
9810 << Base << BI->getType() << BaseSpec->getSourceRange();
9811
9812 // Only diagnose each vbase once.
9813 Existing = 0;
9814 }
9815 } else {
9816 // Only walk over bases that have defaulted move assignment operators.
9817 // We assume that any user-provided move assignment operator handles
9818 // the multiple-moves-of-vbase case itself somehow.
9819 if (!SMOR->getMethod()->isDefaulted())
9820 continue;
9821
9822 // We're going to move the base classes of Base. Add them to the list.
9823 for (CXXRecordDecl::base_class_iterator BI = Base->bases_begin(),
9824 BE = Base->bases_end();
9825 BI != BE; ++BI)
9826 Worklist.push_back(&*BI);
9827 }
9828 }
9829 }
9830}
9831
Sebastian Redl22653ba2011-08-30 19:58:05 +00009832void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9833 CXXMethodDecl *MoveAssignOperator) {
9834 assert((MoveAssignOperator->isDefaulted() &&
9835 MoveAssignOperator->isOverloadedOperator() &&
9836 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009837 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9838 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +00009839 "DefineImplicitMoveAssignment called for wrong function");
9840
9841 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9842
9843 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9844 MoveAssignOperator->setInvalidDecl();
9845 return;
9846 }
9847
Eli Friedman276dd182013-09-05 00:02:25 +00009848 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009849
Eli Friedmaneaf34142012-10-18 20:14:08 +00009850 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009851 DiagnosticErrorTrap Trap(Diags);
9852
9853 // C++0x [class.copy]p28:
9854 // The implicitly-defined or move assignment operator for a non-union class
9855 // X performs memberwise move assignment of its subobjects. The direct base
9856 // classes of X are assigned first, in the order of their declaration in the
9857 // base-specifier-list, and then the immediate non-static data members of X
9858 // are assigned, in the order in which they were declared in the class
9859 // definition.
9860
Richard Smithb2504bd2013-11-04 04:26:14 +00009861 // Issue a warning if our implicit move assignment operator will move
9862 // from a virtual base more than once.
9863 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +00009864
Sebastian Redl22653ba2011-08-30 19:58:05 +00009865 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009866 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +00009867
9868 // The parameter for the "other" object, which we are move from.
9869 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9870 QualType OtherRefType = Other->getType()->
9871 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +00009872 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +00009873 "Bad argument type of defaulted move assignment");
9874
9875 // Our location for everything implicitly-generated.
9876 SourceLocation Loc = MoveAssignOperator->getLocation();
9877
Pavel Labath58934982013-08-30 08:52:28 +00009878 // Builds a reference to the "other" object.
9879 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009880 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009881 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009882
Pavel Labath58934982013-08-30 08:52:28 +00009883 // Builds the "this" pointer.
9884 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009885
Sebastian Redl22653ba2011-08-30 19:58:05 +00009886 // Assign base classes.
9887 bool Invalid = false;
9888 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9889 E = ClassDecl->bases_end(); Base != E; ++Base) {
Richard Smithb2504bd2013-11-04 04:26:14 +00009890 // C++11 [class.copy]p28:
9891 // It is unspecified whether subobjects representing virtual base classes
9892 // are assigned more than once by the implicitly-defined copy assignment
9893 // operator.
9894 // FIXME: Do not assign to a vbase that will be assigned by some other base
9895 // class. For a move-assignment, this can result in the vbase being moved
9896 // multiple times.
9897
Sebastian Redl22653ba2011-08-30 19:58:05 +00009898 // Form the assignment:
9899 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9900 QualType BaseType = Base->getType().getUnqualifiedType();
9901 if (!BaseType->isRecordType()) {
9902 Invalid = true;
9903 continue;
9904 }
9905
9906 CXXCastPath BasePath;
9907 BasePath.push_back(Base);
9908
9909 // Construct the "from" expression, which is an implicit cast to the
9910 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009911 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009912
9913 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009914 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009915
9916 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009917 CastBuilder To(DerefThis,
9918 Context.getCVRQualifiedType(
9919 BaseType, MoveAssignOperator->getTypeQualifiers()),
9920 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009921
9922 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +00009923 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +00009924 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009925 /*CopyingBaseSubobject=*/true,
9926 /*Copying=*/false);
9927 if (Move.isInvalid()) {
9928 Diag(CurrentLocation, diag::note_member_synthesized_at)
9929 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9930 MoveAssignOperator->setInvalidDecl();
9931 return;
9932 }
9933
9934 // Success! Record the move.
9935 Statements.push_back(Move.takeAs<Expr>());
9936 }
9937
Sebastian Redl22653ba2011-08-30 19:58:05 +00009938 // Assign non-static members.
9939 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9940 FieldEnd = ClassDecl->field_end();
9941 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009942 if (Field->isUnnamedBitfield())
9943 continue;
9944
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009945 if (Field->isInvalidDecl()) {
9946 Invalid = true;
9947 continue;
9948 }
9949
Sebastian Redl22653ba2011-08-30 19:58:05 +00009950 // Check for members of reference type; we can't move those.
9951 if (Field->getType()->isReferenceType()) {
9952 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9953 << Context.getTagDeclType(ClassDecl) << 0 << 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 // Check for members of const-qualified, non-class type.
9962 QualType BaseType = Context.getBaseElementType(Field->getType());
9963 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9964 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9965 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9966 Diag(Field->getLocation(), diag::note_declared_at);
9967 Diag(CurrentLocation, diag::note_member_synthesized_at)
9968 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9969 Invalid = true;
9970 continue;
9971 }
9972
9973 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009974 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9975 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +00009976
9977 QualType FieldType = Field->getType().getNonReferenceType();
9978 if (FieldType->isIncompleteArrayType()) {
9979 assert(ClassDecl->hasFlexibleArrayMember() &&
9980 "Incomplete array type is not valid");
9981 continue;
9982 }
9983
9984 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +00009985 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9986 LookupMemberName);
David Blaikie40ed2972012-06-06 20:45:41 +00009987 MemberLookup.addDecl(*Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009988 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +00009989 MemberBuilder From(MoveOther, OtherRefType,
9990 /*IsArrow=*/false, MemberLookup);
9991 MemberBuilder To(This, getCurrentThisType(),
9992 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009993
Pavel Labath58934982013-08-30 08:52:28 +00009994 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +00009995 "Member reference with rvalue base must be rvalue except for reference "
9996 "members, which aren't allowed for move assignment.");
9997
Sebastian Redl22653ba2011-08-30 19:58:05 +00009998 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +00009999 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010000 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010001 /*CopyingBaseSubobject=*/false,
10002 /*Copying=*/false);
10003 if (Move.isInvalid()) {
10004 Diag(CurrentLocation, diag::note_member_synthesized_at)
10005 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10006 MoveAssignOperator->setInvalidDecl();
10007 return;
10008 }
Richard Smith11d19592012-11-12 23:33:00 +000010009
Sebastian Redl22653ba2011-08-30 19:58:05 +000010010 // Success! Record the copy.
10011 Statements.push_back(Move.takeAs<Stmt>());
10012 }
10013
10014 if (!Invalid) {
10015 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +000010016 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Sebastian Redl22653ba2011-08-30 19:58:05 +000010017
10018 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
10019 if (Return.isInvalid())
10020 Invalid = true;
10021 else {
10022 Statements.push_back(Return.takeAs<Stmt>());
10023
10024 if (Trap.hasErrorOccurred()) {
10025 Diag(CurrentLocation, diag::note_member_synthesized_at)
10026 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10027 Invalid = true;
10028 }
10029 }
10030 }
10031
10032 if (Invalid) {
10033 MoveAssignOperator->setInvalidDecl();
10034 return;
10035 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010036
10037 StmtResult Body;
10038 {
10039 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010040 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010041 /*isStmtExpr=*/false);
10042 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10043 }
Sebastian Redl22653ba2011-08-30 19:58:05 +000010044 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
10045
10046 if (ASTMutationListener *L = getASTMutationListener()) {
10047 L->CompletedImplicitDefinition(MoveAssignOperator);
10048 }
10049}
10050
Richard Smithd3b5c9082012-07-27 04:22:15 +000010051Sema::ImplicitExceptionSpecification
10052Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10053 CXXRecordDecl *ClassDecl = MD->getParent();
10054
10055 ImplicitExceptionSpecification ExceptSpec(*this);
10056 if (ClassDecl->isInvalidDecl())
10057 return ExceptSpec;
10058
10059 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000010060 assert(T->getNumParams() >= 1 && "not a copy ctor");
10061 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010062
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010063 // C++ [except.spec]p14:
10064 // An implicitly declared special member function (Clause 12) shall have an
10065 // exception-specification. [...]
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010066 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
10067 BaseEnd = ClassDecl->bases_end();
10068 Base != BaseEnd;
10069 ++Base) {
10070 // Virtual bases are handled below.
10071 if (Base->isVirtual())
10072 continue;
10073
Douglas Gregora6d69502010-07-02 23:41:54 +000010074 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010075 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010076 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010077 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithf623c962012-04-17 00:58:00 +000010078 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010079 }
10080 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
10081 BaseEnd = ClassDecl->vbases_end();
10082 Base != BaseEnd;
10083 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +000010084 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010085 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010086 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010087 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithf623c962012-04-17 00:58:00 +000010088 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010089 }
10090 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
10091 FieldEnd = ClassDecl->field_end();
10092 Field != FieldEnd;
10093 ++Field) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010094 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000010095 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10096 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000010097 LookupCopyingConstructor(FieldClassDecl,
10098 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000010099 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010100 }
10101 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010102
Richard Smithd3b5c9082012-07-27 04:22:15 +000010103 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000010104}
10105
10106CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10107 CXXRecordDecl *ClassDecl) {
10108 // C++ [class.copy]p4:
10109 // If the class definition does not explicitly declare a copy
10110 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000010111 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000010112
Richard Smith8bf22e52012-11-29 01:34:07 +000010113 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10114 if (DSM.isAlreadyBeingDeclared())
10115 return 0;
10116
Alexis Hunt913820d2011-05-13 06:10:58 +000010117 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10118 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000010119 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000010120 if (Const)
10121 ArgType = ArgType.withConst();
10122 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000010123
Richard Smithb5800092012-06-10 05:43:50 +000010124 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10125 CXXCopyConstructor,
10126 Const);
10127
Douglas Gregor54be3392010-07-01 17:57:27 +000010128 DeclarationName Name
10129 = Context.DeclarationNames.getCXXConstructorName(
10130 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010131 SourceLocation ClassLoc = ClassDecl->getLocation();
10132 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000010133
10134 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010135 // member of its class.
10136 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +000010137 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +000010138 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010139 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000010140 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000010141 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010142
Richard Smithd3b5c9082012-07-27 04:22:15 +000010143 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010144 FunctionProtoType::ExtProtoInfo EPI =
10145 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010146 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010147 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010148
Douglas Gregor54be3392010-07-01 17:57:27 +000010149 // Add the parameter to the constructor.
10150 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000010151 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +000010152 /*IdentifierInfo=*/0,
10153 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +000010154 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +000010155 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000010156
Richard Smith6b02d462012-12-08 08:32:28 +000010157 CopyConstructor->setTrivial(
10158 ClassDecl->needsOverloadResolutionForCopyConstructor()
10159 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10160 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000010161
Richard Smith852265f2012-03-30 20:53:28 +000010162 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +000010163 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010164
Richard Smith6b02d462012-12-08 08:32:28 +000010165 // Note that we have declared this constructor.
10166 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10167
10168 if (Scope *S = getScopeForContext(ClassDecl))
10169 PushOnScopeChains(CopyConstructor, S, false);
10170 ClassDecl->addDecl(CopyConstructor);
10171
Douglas Gregor54be3392010-07-01 17:57:27 +000010172 return CopyConstructor;
10173}
10174
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010175void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000010176 CXXConstructorDecl *CopyConstructor) {
10177 assert((CopyConstructor->isDefaulted() &&
10178 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010179 !CopyConstructor->doesThisDeclarationHaveABody() &&
10180 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010181 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010182
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000010183 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010184 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010185
Richard Smithd577fbb2013-06-13 03:23:42 +000010186 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000010187 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000010188 // deprecated if the class has a user-declared copy assignment operator
10189 // or a user-declared destructor.
10190 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10191 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10192
Eli Friedmaneaf34142012-10-18 20:14:08 +000010193 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010194 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010195
David Blaikie3fc2f912013-01-17 05:26:25 +000010196 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010197 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000010198 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000010199 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000010200 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000010201 } else {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010202 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010203 CopyConstructor->setBody(ActOnCompoundStmt(
10204 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
10205 /*isStmtExpr=*/ false).takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000010206 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010207
Eli Friedman276dd182013-09-05 00:02:25 +000010208 CopyConstructor->markUsed(Context);
Sebastian Redlab238a72011-04-24 16:28:06 +000010209 if (ASTMutationListener *L = getASTMutationListener()) {
10210 L->CompletedImplicitDefinition(CopyConstructor);
10211 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010212}
10213
Sebastian Redl22653ba2011-08-30 19:58:05 +000010214Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010215Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10216 CXXRecordDecl *ClassDecl = MD->getParent();
10217
Sebastian Redl22653ba2011-08-30 19:58:05 +000010218 // C++ [except.spec]p14:
10219 // An implicitly declared special member function (Clause 12) shall have an
10220 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000010221 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010222 if (ClassDecl->isInvalidDecl())
10223 return ExceptSpec;
10224
10225 // Direct base-class constructors.
10226 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
10227 BEnd = ClassDecl->bases_end();
10228 B != BEnd; ++B) {
10229 if (B->isVirtual()) // Handled below.
10230 continue;
10231
10232 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10233 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010234 CXXConstructorDecl *Constructor =
10235 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010236 // If this is a deleted function, add it anyway. This might be conformant
10237 // with the standard. This might not. I'm not sure. It might not matter.
10238 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010239 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010240 }
10241 }
10242
10243 // Virtual base-class constructors.
10244 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
10245 BEnd = ClassDecl->vbases_end();
10246 B != BEnd; ++B) {
10247 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10248 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010249 CXXConstructorDecl *Constructor =
10250 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010251 // If this is a deleted function, add it anyway. This might be conformant
10252 // with the standard. This might not. I'm not sure. It might not matter.
10253 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010254 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010255 }
10256 }
10257
10258 // Field constructors.
10259 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
10260 FEnd = ClassDecl->field_end();
10261 F != FEnd; ++F) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010262 QualType FieldType = Context.getBaseElementType(F->getType());
10263 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10264 CXXConstructorDecl *Constructor =
10265 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010266 // If this is a deleted function, add it anyway. This might be conformant
10267 // with the standard. This might not. I'm not sure. It might not matter.
10268 // In particular, the problem is that this function never gets called. It
10269 // might just be ill-formed because this function attempts to refer to
10270 // a deleted function here.
10271 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010272 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010273 }
10274 }
10275
10276 return ExceptSpec;
10277}
10278
10279CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10280 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010281 assert(ClassDecl->needsImplicitMoveConstructor());
10282
Richard Smith8bf22e52012-11-29 01:34:07 +000010283 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10284 if (DSM.isAlreadyBeingDeclared())
10285 return 0;
10286
Sebastian Redl22653ba2011-08-30 19:58:05 +000010287 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10288 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010289
Richard Smithb5800092012-06-10 05:43:50 +000010290 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10291 CXXMoveConstructor,
10292 false);
10293
Sebastian Redl22653ba2011-08-30 19:58:05 +000010294 DeclarationName Name
10295 = Context.DeclarationNames.getCXXConstructorName(
10296 Context.getCanonicalType(ClassType));
10297 SourceLocation ClassLoc = ClassDecl->getLocation();
10298 DeclarationNameInfo NameInfo(Name, ClassLoc);
10299
Richard Smith99005e62013-05-07 03:19:20 +000010300 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000010301 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010302 // member of its class.
10303 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithd3b5c9082012-07-27 04:22:15 +000010304 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smithcc36f692011-12-22 02:22:31 +000010305 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010306 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010307 MoveConstructor->setAccess(AS_public);
10308 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010309
Richard Smithd3b5c9082012-07-27 04:22:15 +000010310 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010311 FunctionProtoType::ExtProtoInfo EPI =
10312 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010313 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010314 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010315
Sebastian Redl22653ba2011-08-30 19:58:05 +000010316 // Add the parameter to the constructor.
10317 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10318 ClassLoc, ClassLoc,
10319 /*IdentifierInfo=*/0,
10320 ArgType, /*TInfo=*/0,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010321 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +000010322 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010323
Richard Smith6b02d462012-12-08 08:32:28 +000010324 MoveConstructor->setTrivial(
10325 ClassDecl->needsOverloadResolutionForMoveConstructor()
10326 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10327 : ClassDecl->hasTrivialMoveConstructor());
10328
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000010329 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010330 ClassDecl->setImplicitMoveConstructorIsDeleted();
10331 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010332 }
10333
10334 // Note that we have declared this constructor.
10335 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10336
10337 if (Scope *S = getScopeForContext(ClassDecl))
10338 PushOnScopeChains(MoveConstructor, S, false);
10339 ClassDecl->addDecl(MoveConstructor);
10340
10341 return MoveConstructor;
10342}
10343
10344void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10345 CXXConstructorDecl *MoveConstructor) {
10346 assert((MoveConstructor->isDefaulted() &&
10347 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010348 !MoveConstructor->doesThisDeclarationHaveABody() &&
10349 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010350 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10351
10352 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10353 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10354
Eli Friedmaneaf34142012-10-18 20:14:08 +000010355 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010356 DiagnosticErrorTrap Trap(Diags);
10357
David Blaikie3fc2f912013-01-17 05:26:25 +000010358 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000010359 Trap.hasErrorOccurred()) {
10360 Diag(CurrentLocation, diag::note_member_synthesized_at)
10361 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10362 MoveConstructor->setInvalidDecl();
10363 } else {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010364 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010365 MoveConstructor->setBody(ActOnCompoundStmt(
10366 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
10367 /*isStmtExpr=*/ false).takeAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010368 }
10369
Eli Friedman276dd182013-09-05 00:02:25 +000010370 MoveConstructor->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010371
10372 if (ASTMutationListener *L = getASTMutationListener()) {
10373 L->CompletedImplicitDefinition(MoveConstructor);
10374 }
10375}
10376
Douglas Gregor74f7d502012-02-15 19:33:52 +000010377bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000010378 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000010379}
Douglas Gregord3b672c2012-02-16 01:06:16 +000010380
10381void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000010382 SourceLocation CurrentLocation,
10383 CXXConversionDecl *Conv) {
10384 CXXRecordDecl *Lambda = Conv->getParent();
10385 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10386 // If we are defining a specialization of a conversion to function-ptr
10387 // cache the deduced template arguments for this specialization
10388 // so that we can use them to retrieve the corresponding call-operator
10389 // and static-invoker.
10390 const TemplateArgumentList *DeducedTemplateArgs = 0;
10391
Douglas Gregor355efbb2012-02-17 03:02:34 +000010392
Faisal Vali571df122013-09-29 08:45:24 +000010393 // Retrieve the corresponding call-operator specialization.
10394 if (Lambda->isGenericLambda()) {
10395 assert(Conv->isFunctionTemplateSpecialization());
10396 FunctionTemplateDecl *CallOpTemplate =
10397 CallOp->getDescribedFunctionTemplate();
10398 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
10399 void *InsertPos = 0;
10400 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10401 DeducedTemplateArgs->data(),
10402 DeducedTemplateArgs->size(),
10403 InsertPos);
10404 assert(CallOpSpec &&
10405 "Conversion operator must have a corresponding call operator");
10406 CallOp = cast<CXXMethodDecl>(CallOpSpec);
10407 }
10408 // Mark the call operator referenced (and add to pending instantiations
10409 // if necessary).
10410 // For both the conversion and static-invoker template specializations
10411 // we construct their body's in this function, so no need to add them
10412 // to the PendingInstantiations.
10413 MarkFunctionReferenced(CurrentLocation, CallOp);
10414
Eli Friedmaneaf34142012-10-18 20:14:08 +000010415 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010416 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000010417
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010418 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000010419 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10420 // ... and get the corresponding specialization for a generic lambda.
10421 if (Lambda->isGenericLambda()) {
10422 assert(DeducedTemplateArgs &&
10423 "Must have deduced template arguments from Conversion Operator");
10424 FunctionTemplateDecl *InvokeTemplate =
10425 Invoker->getDescribedFunctionTemplate();
10426 void *InsertPos = 0;
10427 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10428 DeducedTemplateArgs->data(),
10429 DeducedTemplateArgs->size(),
10430 InsertPos);
10431 assert(InvokeSpec &&
10432 "Must have a corresponding static invoker specialization");
10433 Invoker = cast<CXXMethodDecl>(InvokeSpec);
10434 }
10435 // Construct the body of the conversion function { return __invoke; }.
10436 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
10437 VK_LValue, Conv->getLocation()).take();
10438 assert(FunctionRef && "Can't refer to __invoke function?");
10439 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
10440 Conv->setBody(new (Context) CompoundStmt(Context, Return,
10441 Conv->getLocation(),
10442 Conv->getLocation()));
10443
10444 Conv->markUsed(Context);
10445 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010446
Faisal Vali571df122013-09-29 08:45:24 +000010447 // Fill in the __invoke function with a dummy implementation. IR generation
10448 // will fill in the actual details.
10449 Invoker->markUsed(Context);
10450 Invoker->setReferenced();
10451 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10452
Douglas Gregord3b672c2012-02-16 01:06:16 +000010453 if (ASTMutationListener *L = getASTMutationListener()) {
10454 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000010455 L->CompletedImplicitDefinition(Invoker);
10456 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000010457}
10458
Faisal Vali571df122013-09-29 08:45:24 +000010459
10460
Douglas Gregord3b672c2012-02-16 01:06:16 +000010461void Sema::DefineImplicitLambdaToBlockPointerConversion(
10462 SourceLocation CurrentLocation,
10463 CXXConversionDecl *Conv)
10464{
Faisal Vali850da1a2013-09-29 17:08:32 +000010465 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000010466
Eli Friedman276dd182013-09-05 00:02:25 +000010467 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010468
Eli Friedmaneaf34142012-10-18 20:14:08 +000010469 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010470 DiagnosticErrorTrap Trap(Diags);
10471
Douglas Gregored90df32012-02-22 05:02:47 +000010472 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010473 Expr *This = ActOnCXXThis(CurrentLocation).take();
10474 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010475
Eli Friedman98b01ed2012-03-01 04:01:32 +000010476 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10477 Conv->getLocation(),
10478 Conv, DerefThis);
10479
10480 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10481 // behavior. Note that only the general conversion function does this
10482 // (since it's unusable otherwise); in the case where we inline the
10483 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010484 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000010485 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10486 CK_CopyAndAutoreleaseBlockObject,
10487 BuildBlock.get(), 0, VK_RValue);
10488
10489 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000010490 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000010491 Conv->setInvalidDecl();
10492 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000010493 }
Douglas Gregored90df32012-02-22 05:02:47 +000010494
Douglas Gregored90df32012-02-22 05:02:47 +000010495 // Create the return statement that returns the block from the conversion
10496 // function.
Eli Friedman98b01ed2012-03-01 04:01:32 +000010497 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000010498 if (Return.isInvalid()) {
10499 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10500 Conv->setInvalidDecl();
10501 return;
10502 }
10503
10504 // Set the body of the conversion function.
10505 Stmt *ReturnS = Return.take();
Nico Webera2a0eb92012-12-29 20:03:39 +000010506 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000010507 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000010508 Conv->getLocation()));
10509
Douglas Gregored90df32012-02-22 05:02:47 +000010510 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010511 if (ASTMutationListener *L = getASTMutationListener()) {
10512 L->CompletedImplicitDefinition(Conv);
10513 }
10514}
10515
Douglas Gregord2f70072012-03-10 06:53:13 +000010516/// \brief Determine whether the given list arguments contains exactly one
10517/// "real" (non-default) argument.
10518static bool hasOneRealArgument(MultiExprArg Args) {
10519 switch (Args.size()) {
10520 case 0:
10521 return false;
10522
10523 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010524 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000010525 return false;
10526
10527 // fall through
10528 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010529 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000010530 }
10531
10532 return false;
10533}
10534
John McCalldadc5752010-08-24 06:29:42 +000010535ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010536Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +000010537 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010538 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010539 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010540 bool IsListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010541 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010542 unsigned ConstructKind,
10543 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000010544 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000010545
Douglas Gregor45cf7e32010-04-02 18:24:57 +000010546 // C++0x [class.copy]p34:
10547 // When certain criteria are met, an implementation is allowed to
10548 // omit the copy/move construction of a class object, even if the
10549 // copy/move constructor and/or destructor for the object have
10550 // side effects. [...]
10551 // - when a temporary class object that has not been bound to a
10552 // reference (12.2) would be copied/moved to a class object
10553 // with the same cv-unqualified type, the copy/move operation
10554 // can be omitted by constructing the temporary object
10555 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +000010556 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregord2f70072012-03-10 06:53:13 +000010557 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010558 Expr *SubExpr = ExprArgs[0];
John McCall7a626f62010-09-15 10:14:12 +000010559 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +000010560 }
Mike Stump11289f42009-09-09 15:08:12 +000010561
10562 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010563 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010564 IsListInitialization, RequiresZeroInit,
10565 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000010566}
10567
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010568/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10569/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +000010570ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010571Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10572 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010573 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010574 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010575 bool IsListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010576 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010577 unsigned ConstructKind,
10578 SourceRange ParenRange) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010579 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +000010580 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010581 Constructor, Elidable, ExprArgs,
Richard Smithd59b8322012-12-19 01:39:02 +000010582 HadMultipleCandidates,
10583 IsListInitialization, RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010584 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10585 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010586}
10587
John McCall03c48482010-02-02 09:10:11 +000010588void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000010589 if (VD->isInvalidDecl()) return;
10590
John McCall03c48482010-02-02 09:10:11 +000010591 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000010592 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000010593 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000010594 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000010595
Chandler Carruth86d17d32011-03-27 21:26:48 +000010596 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010597 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000010598 CheckDestructorAccess(VD->getLocation(), Destructor,
10599 PDiag(diag::err_access_dtor_var)
10600 << VD->getDeclName()
10601 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000010602 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000010603
Chandler Carruth86d17d32011-03-27 21:26:48 +000010604 if (!VD->hasGlobalStorage()) return;
10605
10606 // Emit warning for non-trivial dtor in global scope (a real global,
10607 // class-static, function-static).
10608 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10609
10610 // TODO: this should be re-enabled for static locals by !CXAAtExit
10611 if (!VD->isStaticLocal())
10612 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010613}
10614
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010615/// \brief Given a constructor and the set of arguments provided for the
10616/// constructor, convert the arguments and add any required default arguments
10617/// to form a proper call to this constructor.
10618///
10619/// \returns true if an error occurred, false otherwise.
10620bool
10621Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10622 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000010623 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000010624 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010625 bool AllowExplicit,
10626 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010627 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10628 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010629 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010630
10631 const FunctionProtoType *Proto
10632 = Constructor->getType()->getAs<FunctionProtoType>();
10633 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010634 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000010635
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010636 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010637 if (NumArgs < NumParams)
10638 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010639 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010640 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010641
10642 VariadicCallType CallType =
10643 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010644 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010645 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010646 Proto, 0,
10647 llvm::makeArrayRef(Args, NumArgs),
10648 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010649 CallType, AllowExplicit,
10650 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000010651 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000010652
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010653 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010654
Dmitri Gribenko765396f2013-01-13 20:46:02 +000010655 CheckConstructorCall(Constructor,
10656 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10657 AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000010658 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010659
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010660 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000010661}
10662
Anders Carlssone363c8e2009-12-12 00:32:00 +000010663static inline bool
10664CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10665 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000010666 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000010667 if (isa<NamespaceDecl>(DC)) {
10668 return SemaRef.Diag(FnDecl->getLocation(),
10669 diag::err_operator_new_delete_declared_in_namespace)
10670 << FnDecl->getDeclName();
10671 }
10672
10673 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000010674 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010675 return SemaRef.Diag(FnDecl->getLocation(),
10676 diag::err_operator_new_delete_declared_static)
10677 << FnDecl->getDeclName();
10678 }
10679
Anders Carlsson60659a82009-12-12 02:43:16 +000010680 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000010681}
10682
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010683static inline bool
10684CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10685 CanQualType ExpectedResultType,
10686 CanQualType ExpectedFirstParamType,
10687 unsigned DependentParamTypeDiag,
10688 unsigned InvalidParamTypeDiag) {
10689 QualType ResultType =
10690 FnDecl->getType()->getAs<FunctionType>()->getResultType();
10691
10692 // Check that the result type is not dependent.
10693 if (ResultType->isDependentType())
10694 return SemaRef.Diag(FnDecl->getLocation(),
10695 diag::err_operator_new_delete_dependent_result_type)
10696 << FnDecl->getDeclName() << ExpectedResultType;
10697
10698 // Check that the result type is what we expect.
10699 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10700 return SemaRef.Diag(FnDecl->getLocation(),
10701 diag::err_operator_new_delete_invalid_result_type)
10702 << FnDecl->getDeclName() << ExpectedResultType;
10703
10704 // A function template must have at least 2 parameters.
10705 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10706 return SemaRef.Diag(FnDecl->getLocation(),
10707 diag::err_operator_new_delete_template_too_few_parameters)
10708 << FnDecl->getDeclName();
10709
10710 // The function decl must have at least 1 parameter.
10711 if (FnDecl->getNumParams() == 0)
10712 return SemaRef.Diag(FnDecl->getLocation(),
10713 diag::err_operator_new_delete_too_few_parameters)
10714 << FnDecl->getDeclName();
10715
Sylvestre Ledru830885c2012-07-23 08:59:39 +000010716 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010717 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10718 if (FirstParamType->isDependentType())
10719 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10720 << FnDecl->getDeclName() << ExpectedFirstParamType;
10721
10722 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000010723 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010724 ExpectedFirstParamType)
10725 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10726 << FnDecl->getDeclName() << ExpectedFirstParamType;
10727
10728 return false;
10729}
10730
Anders Carlsson12308f42009-12-11 23:23:22 +000010731static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010732CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010733 // C++ [basic.stc.dynamic.allocation]p1:
10734 // A program is ill-formed if an allocation function is declared in a
10735 // namespace scope other than global scope or declared static in global
10736 // scope.
10737 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10738 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010739
10740 CanQualType SizeTy =
10741 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10742
10743 // C++ [basic.stc.dynamic.allocation]p1:
10744 // The return type shall be void*. The first parameter shall have type
10745 // std::size_t.
10746 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10747 SizeTy,
10748 diag::err_operator_new_dependent_param_type,
10749 diag::err_operator_new_param_type))
10750 return true;
10751
10752 // C++ [basic.stc.dynamic.allocation]p1:
10753 // The first parameter shall not have an associated default argument.
10754 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000010755 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010756 diag::err_operator_new_default_arg)
10757 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10758
10759 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000010760}
10761
10762static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000010763CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000010764 // C++ [basic.stc.dynamic.deallocation]p1:
10765 // A program is ill-formed if deallocation functions are declared in a
10766 // namespace scope other than global scope or declared static in global
10767 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000010768 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10769 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010770
10771 // C++ [basic.stc.dynamic.deallocation]p2:
10772 // Each deallocation function shall return void and its first parameter
10773 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010774 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10775 SemaRef.Context.VoidPtrTy,
10776 diag::err_operator_delete_dependent_param_type,
10777 diag::err_operator_delete_param_type))
10778 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010779
Anders Carlsson12308f42009-12-11 23:23:22 +000010780 return false;
10781}
10782
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010783/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10784/// of this overloaded operator is well-formed. If so, returns false;
10785/// otherwise, emits appropriate diagnostics and returns true.
10786bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000010787 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010788 "Expected an overloaded operator declaration");
10789
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010790 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10791
Mike Stump11289f42009-09-09 15:08:12 +000010792 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010793 // The allocation and deallocation functions, operator new,
10794 // operator new[], operator delete and operator delete[], are
10795 // described completely in 3.7.3. The attributes and restrictions
10796 // found in the rest of this subclause do not apply to them unless
10797 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000010798 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000010799 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000010800
Anders Carlsson22f443f2009-12-12 00:26:23 +000010801 if (Op == OO_New || Op == OO_Array_New)
10802 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010803
10804 // C++ [over.oper]p6:
10805 // An operator function shall either be a non-static member
10806 // function or be a non-member function and have at least one
10807 // parameter whose type is a class, a reference to a class, an
10808 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000010809 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10810 if (MethodDecl->isStatic())
10811 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010812 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010813 } else {
10814 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +000010815 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10816 ParamEnd = FnDecl->param_end();
10817 Param != ParamEnd; ++Param) {
10818 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000010819 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10820 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010821 ClassOrEnumParam = true;
10822 break;
10823 }
10824 }
10825
Douglas Gregord69246b2008-11-17 16:14:12 +000010826 if (!ClassOrEnumParam)
10827 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000010828 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010829 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010830 }
10831
10832 // C++ [over.oper]p8:
10833 // An operator function cannot have default arguments (8.3.6),
10834 // except where explicitly stated below.
10835 //
Mike Stump11289f42009-09-09 15:08:12 +000010836 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010837 // (C++ [over.call]p1).
10838 if (Op != OO_Call) {
10839 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10840 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010841 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +000010842 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000010843 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010844 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010845 }
10846 }
10847
Douglas Gregor6cf08062008-11-10 13:38:07 +000010848 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10849 { false, false, false }
10850#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10851 , { Unary, Binary, MemberOnly }
10852#include "clang/Basic/OperatorKinds.def"
10853 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010854
Douglas Gregor6cf08062008-11-10 13:38:07 +000010855 bool CanBeUnaryOperator = OperatorUses[Op][0];
10856 bool CanBeBinaryOperator = OperatorUses[Op][1];
10857 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010858
10859 // C++ [over.oper]p8:
10860 // [...] Operator functions cannot have more or fewer parameters
10861 // than the number required for the corresponding operator, as
10862 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000010863 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000010864 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010865 if (Op != OO_Call &&
10866 ((NumParams == 1 && !CanBeUnaryOperator) ||
10867 (NumParams == 2 && !CanBeBinaryOperator) ||
10868 (NumParams < 1) || (NumParams > 2))) {
10869 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010870 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000010871 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010872 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000010873 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010874 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000010875 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000010876 assert(CanBeBinaryOperator &&
10877 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010878 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000010879 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010880
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000010881 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010882 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010883 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000010884
Douglas Gregord69246b2008-11-17 16:14:12 +000010885 // Overloaded operators other than operator() cannot be variadic.
10886 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000010887 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000010888 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010889 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010890 }
10891
10892 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000010893 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10894 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000010895 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000010896 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010897 }
10898
10899 // C++ [over.inc]p1:
10900 // The user-defined function called operator++ implements the
10901 // prefix and postfix ++ operator. If this function is a member
10902 // function with no parameters, or a non-member function with one
10903 // parameter of class or enumeration type, it defines the prefix
10904 // increment operator ++ for objects of that type. If the function
10905 // is a member function with one parameter (which shall be of type
10906 // int) or a non-member function with two parameters (the second
10907 // of which shall be of type int), it defines the postfix
10908 // increment operator ++ for objects of that type.
10909 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10910 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10911 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +000010912 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010913 ParamIsInt = BT->getKind() == BuiltinType::Int;
10914
Chris Lattner2b786902008-11-21 07:50:02 +000010915 if (!ParamIsInt)
10916 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000010917 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000010918 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010919 }
10920
Douglas Gregord69246b2008-11-17 16:14:12 +000010921 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010922}
Chris Lattner3b024a32008-12-17 07:09:26 +000010923
Alexis Huntc88db062010-01-13 09:01:02 +000010924/// CheckLiteralOperatorDeclaration - Check whether the declaration
10925/// of this literal operator function is well-formed. If so, returns
10926/// false; otherwise, emits appropriate diagnostics and returns true.
10927bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000010928 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000010929 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10930 << FnDecl->getDeclName();
10931 return true;
10932 }
10933
Richard Smith72eebee2012-03-04 09:41:16 +000010934 if (FnDecl->isExternC()) {
10935 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10936 return true;
10937 }
10938
Alexis Huntc88db062010-01-13 09:01:02 +000010939 bool Valid = false;
10940
Richard Smithbcc22fc2012-03-09 08:00:36 +000010941 // This might be the definition of a literal operator template.
10942 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10943 // This might be a specialization of a literal operator template.
10944 if (!TpDecl)
10945 TpDecl = FnDecl->getPrimaryTemplate();
10946
Richard Smithb8b41d32013-10-07 19:57:58 +000010947 // template <char...> type operator "" name() and
10948 // template <class T, T...> type operator "" name() are the only valid
10949 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000010950 if (TpDecl) {
Richard Smith72eebee2012-03-04 09:41:16 +000010951 if (FnDecl->param_size() == 0) {
Richard Smithb8b41d32013-10-07 19:57:58 +000010952 // Must have one or two template parameters
Alexis Hunt7dd26172010-04-07 23:11:06 +000010953 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10954 if (Params->size() == 1) {
10955 NonTypeTemplateParmDecl *PmDecl =
Richard Smithed943022012-08-03 21:14:57 +000010956 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +000010957
Alexis Hunt7dd26172010-04-07 23:11:06 +000010958 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +000010959 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10960 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10961 Valid = true;
Richard Smithb8b41d32013-10-07 19:57:58 +000010962 } else if (Params->size() == 2) {
10963 TemplateTypeParmDecl *PmType =
10964 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
10965 NonTypeTemplateParmDecl *PmArgs =
10966 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
10967
10968 // The second template parameter must be a parameter pack with the
10969 // first template parameter as its type.
10970 if (PmType && PmArgs &&
10971 !PmType->isTemplateParameterPack() &&
10972 PmArgs->isTemplateParameterPack()) {
10973 const TemplateTypeParmType *TArgs =
10974 PmArgs->getType()->getAs<TemplateTypeParmType>();
10975 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
10976 TArgs->getIndex() == PmType->getIndex()) {
10977 Valid = true;
10978 if (ActiveTemplateInstantiations.empty())
10979 Diag(FnDecl->getLocation(),
10980 diag::ext_string_literal_operator_template);
10981 }
10982 }
Alexis Hunt7dd26172010-04-07 23:11:06 +000010983 }
10984 }
Richard Smith72eebee2012-03-04 09:41:16 +000010985 } else if (FnDecl->param_size()) {
Alexis Huntc88db062010-01-13 09:01:02 +000010986 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +000010987 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10988
Richard Smith72eebee2012-03-04 09:41:16 +000010989 QualType T = (*Param)->getType().getUnqualifiedType();
Alexis Huntc88db062010-01-13 09:01:02 +000010990
Alexis Hunt079a6f72010-04-07 22:57:35 +000010991 // unsigned long long int, long double, and any character type are allowed
10992 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +000010993 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10994 Context.hasSameType(T, Context.LongDoubleTy) ||
10995 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000010996 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000010997 Context.hasSameType(T, Context.Char16Ty) ||
10998 Context.hasSameType(T, Context.Char32Ty)) {
10999 if (++Param == FnDecl->param_end())
11000 Valid = true;
11001 goto FinishedParams;
11002 }
11003
Alexis Hunt079a6f72010-04-07 22:57:35 +000011004 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +000011005 const PointerType *PT = T->getAs<PointerType>();
11006 if (!PT)
11007 goto FinishedParams;
11008 T = PT->getPointeeType();
Richard Smith72eebee2012-03-04 09:41:16 +000011009 if (!T.isConstQualified() || T.isVolatileQualified())
Alexis Huntc88db062010-01-13 09:01:02 +000011010 goto FinishedParams;
11011 T = T.getUnqualifiedType();
11012
11013 // Move on to the second parameter;
11014 ++Param;
11015
11016 // If there is no second parameter, the first must be a const char *
11017 if (Param == FnDecl->param_end()) {
11018 if (Context.hasSameType(T, Context.CharTy))
11019 Valid = true;
11020 goto FinishedParams;
11021 }
11022
11023 // const char *, const wchar_t*, const char16_t*, and const char32_t*
11024 // are allowed as the first parameter to a two-parameter function
11025 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011026 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011027 Context.hasSameType(T, Context.Char16Ty) ||
11028 Context.hasSameType(T, Context.Char32Ty)))
11029 goto FinishedParams;
11030
11031 // The second and final parameter must be an std::size_t
11032 T = (*Param)->getType().getUnqualifiedType();
11033 if (Context.hasSameType(T, Context.getSizeType()) &&
11034 ++Param == FnDecl->param_end())
11035 Valid = true;
11036 }
11037
11038 // FIXME: This diagnostic is absolutely terrible.
11039FinishedParams:
11040 if (!Valid) {
11041 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11042 << FnDecl->getDeclName();
11043 return true;
11044 }
11045
Richard Smith768cecc2012-03-09 08:16:22 +000011046 // A parameter-declaration-clause containing a default argument is not
11047 // equivalent to any of the permitted forms.
11048 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
11049 ParamEnd = FnDecl->param_end();
11050 Param != ParamEnd; ++Param) {
11051 if ((*Param)->hasDefaultArg()) {
11052 Diag((*Param)->getDefaultArgRange().getBegin(),
11053 diag::err_literal_operator_default_argument)
11054 << (*Param)->getDefaultArgRange();
11055 break;
11056 }
11057 }
11058
Richard Smith0df56f42012-03-08 02:39:21 +000011059 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000011060 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11061 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000011062 // C++11 [usrlit.suffix]p1:
11063 // Literal suffix identifiers that do not start with an underscore
11064 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000011065 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11066 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000011067 }
Richard Smith0df56f42012-03-08 02:39:21 +000011068
Alexis Huntc88db062010-01-13 09:01:02 +000011069 return false;
11070}
11071
Douglas Gregor07665a62009-01-05 19:45:36 +000011072/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11073/// linkage specification, including the language and (if present)
11074/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
11075/// the location of the language string literal, which is provided
11076/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
11077/// the '{' brace. Otherwise, this linkage specification does not
11078/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000011079Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
11080 SourceLocation LangLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011081 StringRef Lang,
Chris Lattner8ea64422010-11-09 20:15:55 +000011082 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +000011083 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +000011084 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +000011085 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +000011086 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +000011087 Language = LinkageSpecDecl::lang_cxx;
11088 else {
Douglas Gregor07665a62009-01-05 19:45:36 +000011089 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +000011090 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +000011091 }
Mike Stump11289f42009-09-09 15:08:12 +000011092
Chris Lattner438e5012008-12-17 07:13:27 +000011093 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000011094
Douglas Gregor07665a62009-01-05 19:45:36 +000011095 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Rafael Espindola327be3c2013-04-26 01:30:23 +000011096 ExternLoc, LangLoc, Language,
11097 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011098 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000011099 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000011100 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000011101}
11102
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000011103/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000011104/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11105/// valid, it's the position of the closing '}' brace in a linkage
11106/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000011107Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011108 Decl *LinkageSpec,
11109 SourceLocation RBraceLoc) {
11110 if (LinkageSpec) {
11111 if (RBraceLoc.isValid()) {
11112 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11113 LSDecl->setRBraceLoc(RBraceLoc);
11114 }
Douglas Gregor07665a62009-01-05 19:45:36 +000011115 PopDeclContext();
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011116 }
Douglas Gregor07665a62009-01-05 19:45:36 +000011117 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000011118}
11119
Michael Han84324352013-02-22 17:15:32 +000011120Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11121 AttributeList *AttrList,
11122 SourceLocation SemiLoc) {
11123 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11124 // Attribute declarations appertain to empty declaration so we handle
11125 // them here.
11126 if (AttrList)
11127 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000011128
Michael Han84324352013-02-22 17:15:32 +000011129 CurContext->addDecl(ED);
11130 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000011131}
11132
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011133/// \brief Perform semantic analysis for the variable declaration that
11134/// occurs within a C++ catch clause, returning the newly-created
11135/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011136VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000011137 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011138 SourceLocation StartLoc,
11139 SourceLocation Loc,
11140 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011141 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011142 QualType ExDeclType = TInfo->getType();
11143
Sebastian Redl54c04d42008-12-22 19:15:10 +000011144 // Arrays and functions decay.
11145 if (ExDeclType->isArrayType())
11146 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11147 else if (ExDeclType->isFunctionType())
11148 ExDeclType = Context.getPointerType(ExDeclType);
11149
11150 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11151 // The exception-declaration shall not denote a pointer or reference to an
11152 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000011153 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000011154 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011155 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000011156 Invalid = true;
11157 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011158
Sebastian Redl54c04d42008-12-22 19:15:10 +000011159 QualType BaseType = ExDeclType;
11160 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000011161 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011162 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011163 BaseType = Ptr->getPointeeType();
11164 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011165 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000011166 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000011167 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011168 BaseType = Ref->getPointeeType();
11169 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011170 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011171 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000011172 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011173 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000011174 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011175
Mike Stump11289f42009-09-09 15:08:12 +000011176 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011177 RequireNonAbstractType(Loc, ExDeclType,
11178 diag::err_abstract_type_in_decl,
11179 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000011180 Invalid = true;
11181
John McCall2ca705e2010-07-24 00:37:23 +000011182 // Only the non-fragile NeXT runtime currently supports C++ catches
11183 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011184 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000011185 QualType T = ExDeclType;
11186 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11187 T = RT->getPointeeType();
11188
11189 if (T->isObjCObjectType()) {
11190 Diag(Loc, diag::err_objc_object_catch);
11191 Invalid = true;
11192 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000011193 // FIXME: should this be a test for macosx-fragile specifically?
11194 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000011195 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000011196 }
11197 }
11198
Abramo Bagnaradff19302011-03-08 08:55:46 +000011199 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000011200 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000011201 ExDecl->setExceptionVariable(true);
11202
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011203 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011204 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011205 Invalid = true;
11206
Douglas Gregor750734c2011-07-06 18:14:43 +000011207 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000011208 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000011209 // Insulate this from anything else we might currently be parsing.
11210 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11211
Douglas Gregor6de584c2010-03-05 23:38:39 +000011212 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000011213 // The object declared in an exception-declaration or, if the
11214 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000011215 // copy-initialized (8.5) from the exception object. [...]
11216 // The object is destroyed when the handler exits, after the destruction
11217 // of any automatic objects initialized within the handler.
11218 //
Nick Lewycky0f292892013-09-22 10:06:57 +000011219 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000011220 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +000011221 QualType initType = ExDeclType;
11222
11223 InitializedEntity entity =
11224 InitializedEntity::InitializeVariable(ExDecl);
11225 InitializationKind initKind =
11226 InitializationKind::CreateCopy(Loc, SourceLocation());
11227
11228 Expr *opaqueValue =
11229 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000011230 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11231 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000011232 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000011233 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000011234 else {
11235 // If the constructor used was non-trivial, set this as the
11236 // "initializer".
Nick Lewycky0f292892013-09-22 10:06:57 +000011237 CXXConstructExpr *construct = result.takeAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000011238 if (!construct->getConstructor()->isTrivial()) {
11239 Expr *init = MaybeCreateExprWithCleanups(construct);
11240 ExDecl->setInit(init);
11241 }
11242
11243 // And make sure it's destructable.
11244 FinalizeVarWithDestructor(ExDecl, recordType);
11245 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000011246 }
11247 }
11248
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011249 if (Invalid)
11250 ExDecl->setInvalidDecl();
11251
11252 return ExDecl;
11253}
11254
11255/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11256/// handler.
John McCall48871652010-08-21 09:40:31 +000011257Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000011258 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000011259 bool Invalid = D.isInvalidType();
11260
11261 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000011262 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11263 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000011264 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11265 D.getIdentifierLoc());
11266 Invalid = true;
11267 }
11268
Sebastian Redl54c04d42008-12-22 19:15:10 +000011269 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011270 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000011271 LookupOrdinaryName,
11272 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011273 // The scope should be freshly made just for us. There is just no way
11274 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +000011275 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +000011276 if (PrevDecl->isTemplateParameter()) {
11277 // Maybe we will complain about the shadowed template parameter.
11278 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorf4ef4d22011-10-20 17:58:49 +000011279 PrevDecl = 0;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011280 }
11281 }
11282
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011283 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011284 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11285 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011286 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011287 }
11288
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011289 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011290 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011291 D.getIdentifierLoc(),
11292 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011293 if (Invalid)
11294 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000011295
Sebastian Redl54c04d42008-12-22 19:15:10 +000011296 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011297 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011298 PushOnScopeChains(ExDecl, S);
11299 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011300 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011301
Douglas Gregor758a8692009-06-17 21:51:59 +000011302 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000011303 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011304}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011305
Abramo Bagnaraea947882011-03-08 16:41:52 +000011306Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000011307 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000011308 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000011309 SourceLocation RParenLoc) {
Richard Smithded9c2e2012-07-11 22:37:56 +000011310 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011311
Richard Smithded9c2e2012-07-11 22:37:56 +000011312 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11313 return 0;
11314
11315 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11316 AssertMessage, RParenLoc, false);
11317}
11318
11319Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11320 Expr *AssertExpr,
11321 StringLiteral *AssertMessage,
11322 SourceLocation RParenLoc,
11323 bool Failed) {
11324 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11325 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000011326 // In a static_assert-declaration, the constant-expression shall be a
11327 // constant expression that can be contextually converted to bool.
11328 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11329 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011330 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000011331
Richard Smith902ca212011-12-14 23:32:26 +000011332 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000011333 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000011334 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000011335 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011336 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011337
Richard Smithded9c2e2012-07-11 22:37:56 +000011338 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011339 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000011340 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith235341b2012-08-16 03:56:14 +000011341 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000011342 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smithf506eaf2012-03-05 23:20:05 +000011343 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000011344 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000011345 }
Anders Carlsson54b26982009-03-14 00:33:21 +000011346 }
Mike Stump11289f42009-09-09 15:08:12 +000011347
Abramo Bagnaraea947882011-03-08 16:41:52 +000011348 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000011349 AssertExpr, AssertMessage, RParenLoc,
11350 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000011351
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011352 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000011353 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011354}
Sebastian Redlf769df52009-03-24 22:27:57 +000011355
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011356/// \brief Perform semantic analysis of the given friend type declaration.
11357///
11358/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000011359FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000011360 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011361 TypeSourceInfo *TSInfo) {
11362 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11363
11364 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000011365 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011366
Richard Smithc8239732011-10-18 21:39:00 +000011367 // C++03 [class.friend]p2:
11368 // An elaborated-type-specifier shall be used in a friend declaration
11369 // for a class.*
11370 //
11371 // * The class-key of the elaborated-type-specifier is required.
11372 if (!ActiveTemplateInstantiations.empty()) {
11373 // Do not complain about the form of friend template types during
11374 // template instantiation; we will already have complained when the
11375 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000011376 } else {
11377 if (!T->isElaboratedTypeSpecifier()) {
11378 // If we evaluated the type to a record type, suggest putting
11379 // a tag in front.
11380 if (const RecordType *RT = T->getAs<RecordType>()) {
11381 RecordDecl *RD = RT->getDecl();
Richard Smithc8239732011-10-18 21:39:00 +000011382
Nick Lewycky36722d22013-02-06 05:59:33 +000011383 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smithc8239732011-10-18 21:39:00 +000011384
Nick Lewycky36722d22013-02-06 05:59:33 +000011385 Diag(TypeRange.getBegin(),
11386 getLangOpts().CPlusPlus11 ?
11387 diag::warn_cxx98_compat_unelaborated_friend_type :
11388 diag::ext_unelaborated_friend_type)
11389 << (unsigned) RD->getTagKind()
11390 << T
11391 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11392 InsertionText);
11393 } else {
11394 Diag(FriendLoc,
11395 getLangOpts().CPlusPlus11 ?
11396 diag::warn_cxx98_compat_nonclass_type_friend :
11397 diag::ext_nonclass_type_friend)
11398 << T
11399 << TypeRange;
11400 }
11401 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000011402 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011403 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000011404 diag::warn_cxx98_compat_enum_friend :
11405 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011406 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000011407 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011408 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011409
Nick Lewycky36722d22013-02-06 05:59:33 +000011410 // C++11 [class.friend]p3:
11411 // A friend declaration that does not declare a function shall have one
11412 // of the following forms:
11413 // friend elaborated-type-specifier ;
11414 // friend simple-type-specifier ;
11415 // friend typename-specifier ;
11416 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11417 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11418 }
Richard Smitha31a89a2012-09-20 01:31:00 +000011419
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011420 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000011421 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011422 // the friend declaration is ignored.
Richard Smitha31a89a2012-09-20 01:31:00 +000011423 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011424}
11425
John McCallace48cd2010-10-19 01:40:49 +000011426/// Handle a friend tag declaration where the scope specifier was
11427/// templated.
11428Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11429 unsigned TagSpec, SourceLocation TagLoc,
11430 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011431 IdentifierInfo *Name,
11432 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000011433 AttributeList *Attr,
11434 MultiTemplateParamsArg TempParamLists) {
11435 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11436
11437 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000011438 bool Invalid = false;
11439
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011440 if (TemplateParameterList *TemplateParams =
11441 MatchTemplateParametersToScopeSpecifier(
11442 TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true,
11443 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000011444 if (TemplateParams->size() > 0) {
11445 // This is a declaration of a class template.
11446 if (Invalid)
11447 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000011448
Eric Christopher6f228b52011-07-21 05:34:24 +000011449 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11450 SS, Name, NameLoc, Attr,
11451 TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000011452 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher6f228b52011-07-21 05:34:24 +000011453 TempParamLists.size() - 1,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011454 TempParamLists.data()).take();
John McCallace48cd2010-10-19 01:40:49 +000011455 } else {
11456 // The "template<>" header is extraneous.
11457 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11458 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11459 isExplicitSpecialization = true;
11460 }
11461 }
11462
11463 if (Invalid) return 0;
11464
John McCallace48cd2010-10-19 01:40:49 +000011465 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000011466 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011467 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000011468 isAllExplicitSpecializations = false;
11469 break;
11470 }
11471 }
11472
11473 // FIXME: don't ignore attributes.
11474
11475 // If it's explicit specializations all the way down, just forget
11476 // about the template header and build an appropriate non-templated
11477 // friend. TODO: for source fidelity, remember the headers.
11478 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011479 if (SS.isEmpty()) {
11480 bool Owned = false;
11481 bool IsDependent = false;
11482 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000011483 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011484 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000011485 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000011486 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011487 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000011488 /*UnderlyingType=*/TypeResult(),
11489 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011490 }
Richard Smith649c7b062014-01-08 00:56:48 +000011491
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011492 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000011493 ElaboratedTypeKeyword Keyword
11494 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011495 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000011496 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011497 if (T.isNull())
11498 return 0;
11499
11500 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11501 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000011502 DependentNameTypeLoc TL =
11503 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011504 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011505 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000011506 TL.setNameLoc(NameLoc);
11507 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000011508 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011509 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000011510 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000011511 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011512 }
11513
11514 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011515 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011516 Friend->setAccess(AS_public);
11517 CurContext->addDecl(Friend);
11518 return Friend;
11519 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011520
11521 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11522
11523
John McCallace48cd2010-10-19 01:40:49 +000011524
11525 // Handle the case of a templated-scope friend class. e.g.
11526 // template <class T> class A<T>::B;
11527 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000011528 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
11529 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000011530 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11531 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11532 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000011533 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011534 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011535 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000011536 TL.setNameLoc(NameLoc);
11537
11538 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011539 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011540 Friend->setAccess(AS_public);
11541 Friend->setUnsupportedFriend(true);
11542 CurContext->addDecl(Friend);
11543 return Friend;
11544}
11545
11546
John McCall11083da2009-09-16 22:47:08 +000011547/// Handle a friend type declaration. This works in tandem with
11548/// ActOnTag.
11549///
11550/// Notes on friend class templates:
11551///
11552/// We generally treat friend class declarations as if they were
11553/// declaring a class. So, for example, the elaborated type specifier
11554/// in a friend declaration is required to obey the restrictions of a
11555/// class-head (i.e. no typedefs in the scope chain), template
11556/// parameters are required to match up with simple template-ids, &c.
11557/// However, unlike when declaring a template specialization, it's
11558/// okay to refer to a template specialization without an empty
11559/// template parameter declaration, e.g.
11560/// friend class A<T>::B<unsigned>;
11561/// We permit this as a special case; if there are any template
11562/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000011563/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000011564Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000011565 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011566 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000011567
11568 assert(DS.isFriendSpecified());
11569 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11570
John McCall11083da2009-09-16 22:47:08 +000011571 // Try to convert the decl specifier to a type. This works for
11572 // friend templates because ActOnTag never produces a ClassTemplateDecl
11573 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000011574 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000011575 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11576 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000011577 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +000011578 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011579
Douglas Gregor6c110f32010-12-16 01:14:37 +000011580 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11581 return 0;
11582
John McCall11083da2009-09-16 22:47:08 +000011583 // This is definitely an error in C++98. It's probably meant to
11584 // be forbidden in C++0x, too, but the specification is just
11585 // poorly written.
11586 //
11587 // The problem is with declarations like the following:
11588 // template <T> friend A<T>::foo;
11589 // where deciding whether a class C is a friend or not now hinges
11590 // on whether there exists an instantiation of A that causes
11591 // 'foo' to equal C. There are restrictions on class-heads
11592 // (which we declare (by fiat) elaborated friend declarations to
11593 // be) that makes this tractable.
11594 //
11595 // FIXME: handle "template <> friend class A<T>;", which
11596 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000011597 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000011598 Diag(Loc, diag::err_tagless_friend_type_template)
11599 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +000011600 return 0;
John McCall11083da2009-09-16 22:47:08 +000011601 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011602
John McCallaa74a0c2009-08-28 07:59:38 +000011603 // C++98 [class.friend]p1: A friend of a class is a function
11604 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000011605 // This is fixed in DR77, which just barely didn't make the C++03
11606 // deadline. It's also a very silly restriction that seriously
11607 // affects inner classes and which nobody else seems to implement;
11608 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000011609 //
11610 // But note that we could warn about it: it's always useless to
11611 // friend one of your own members (it's not, however, worthless to
11612 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000011613
John McCall11083da2009-09-16 22:47:08 +000011614 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011615 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000011616 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011617 NumTempParamLists,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011618 TempParams.data(),
John McCall15ad0962010-03-25 18:04:51 +000011619 TSI,
John McCall11083da2009-09-16 22:47:08 +000011620 DS.getFriendSpecLoc());
11621 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000011622 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011623
11624 if (!D)
John McCall48871652010-08-21 09:40:31 +000011625 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011626
John McCall11083da2009-09-16 22:47:08 +000011627 D->setAccess(AS_public);
11628 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000011629
John McCall48871652010-08-21 09:40:31 +000011630 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000011631}
11632
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000011633NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11634 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000011635 const DeclSpec &DS = D.getDeclSpec();
11636
11637 assert(DS.isFriendSpecified());
11638 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11639
11640 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000011641 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000011642
11643 // C++ [class.friend]p1
11644 // A friend of a class is a function or class....
11645 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000011646 // It *doesn't* see through dependent types, which is correct
11647 // according to [temp.arg.type]p3:
11648 // If a declaration acquires a function type through a
11649 // type dependent on a template-parameter and this causes
11650 // a declaration that does not use the syntactic form of a
11651 // function declarator to have a function type, the program
11652 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011653 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000011654 Diag(Loc, diag::err_unexpected_friend);
11655
11656 // It might be worthwhile to try to recover by creating an
11657 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +000011658 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011659 }
11660
11661 // C++ [namespace.memdef]p3
11662 // - If a friend declaration in a non-local class first declares a
11663 // class or function, the friend class or function is a member
11664 // of the innermost enclosing namespace.
11665 // - The name of the friend is not found by simple name lookup
11666 // until a matching declaration is provided in that namespace
11667 // scope (either before or after the class declaration granting
11668 // friendship).
11669 // - If a friend function is called, its name may be found by the
11670 // name lookup that considers functions from namespaces and
11671 // classes associated with the types of the function arguments.
11672 // - When looking for a prior declaration of a class or a function
11673 // declared as a friend, scopes outside the innermost enclosing
11674 // namespace scope are not considered.
11675
John McCallde3fd222010-10-12 23:13:28 +000011676 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011677 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11678 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000011679 assert(Name);
11680
Douglas Gregor6c110f32010-12-16 01:14:37 +000011681 // Check for unexpanded parameter packs.
11682 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11683 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11684 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11685 return 0;
11686
John McCall07e91c02009-08-06 02:15:43 +000011687 // The context we found the declaration in, or in which we should
11688 // create the declaration.
11689 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000011690 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011691 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000011692 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000011693
Richard Smith114394f2013-08-09 04:35:01 +000011694 // There are five cases here.
11695 // - There's no scope specifier and we're in a local class. Only look
11696 // for functions declared in the immediately-enclosing block scope.
11697 // We recover from invalid scope qualifiers as if they just weren't there.
11698 FunctionDecl *FunctionContainingLocalClass = 0;
11699 if ((SS.isInvalid() || !SS.isSet()) &&
11700 (FunctionContainingLocalClass =
11701 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11702 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000011703 // If a friend declaration appears in a local class and the name
11704 // specified is an unqualified name, a prior declaration is
11705 // looked up without considering scopes that are outside the
11706 // innermost enclosing non-class scope. For a friend function
11707 // declaration, if there is no prior declaration, the program is
11708 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000011709
11710 // Find the innermost enclosing non-class scope. This is the block
11711 // scope containing the local class definition (or for a nested class,
11712 // the outer local class).
11713 DCScope = S->getFnParent();
11714
11715 // Look up the function name in the scope.
11716 Previous.clear(LookupLocalFriendName);
11717 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11718
11719 if (!Previous.empty()) {
11720 // All possible previous declarations must have the same context:
11721 // either they were declared at block scope or they are members of
11722 // one of the enclosing local classes.
11723 DC = Previous.getRepresentativeDecl()->getDeclContext();
11724 } else {
11725 // This is ill-formed, but provide the context that we would have
11726 // declared the function in, if we were permitted to, for error recovery.
11727 DC = FunctionContainingLocalClass;
11728 }
Richard Smith541b38b2013-09-20 01:15:31 +000011729 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000011730
11731 // C++ [class.friend]p6:
11732 // A function can be defined in a friend declaration of a class if and
11733 // only if the class is a non-local class (9.8), the function name is
11734 // unqualified, and the function has namespace scope.
11735 if (D.isFunctionDefinition()) {
11736 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11737 }
11738
11739 // - There's no scope specifier, in which case we just go to the
11740 // appropriate scope and look for a function or function template
11741 // there as appropriate.
11742 } else if (SS.isInvalid() || !SS.isSet()) {
11743 // C++11 [namespace.memdef]p3:
11744 // If the name in a friend declaration is neither qualified nor
11745 // a template-id and the declaration is a function or an
11746 // elaborated-type-specifier, the lookup to determine whether
11747 // the entity has been previously declared shall not consider
11748 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000011749 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000011750
John McCallf7cfb222010-10-13 05:45:15 +000011751 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000011752 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000011753
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011754 // Skip class contexts. If someone can cite chapter and verse
11755 // for this behavior, that would be nice --- it's what GCC and
11756 // EDG do, and it seems like a reasonable intent, but the spec
11757 // really only says that checks for unqualified existing
11758 // declarations should stop at the nearest enclosing namespace,
11759 // not that they should only consider the nearest enclosing
11760 // namespace.
11761 while (DC->isRecord())
11762 DC = DC->getParent();
11763
11764 DeclContext *LookupDC = DC;
11765 while (LookupDC->isTransparentContext())
11766 LookupDC = LookupDC->getParent();
11767
11768 while (true) {
11769 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000011770
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011771 if (!Previous.empty()) {
11772 DC = LookupDC;
11773 break;
John McCallf4776592010-10-14 22:22:28 +000011774 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011775
11776 if (isTemplateId) {
11777 if (isa<TranslationUnitDecl>(LookupDC)) break;
11778 } else {
11779 if (LookupDC->isFileContext()) break;
11780 }
11781 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000011782 }
11783
John McCallccbc0322010-10-13 06:22:15 +000011784 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000011785
John McCallde3fd222010-10-12 23:13:28 +000011786 // - There's a non-dependent scope specifier, in which case we
11787 // compute it and do a previous lookup there for a function
11788 // or function template.
11789 } else if (!SS.getScopeRep()->isDependent()) {
11790 DC = computeDeclContext(SS);
11791 if (!DC) return 0;
11792
11793 if (RequireCompleteDeclContext(SS, DC)) return 0;
11794
11795 LookupQualifiedName(Previous, DC);
11796
11797 // Ignore things found implicitly in the wrong scope.
11798 // TODO: better diagnostics for this case. Suggesting the right
11799 // qualified scope would be nice...
11800 LookupResult::Filter F = Previous.makeFilter();
11801 while (F.hasNext()) {
11802 NamedDecl *D = F.next();
11803 if (!DC->InEnclosingNamespaceSetOf(
11804 D->getDeclContext()->getRedeclContext()))
11805 F.erase();
11806 }
11807 F.done();
11808
11809 if (Previous.empty()) {
11810 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011811 Diag(Loc, diag::err_qualified_friend_not_found)
11812 << Name << TInfo->getType();
John McCallde3fd222010-10-12 23:13:28 +000011813 return 0;
11814 }
11815
11816 // C++ [class.friend]p1: A friend of a class is a function or
11817 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000011818 if (DC->Equals(CurContext))
11819 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011820 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000011821 diag::warn_cxx98_compat_friend_is_member :
11822 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000011823
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011824 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000011825 // C++ [class.friend]p6:
11826 // A function can be defined in a friend declaration of a class if and
11827 // only if the class is a non-local class (9.8), the function name is
11828 // unqualified, and the function has namespace scope.
11829 SemaDiagnosticBuilder DB
11830 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11831
11832 DB << SS.getScopeRep();
11833 if (DC->isFileContext())
11834 DB << FixItHint::CreateRemoval(SS.getRange());
11835 SS.clear();
11836 }
John McCallde3fd222010-10-12 23:13:28 +000011837
11838 // - There's a scope specifier that does not match any template
11839 // parameter lists, in which case we use some arbitrary context,
11840 // create a method or method template, and wait for instantiation.
11841 // - There's a scope specifier that does match some template
11842 // parameter lists, which we don't handle right now.
11843 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011844 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000011845 // C++ [class.friend]p6:
11846 // A function can be defined in a friend declaration of a class if and
11847 // only if the class is a non-local class (9.8), the function name is
11848 // unqualified, and the function has namespace scope.
11849 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11850 << SS.getScopeRep();
11851 }
11852
John McCallde3fd222010-10-12 23:13:28 +000011853 DC = CurContext;
11854 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000011855 }
Douglas Gregor16e65612011-10-10 01:11:59 +000011856
John McCallf7cfb222010-10-13 05:45:15 +000011857 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000011858 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000011859 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11860 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11861 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000011862 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000011863 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11864 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +000011865 return 0;
John McCall07e91c02009-08-06 02:15:43 +000011866 }
John McCall07e91c02009-08-06 02:15:43 +000011867 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011868
Douglas Gregordd847ba2011-11-03 16:37:14 +000011869 // FIXME: This is an egregious hack to cope with cases where the scope stack
11870 // does not contain the declaration context, i.e., in an out-of-line
11871 // definition of a class.
11872 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11873 if (!DCScope) {
11874 FakeDCScope.setEntity(DC);
11875 DCScope = &FakeDCScope;
11876 }
Richard Smith114394f2013-08-09 04:35:01 +000011877
Francois Pichet00c7e6c2011-08-14 03:52:19 +000011878 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011879 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011880 TemplateParams, AddToScope);
John McCall48871652010-08-21 09:40:31 +000011881 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +000011882
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011883 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000011884
Richard Smith114394f2013-08-09 04:35:01 +000011885 // If we performed typo correction, we might have added a scope specifier
11886 // and changed the decl context.
11887 DC = ND->getDeclContext();
11888
John McCall759e32b2009-08-31 22:39:49 +000011889 // Add the function declaration to the appropriate lookup tables,
11890 // adjusting the redeclarations list as necessary. We don't
11891 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000011892 //
John McCall759e32b2009-08-31 22:39:49 +000011893 // Also update the scope-based lookup if the target context's
11894 // lookup context is in lexical scope.
11895 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000011896 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000011897 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000011898 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011899 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000011900 }
John McCallaa74a0c2009-08-28 07:59:38 +000011901
11902 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000011903 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000011904 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000011905 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000011906 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000011907
John McCalla0a96892012-08-10 03:15:35 +000011908 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000011909 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000011910 } else {
11911 if (DC->isRecord()) CheckFriendAccess(ND);
11912
John McCall2c2eb122010-10-16 06:59:13 +000011913 FunctionDecl *FD;
11914 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11915 FD = FTD->getTemplatedDecl();
11916 else
11917 FD = cast<FunctionDecl>(ND);
11918
David Majnemer502b0ed2013-06-25 23:09:30 +000011919 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11920 // default argument expression, that declaration shall be a definition
11921 // and shall be the only declaration of the function or function
11922 // template in the translation unit.
11923 if (functionDeclHasDefaultArgument(FD)) {
11924 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11925 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11926 Diag(OldFD->getLocation(), diag::note_previous_declaration);
11927 } else if (!D.isFunctionDefinition())
11928 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11929 }
11930
John McCall2c2eb122010-10-16 06:59:13 +000011931 // Mark templated-scope function declarations as unsupported.
11932 if (FD->getNumTemplateParameterLists())
11933 FrD->setUnsupportedFriend(true);
11934 }
John McCallde3fd222010-10-12 23:13:28 +000011935
John McCall48871652010-08-21 09:40:31 +000011936 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000011937}
11938
John McCall48871652010-08-21 09:40:31 +000011939void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11940 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000011941
Aaron Ballmanf96361e2013-01-16 23:39:10 +000011942 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000011943 if (!Fn) {
11944 Diag(DelLoc, diag::err_deleted_non_function);
11945 return;
11946 }
Richard Smithb4d2a152013-04-02 19:38:47 +000011947
Douglas Gregorec9fd132012-01-14 16:38:05 +000011948 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000011949 // Don't consider the implicit declaration we generate for explicit
11950 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikieaf031a92012-06-29 18:00:25 +000011951 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11952 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000011953 Diag(DelLoc, diag::err_deleted_decl_not_first);
11954 Diag(Prev->getLocation(), diag::note_previous_declaration);
11955 }
Sebastian Redlf769df52009-03-24 22:27:57 +000011956 // If the declaration wasn't the first, we delete the function anyway for
11957 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000011958 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000011959 }
Richard Smithb4d2a152013-04-02 19:38:47 +000011960
11961 if (Fn->isDeleted())
11962 return;
11963
11964 // See if we're deleting a function which is already known to override a
11965 // non-deleted virtual function.
11966 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11967 bool IssuedDiagnostic = false;
11968 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11969 E = MD->end_overridden_methods();
11970 I != E; ++I) {
11971 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11972 if (!IssuedDiagnostic) {
11973 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11974 IssuedDiagnostic = true;
11975 }
11976 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11977 }
11978 }
11979 }
11980
Richard Smithb63b6ee2014-01-22 01:43:19 +000011981 // C++11 [basic.start.main]p3:
11982 // A program that defines main as deleted [...] is ill-formed.
11983 if (Fn->isMain())
11984 Diag(DelLoc, diag::err_deleted_main);
11985
Alexis Hunt4a8ea102011-05-06 20:44:56 +000011986 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000011987}
Sebastian Redl4c018662009-04-27 21:33:24 +000011988
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011989void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000011990 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011991
11992 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000011993 if (MD->getParent()->isDependentType()) {
11994 MD->setDefaulted();
11995 MD->setExplicitlyDefaulted();
11996 return;
11997 }
11998
Alexis Hunt5a7fa252011-05-12 06:15:49 +000011999 CXXSpecialMember Member = getSpecialMember(MD);
12000 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000012001 if (!MD->isInvalidDecl())
12002 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012003 return;
12004 }
12005
12006 MD->setDefaulted();
12007 MD->setExplicitlyDefaulted();
12008
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012009 // If this definition appears within the record, do the checking when
12010 // the record is complete.
12011 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000012012 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012013 // Find the uninstantiated declaration that actually had the '= default'
12014 // on it.
Richard Smith802c4b72012-08-23 06:16:52 +000012015 Pattern->isDefined(Primary);
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012016
Richard Smith3901dfe2013-03-27 00:22:47 +000012017 // If the method was defaulted on its first declaration, we will have
12018 // already performed the checking in CheckCompletedCXXClass. Such a
12019 // declaration doesn't trigger an implicit definition.
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012020 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012021 return;
12022
Richard Smithd3b5c9082012-07-27 04:22:15 +000012023 CheckExplicitlyDefaultedSpecialMember(MD);
12024
Richard Smithbd305122012-12-11 01:14:52 +000012025 // The exception specification is needed because we are defining the
12026 // function.
12027 ResolveExceptionSpec(DefaultLoc,
12028 MD->getType()->castAs<FunctionProtoType>());
12029
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012030 if (MD->isInvalidDecl())
12031 return;
12032
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012033 switch (Member) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012034 case CXXDefaultConstructor:
12035 DefineImplicitDefaultConstructor(DefaultLoc,
12036 cast<CXXConstructorDecl>(MD));
Alexis Hunt913820d2011-05-13 06:10:58 +000012037 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012038 case CXXCopyConstructor:
12039 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012040 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012041 case CXXCopyAssignment:
12042 DefineImplicitCopyAssignment(DefaultLoc, MD);
Alexis Huntc9a55732011-05-14 05:23:28 +000012043 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012044 case CXXDestructor:
12045 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Alexis Huntf91729462011-05-12 22:46:25 +000012046 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012047 case CXXMoveConstructor:
12048 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt119c10e2011-05-25 23:16:36 +000012049 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012050 case CXXMoveAssignment:
12051 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012052 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000012053 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000012054 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012055 }
12056 } else {
12057 Diag(DefaultLoc, diag::err_default_special_members);
12058 }
12059}
12060
Sebastian Redl4c018662009-04-27 21:33:24 +000012061static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000012062 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000012063 Stmt *SubStmt = *CI;
12064 if (!SubStmt)
12065 continue;
12066 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012067 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000012068 diag::err_return_in_constructor_handler);
12069 if (!isa<Expr>(SubStmt))
12070 SearchForReturnInStmt(Self, SubStmt);
12071 }
12072}
12073
12074void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12075 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12076 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12077 SearchForReturnInStmt(*this, Handler);
12078 }
12079}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012080
David Blaikie68f71a32013-01-18 23:03:15 +000012081bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000012082 const CXXMethodDecl *Old) {
12083 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12084 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12085
12086 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12087
12088 // If the calling conventions match, everything is fine
12089 if (NewCC == OldCC)
12090 return false;
12091
Hans Wennborg2545efe2013-12-11 17:42:11 +000012092 // If the calling conventions mismatch because the new function is static,
12093 // suppress the calling convention mismatch error; the error about static
12094 // function override (err_static_overrides_virtual from
12095 // Sema::CheckFunctionDeclaration) is more clear.
12096 if (New->getStorageClass() == SC_Static)
12097 return false;
12098
Reid Kleckner78af0702013-08-27 23:08:25 +000012099 Diag(New->getLocation(),
12100 diag::err_conflicting_overriding_cc_attributes)
12101 << New->getDeclName() << New->getType() << Old->getType();
12102 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12103 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000012104}
12105
Mike Stump11289f42009-09-09 15:08:12 +000012106bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012107 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +000012108 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
12109 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012110
Chandler Carruth284bb2e2010-02-15 11:53:20 +000012111 if (Context.hasSameType(NewTy, OldTy) ||
12112 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012113 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012114
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012115 // Check if the return types are covariant
12116 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000012117
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012118 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012119 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12120 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012121 NewClassTy = NewPT->getPointeeType();
12122 OldClassTy = OldPT->getPointeeType();
12123 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012124 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12125 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12126 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12127 NewClassTy = NewRT->getPointeeType();
12128 OldClassTy = OldRT->getPointeeType();
12129 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012130 }
12131 }
Mike Stump11289f42009-09-09 15:08:12 +000012132
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012133 // The return types aren't either both pointers or references to a class type.
12134 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000012135 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012136 diag::err_different_return_type_for_overriding_virtual_function)
12137 << New->getDeclName() << NewTy << OldTy;
12138 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +000012139
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012140 return true;
12141 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012142
Anders Carlssone60365b2009-12-31 18:34:24 +000012143 // C++ [class.virtual]p6:
12144 // If the return type of D::f differs from the return type of B::f, the
12145 // class type in the return type of D::f shall be complete at the point of
12146 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012147 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12148 if (!RT->isBeingDefined() &&
12149 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012150 diag::err_covariant_return_incomplete,
12151 New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000012152 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012153 }
Anders Carlssone60365b2009-12-31 18:34:24 +000012154
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000012155 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012156 // Check if the new class derives from the old class.
12157 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12158 Diag(New->getLocation(),
12159 diag::err_covariant_return_not_derived)
12160 << New->getDeclName() << NewTy << OldTy;
12161 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12162 return true;
12163 }
Mike Stump11289f42009-09-09 15:08:12 +000012164
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012165 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +000012166 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +000012167 diag::err_covariant_return_inaccessible_base,
12168 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12169 // FIXME: Should this point to the return type?
12170 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +000012171 // FIXME: this note won't trigger for delayed access control
12172 // diagnostics, and it's impossible to get an undelayed error
12173 // here from access control during the original parse because
12174 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012175 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12176 return true;
12177 }
12178 }
Mike Stump11289f42009-09-09 15:08:12 +000012179
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012180 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012181 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012182 Diag(New->getLocation(),
12183 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012184 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012185 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
12190 // The new class type must have the same or less qualifiers as the old type.
12191 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12192 Diag(New->getLocation(),
12193 diag::err_covariant_return_type_class_type_more_qualified)
12194 << New->getDeclName() << NewTy << OldTy;
12195 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12196 return true;
12197 };
Mike Stump11289f42009-09-09 15:08:12 +000012198
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012199 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012200}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012201
Douglas Gregor21920e372009-12-01 17:24:26 +000012202/// \brief Mark the given method pure.
12203///
12204/// \param Method the method to be marked pure.
12205///
12206/// \param InitRange the source range that covers the "0" initializer.
12207bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012208 SourceLocation EndLoc = InitRange.getEnd();
12209 if (EndLoc.isValid())
12210 Method->setRangeEnd(EndLoc);
12211
Douglas Gregor21920e372009-12-01 17:24:26 +000012212 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12213 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000012214 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012215 }
Douglas Gregor21920e372009-12-01 17:24:26 +000012216
12217 if (!Method->isInvalidDecl())
12218 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12219 << Method->getDeclName() << InitRange;
12220 return true;
12221}
12222
Douglas Gregor926410d2012-02-21 02:22:07 +000012223/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012224static bool isStaticDataMember(const Decl *D) {
12225 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12226 return Var->isStaticDataMember();
12227
12228 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000012229}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012230
John McCall1f4ee7b2009-12-19 09:28:58 +000012231/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12232/// an initializer for the out-of-line declaration 'Dcl'. The scope
12233/// is a fresh scope pushed for just this purpose.
12234///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012235/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12236/// static data member of class X, names should be looked up in the scope of
12237/// class X.
John McCall48871652010-08-21 09:40:31 +000012238void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012239 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000012240 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012241
Richard Smitha2302242013-12-05 07:51:02 +000012242 // We will always have a nested name specifier here, but this declaration
12243 // might not be out of line if the specifier names the current namespace:
12244 // extern int n;
12245 // int ::n = 0;
12246 if (D->isOutOfLine())
12247 EnterDeclaratorContext(S, D->getDeclContext());
12248
Douglas Gregor926410d2012-02-21 02:22:07 +000012249 // If we are parsing the initializer for a static data member, push a
12250 // new expression evaluation context that is associated with this static
12251 // data member.
12252 if (isStaticDataMember(D))
12253 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012254}
12255
12256/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000012257/// initializer for the out-of-line declaration 'D'.
12258void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012259 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000012260 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012261
Douglas Gregor926410d2012-02-21 02:22:07 +000012262 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000012263 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000012264
Richard Smitha2302242013-12-05 07:51:02 +000012265 if (D->isOutOfLine())
12266 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012267}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012268
12269/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12270/// C++ if/switch/while/for statement.
12271/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000012272DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012273 // C++ 6.4p2:
12274 // The declarator shall not specify a function or an array.
12275 // The type-specifier-seq shall not contain typedef and shall not declare a
12276 // new class or enumeration.
12277 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12278 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012279
12280 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012281 if (!Dcl)
12282 return true;
12283
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012284 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12285 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012286 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012287 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012288 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012289
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012290 return Dcl;
12291}
Anders Carlssonf98849e2009-12-02 17:15:43 +000012292
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012293void Sema::LoadExternalVTableUses() {
12294 if (!ExternalSource)
12295 return;
12296
12297 SmallVector<ExternalVTableUse, 4> VTables;
12298 ExternalSource->ReadUsedVTables(VTables);
12299 SmallVector<VTableUse, 4> NewUses;
12300 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12301 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12302 = VTablesUsed.find(VTables[I].Record);
12303 // Even if a definition wasn't required before, it may be required now.
12304 if (Pos != VTablesUsed.end()) {
12305 if (!Pos->second && VTables[I].DefinitionRequired)
12306 Pos->second = true;
12307 continue;
12308 }
12309
12310 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12311 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12312 }
12313
12314 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12315}
12316
Douglas Gregor88d292c2010-05-13 16:44:06 +000012317void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12318 bool DefinitionRequired) {
12319 // Ignore any vtable uses in unevaluated operands or for classes that do
12320 // not have a vtable.
12321 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000012322 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000012323 return;
12324
Douglas Gregor88d292c2010-05-13 16:44:06 +000012325 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012326 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012327 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12328 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12329 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12330 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000012331 // If we already had an entry, check to see if we are promoting this vtable
12332 // to required a definition. If so, we need to reappend to the VTableUses
12333 // list, since we may have already processed the first entry.
12334 if (DefinitionRequired && !Pos.first->second) {
12335 Pos.first->second = true;
12336 } else {
12337 // Otherwise, we can early exit.
12338 return;
12339 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012340 }
12341
12342 // Local classes need to have their virtual members marked
12343 // immediately. For all other classes, we mark their virtual members
12344 // at the end of the translation unit.
12345 if (Class->isLocalClass())
12346 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000012347 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000012348 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000012349}
12350
Douglas Gregor88d292c2010-05-13 16:44:06 +000012351bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012352 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012353 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000012354 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000012355
Douglas Gregor88d292c2010-05-13 16:44:06 +000012356 // Note: The VTableUses vector could grow as a result of marking
12357 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000012358 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000012359 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000012360 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012361 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000012362 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012363 if (!Class)
12364 continue;
12365
12366 SourceLocation Loc = VTableUses[I].second;
12367
Richard Smithd3b5c9082012-07-27 04:22:15 +000012368 bool DefineVTable = true;
12369
Douglas Gregor88d292c2010-05-13 16:44:06 +000012370 // If this class has a key function, but that key function is
12371 // defined in another translation unit, we don't need to emit the
12372 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000012373 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000012374 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000012375 // The key function is in another translation unit.
12376 DefineVTable = false;
12377 TemplateSpecializationKind TSK =
12378 KeyFunction->getTemplateSpecializationKind();
12379 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12380 TSK != TSK_ImplicitInstantiation &&
12381 "Instantiations don't have key functions");
12382 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012383 } else if (!KeyFunction) {
12384 // If we have a class with no key function that is the subject
12385 // of an explicit instantiation declaration, suppress the
12386 // vtable; it will live with the explicit instantiation
12387 // definition.
12388 bool IsExplicitInstantiationDeclaration
12389 = Class->getTemplateSpecializationKind()
12390 == TSK_ExplicitInstantiationDeclaration;
12391 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
12392 REnd = Class->redecls_end();
12393 R != REnd; ++R) {
12394 TemplateSpecializationKind TSK
12395 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
12396 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() &&
David Blaikie6adc78e2013-02-18 22:06:02 +000012658 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
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.
12711 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12712 A != AEnd; ++A) {
12713 // FIXME: This should be emitted by tblgen.
12714 Expr *Arg = 0;
12715 ArrayRef<Expr *> Args;
12716 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12717 Arg = G->getArg();
12718 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12719 Arg = G->getArg();
12720 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12721 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12722 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12723 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12724 else if (ExclusiveLockFunctionAttr *ELF
12725 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12726 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12727 else if (SharedLockFunctionAttr *SLF
12728 = dyn_cast<SharedLockFunctionAttr>(*A))
12729 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12730 else if (ExclusiveTrylockFunctionAttr *ETLF
12731 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12732 Arg = ETLF->getSuccessValue();
12733 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12734 } else if (SharedTrylockFunctionAttr *STLF
12735 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12736 Arg = STLF->getSuccessValue();
12737 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12738 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12739 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12740 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12741 Arg = LR->getArg();
12742 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12743 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12744 else if (ExclusiveLocksRequiredAttr *ELR
12745 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12746 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12747 else if (SharedLocksRequiredAttr *SLR
12748 = dyn_cast<SharedLocksRequiredAttr>(*A))
12749 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12750
12751 if (Arg && !Finder.TraverseStmt(Arg))
12752 return true;
12753
12754 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12755 if (!Finder.TraverseStmt(Args[I]))
12756 return true;
12757 }
12758 }
12759
12760 return false;
12761}
12762
Douglas Gregor433e0532012-04-16 18:27:27 +000012763void
12764Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12765 ArrayRef<ParsedType> DynamicExceptions,
12766 ArrayRef<SourceRange> DynamicExceptionRanges,
12767 Expr *NoexceptExpr,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000012768 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor433e0532012-04-16 18:27:27 +000012769 FunctionProtoType::ExtProtoInfo &EPI) {
12770 Exceptions.clear();
12771 EPI.ExceptionSpecType = EST;
12772 if (EST == EST_Dynamic) {
12773 Exceptions.reserve(DynamicExceptions.size());
12774 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12775 // FIXME: Preserve type source info.
12776 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12777
12778 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12779 collectUnexpandedParameterPacks(ET, Unexpanded);
12780 if (!Unexpanded.empty()) {
12781 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12782 UPPC_ExceptionType,
12783 Unexpanded);
12784 continue;
12785 }
12786
12787 // Check that the type is valid for an exception spec, and
12788 // drop it if not.
12789 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12790 Exceptions.push_back(ET);
12791 }
12792 EPI.NumExceptions = Exceptions.size();
12793 EPI.Exceptions = Exceptions.data();
12794 return;
12795 }
12796
12797 if (EST == EST_ComputedNoexcept) {
12798 // If an error occurred, there's no expression here.
12799 if (NoexceptExpr) {
12800 assert((NoexceptExpr->isTypeDependent() ||
12801 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12802 Context.BoolTy) &&
12803 "Parser should have made sure that the expression is boolean");
12804 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12805 EPI.ExceptionSpecType = EST_BasicNoexcept;
12806 return;
12807 }
12808
12809 if (!NoexceptExpr->isValueDependent())
12810 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregore2b37442012-05-04 22:38:52 +000012811 diag::err_noexcept_needs_constant_expression,
Douglas Gregor433e0532012-04-16 18:27:27 +000012812 /*AllowFold*/ false).take();
12813 EPI.NoexceptExpr = NoexceptExpr;
12814 }
12815 return;
12816 }
12817}
12818
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012819/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12820Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12821 // Implicitly declared functions (e.g. copy constructors) are
12822 // __host__ __device__
12823 if (D->isImplicit())
12824 return CFT_HostDevice;
12825
12826 if (D->hasAttr<CUDAGlobalAttr>())
12827 return CFT_Global;
12828
12829 if (D->hasAttr<CUDADeviceAttr>()) {
12830 if (D->hasAttr<CUDAHostAttr>())
12831 return CFT_HostDevice;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012832 return CFT_Device;
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012833 }
12834
12835 return CFT_Host;
12836}
12837
12838bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12839 CUDAFunctionTarget CalleeTarget) {
12840 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12841 // Callable from the device only."
12842 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12843 return true;
12844
12845 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12846 // Callable from the host only."
12847 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12848 // Callable from the host only."
12849 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12850 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12851 return true;
12852
12853 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12854 return true;
12855
12856 return false;
12857}
John McCall5e77d762013-04-16 07:28:30 +000012858
12859/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12860///
12861MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12862 SourceLocation DeclStart,
12863 Declarator &D, Expr *BitWidth,
12864 InClassInitStyle InitStyle,
12865 AccessSpecifier AS,
12866 AttributeList *MSPropertyAttr) {
12867 IdentifierInfo *II = D.getIdentifier();
12868 if (!II) {
12869 Diag(DeclStart, diag::err_anonymous_property);
12870 return NULL;
12871 }
12872 SourceLocation Loc = D.getIdentifierLoc();
12873
12874 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12875 QualType T = TInfo->getType();
12876 if (getLangOpts().CPlusPlus) {
12877 CheckExtraCXXDefaultArguments(D);
12878
12879 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12880 UPPC_DataMemberType)) {
12881 D.setInvalidType();
12882 T = Context.IntTy;
12883 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12884 }
12885 }
12886
12887 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12888
12889 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12890 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12891 diag::err_invalid_thread)
12892 << DeclSpec::getSpecifierName(TSCS);
12893
12894 // Check to see if this name was declared as a member previously
12895 NamedDecl *PrevDecl = 0;
12896 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12897 LookupName(Previous, S);
12898 switch (Previous.getResultKind()) {
12899 case LookupResult::Found:
12900 case LookupResult::FoundUnresolvedValue:
12901 PrevDecl = Previous.getAsSingle<NamedDecl>();
12902 break;
12903
12904 case LookupResult::FoundOverloaded:
12905 PrevDecl = Previous.getRepresentativeDecl();
12906 break;
12907
12908 case LookupResult::NotFound:
12909 case LookupResult::NotFoundInCurrentInstantiation:
12910 case LookupResult::Ambiguous:
12911 break;
12912 }
12913
12914 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12915 // Maybe we will complain about the shadowed template parameter.
12916 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12917 // Just pretend that we didn't see the previous declaration.
12918 PrevDecl = 0;
12919 }
12920
12921 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12922 PrevDecl = 0;
12923
12924 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000012925 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000012926 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
12927 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000012928 ProcessDeclAttributes(TUScope, NewPD, D);
12929 NewPD->setAccess(AS);
12930
12931 if (NewPD->isInvalidDecl())
12932 Record->setInvalidDecl();
12933
12934 if (D.getDeclSpec().isModulePrivateSpecified())
12935 NewPD->setModulePrivate();
12936
12937 if (NewPD->isInvalidDecl() && PrevDecl) {
12938 // Don't introduce NewFD into scope; there's already something
12939 // with the same name in the same scope.
12940 } else if (II) {
12941 PushOnScopeChains(NewPD, S);
12942 } else
12943 Record->addDecl(NewPD);
12944
12945 return NewPD;
12946}