blob: 5e789fe20ed578b47df10abdf50dddd3a3930afe [file] [log] [blame]
Chris Lattner199abbc2008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Faisal Vali2b391ab2013-09-26 19:54:12 +000017#include "clang/AST/ASTLambda.h"
Sebastian Redlab238a72011-04-24 16:28:06 +000018#include "clang/AST/ASTMutationListener.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/CharUnits.h"
Richard Trieu4fc85362012-06-14 23:11:34 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Alexis Huntc5575cc2011-02-26 19:13:13 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000023#include "clang/AST/RecordLayout.h"
Douglas Gregor3024f072012-04-16 07:05:22 +000024#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000025#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballman02df2e02012-12-09 17:45:41 +000029#include "clang/Basic/TargetInfo.h"
Richard Smithf4198b72013-07-23 08:14:48 +000030#include "clang/Lex/LiteralSupport.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000031#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/CXXFieldCollector.h"
33#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Initialization.h"
35#include "clang/Sema/Lookup.h"
36#include "clang/Sema/ParsedTemplate.h"
37#include "clang/Sema/Scope.h"
38#include "clang/Sema/ScopeInfo.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000039#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "llvm/ADT/SmallString.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000041#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000042#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000043
44using namespace clang;
45
Chris Lattner58258242008-04-10 02:22:51 +000046//===----------------------------------------------------------------------===//
47// CheckDefaultArgumentVisitor
48//===----------------------------------------------------------------------===//
49
Chris Lattnerb0d38442008-04-12 23:52:44 +000050namespace {
51 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
52 /// the default argument of a parameter to determine whether it
53 /// contains any ill-formed subexpressions. For example, this will
54 /// diagnose the use of local variables or parameters within the
55 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000056 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000057 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000058 Expr *DefaultArg;
59 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000060
Chris Lattnerb0d38442008-04-12 23:52:44 +000061 public:
Mike Stump11289f42009-09-09 15:08:12 +000062 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000063 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000064
Chris Lattnerb0d38442008-04-12 23:52:44 +000065 bool VisitExpr(Expr *Node);
66 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000067 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0d49512012-02-10 23:30:22 +000068 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall7353c862013-04-09 01:56:28 +000069 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000070 };
Chris Lattner58258242008-04-10 02:22:51 +000071
Chris Lattnerb0d38442008-04-12 23:52:44 +000072 /// VisitExpr - Visit all of the children of this expression.
73 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
74 bool IsInvalid = false;
John McCall8322c3a2011-02-13 04:07:26 +000075 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattner574dee62008-07-26 22:17:49 +000076 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000077 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000078 }
79
Chris Lattnerb0d38442008-04-12 23:52:44 +000080 /// VisitDeclRefExpr - Visit a reference to a declaration, to
81 /// determine whether this declaration can be used in the default
82 /// argument expression.
83 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000084 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000085 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
86 // C++ [dcl.fct.default]p9
87 // Default arguments are evaluated each time the function is
88 // called. The order of evaluation of function arguments is
89 // unspecified. Consequently, parameters of a function shall not
90 // be used in default argument expressions, even if they are not
91 // evaluated. Parameters of a function declared before a default
92 // argument expression are in scope and can hide namespace and
93 // class member names.
Daniel Dunbar62ee6412012-03-09 18:35:03 +000094 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +000095 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000096 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000097 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000098 // C++ [dcl.fct.default]p7
99 // Local variables shall not be used in default argument
100 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +0000101 if (VDecl->isLocalVarDecl())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000102 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000103 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +0000104 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000105 }
Chris Lattner58258242008-04-10 02:22:51 +0000106
Douglas Gregor8e12c382008-11-04 13:41:56 +0000107 return false;
108 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000109
Douglas Gregor97a9c812008-11-04 14:32:21 +0000110 /// VisitCXXThisExpr - Visit a C++ "this" expression.
111 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
112 // C++ [dcl.fct.default]p8:
113 // The keyword this shall not be used in a default argument of a
114 // member function.
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000115 return S->Diag(ThisE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000116 diag::err_param_default_argument_references_this)
117 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000118 }
Douglas Gregorf0d49512012-02-10 23:30:22 +0000119
John McCall7353c862013-04-09 01:56:28 +0000120 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
121 bool Invalid = false;
122 for (PseudoObjectExpr::semantics_iterator
123 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
124 Expr *E = *i;
125
126 // Look through bindings.
127 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
128 E = OVE->getSourceExpr();
129 assert(E && "pseudo-object binding without source expression?");
130 }
131
132 Invalid |= Visit(E);
133 }
134 return Invalid;
135 }
136
Douglas Gregorf0d49512012-02-10 23:30:22 +0000137 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
138 // C++11 [expr.lambda.prim]p13:
139 // A lambda-expression appearing in a default argument shall not
140 // implicitly or explicitly capture any entity.
141 if (Lambda->capture_begin() == Lambda->capture_end())
142 return false;
143
144 return S->Diag(Lambda->getLocStart(),
145 diag::err_lambda_capture_default_arg);
146 }
Chris Lattner58258242008-04-10 02:22:51 +0000147}
148
Richard Smithb7151b92013-04-10 06:11:48 +0000149void
150Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
151 const CXXMethodDecl *Method) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000152 // If we have an MSAny spec already, don't bother.
153 if (!Method || ComputedEST == EST_MSAny)
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000154 return;
155
156 const FunctionProtoType *Proto
157 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +0000158 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
159 if (!Proto)
160 return;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000161
162 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
163
164 // If this function can throw any exceptions, make a note of that.
Richard Smithd3b5c9082012-07-27 04:22:15 +0000165 if (EST == EST_MSAny || EST == EST_None) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000166 ClearExceptions();
167 ComputedEST = EST;
168 return;
169 }
170
Richard Smith938f40b2011-06-11 17:19:42 +0000171 // FIXME: If the call to this decl is using any of its default arguments, we
172 // need to search them for potentially-throwing calls.
173
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000174 // If this function has a basic noexcept, it doesn't affect the outcome.
175 if (EST == EST_BasicNoexcept)
176 return;
177
178 // If we have a throw-all spec at this point, ignore the function.
179 if (ComputedEST == EST_None)
180 return;
181
182 // If we're still at noexcept(true) and there's a nothrow() callee,
183 // change to that specification.
184 if (EST == EST_DynamicNone) {
185 if (ComputedEST == EST_BasicNoexcept)
186 ComputedEST = EST_DynamicNone;
187 return;
188 }
189
190 // Check out noexcept specs.
191 if (EST == EST_ComputedNoexcept) {
Richard Smithf623c962012-04-17 00:58:00 +0000192 FunctionProtoType::NoexceptResult NR =
193 Proto->getNoexceptSpec(Self->Context);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000194 assert(NR != FunctionProtoType::NR_NoNoexcept &&
195 "Must have noexcept result for EST_ComputedNoexcept.");
196 assert(NR != FunctionProtoType::NR_Dependent &&
197 "Should not generate implicit declarations for dependent cases, "
198 "and don't know how to handle them anyway.");
199
200 // noexcept(false) -> no spec on the new function
201 if (NR == FunctionProtoType::NR_Throw) {
202 ClearExceptions();
203 ComputedEST = EST_None;
204 }
205 // noexcept(true) won't change anything either.
206 return;
207 }
208
209 assert(EST == EST_Dynamic && "EST case not considered earlier.");
210 assert(ComputedEST != EST_None &&
211 "Shouldn't collect exceptions when throw-all is guaranteed.");
212 ComputedEST = EST_Dynamic;
213 // Record the exceptions in this function's exception specification.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000214 for (const auto &E : Proto->exceptions())
215 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)))
216 Exceptions.push_back(E);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000217}
218
Richard Smith938f40b2011-06-11 17:19:42 +0000219void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000220 if (!E || ComputedEST == EST_MSAny)
Richard Smith938f40b2011-06-11 17:19:42 +0000221 return;
222
223 // FIXME:
224 //
225 // C++0x [except.spec]p14:
NAKAMURA Takumi53648472011-06-21 03:19:28 +0000226 // [An] implicit exception-specification specifies the type-id T if and
227 // only if T is allowed by the exception-specification of a function directly
228 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith938f40b2011-06-11 17:19:42 +0000229 // function it directly invokes allows all exceptions, and f shall allow no
230 // exceptions if every function it directly invokes allows no exceptions.
231 //
232 // Note in particular that if an implicit exception-specification is generated
233 // for a function containing a throw-expression, that specification can still
234 // be noexcept(true).
235 //
236 // Note also that 'directly invoked' is not defined in the standard, and there
237 // is no indication that we should only consider potentially-evaluated calls.
238 //
239 // Ultimately we should implement the intent of the standard: the exception
240 // specification should be the set of exceptions which can be thrown by the
241 // implicit definition. For now, we assume that any non-nothrow expression can
242 // throw any exception.
243
Richard Smithf623c962012-04-17 00:58:00 +0000244 if (Self->canThrow(E))
Richard Smith938f40b2011-06-11 17:19:42 +0000245 ComputedEST = EST_None;
246}
247
Anders Carlssonc80a1272009-08-25 02:29:20 +0000248bool
John McCallb268a282010-08-23 23:25:46 +0000249Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000250 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000251 if (RequireCompleteType(Param->getLocation(), Param->getType(),
252 diag::err_typecheck_decl_incomplete_type)) {
253 Param->setInvalidDecl();
254 return true;
255 }
256
Anders Carlssonc80a1272009-08-25 02:29:20 +0000257 // C++ [dcl.fct.default]p5
258 // A default argument expression is implicitly converted (clause
259 // 4) to the parameter type. The default argument expression has
260 // the same semantic constraints as the initializer expression in
261 // a declaration of a variable of the parameter type, using the
262 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000263 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
264 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000265 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
266 EqualLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000267 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000268 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman5f101b92009-12-22 02:46:13 +0000269 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000270 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000271 Arg = Result.getAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000272
Richard Smithc406cb72013-01-17 01:17:56 +0000273 CheckCompletedExpr(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000274 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000275
Anders Carlssonc80a1272009-08-25 02:29:20 +0000276 // Okay: add the default argument to the parameter
277 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000278
Douglas Gregor758cb672010-10-12 18:23:32 +0000279 // We have already instantiated this parameter; provide each of the
280 // instantiations with the uninstantiated default argument.
281 UnparsedDefaultArgInstantiationsMap::iterator InstPos
282 = UnparsedDefaultArgInstantiations.find(Param);
283 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
284 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
285 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
286
287 // We're done tracking this parameter's instantiations.
288 UnparsedDefaultArgInstantiations.erase(InstPos);
289 }
290
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000291 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000292}
293
Chris Lattner58258242008-04-10 02:22:51 +0000294/// ActOnParamDefaultArgument - Check whether the default argument
295/// provided for a function parameter is well-formed. If so, attach it
296/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000297void
John McCall48871652010-08-21 09:40:31 +0000298Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000299 Expr *DefaultArg) {
300 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000301 return;
Mike Stump11289f42009-09-09 15:08:12 +0000302
John McCall48871652010-08-21 09:40:31 +0000303 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000304 UnparsedDefaultArgLocs.erase(Param);
305
Chris Lattner199abbc2008-04-08 05:04:30 +0000306 // Default arguments are only permitted in C++
David Blaikiebbafb8a2012-03-11 07:00:24 +0000307 if (!getLangOpts().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000308 Diag(EqualLoc, diag::err_param_default_argument)
309 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000310 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000311 return;
312 }
313
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000314 // Check for unexpanded parameter packs.
315 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
316 Param->setInvalidDecl();
317 return;
318 }
319
Anders Carlssonf1c26952009-08-25 01:02:06 +0000320 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000321 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
322 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000323 Param->setInvalidDecl();
324 return;
325 }
Mike Stump11289f42009-09-09 15:08:12 +0000326
John McCallb268a282010-08-23 23:25:46 +0000327 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000328}
329
Douglas Gregor58354032008-12-24 00:01:03 +0000330/// ActOnParamUnparsedDefaultArgument - We've seen a default
331/// argument for a function parameter, but we can't parse it yet
332/// because we're inside a class definition. Note that this default
333/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000334void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000335 SourceLocation EqualLoc,
336 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000337 if (!param)
338 return;
Mike Stump11289f42009-09-09 15:08:12 +0000339
John McCall48871652010-08-21 09:40:31 +0000340 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Nick Lewycky0f292892013-09-22 10:06:57 +0000341 Param->setUnparsedDefaultArg();
Anders Carlsson84613c42009-06-12 16:51:40 +0000342 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000343}
344
Douglas Gregor4d87df52008-12-16 21:30:33 +0000345/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
346/// the default argument for the parameter param failed.
Serge Pavlovb4b35782014-07-22 01:54:49 +0000347void Sema::ActOnParamDefaultArgumentError(Decl *param,
348 SourceLocation EqualLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000349 if (!param)
350 return;
Mike Stump11289f42009-09-09 15:08:12 +0000351
John McCall48871652010-08-21 09:40:31 +0000352 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000353 Param->setInvalidDecl();
Anders Carlsson84613c42009-06-12 16:51:40 +0000354 UnparsedDefaultArgLocs.erase(Param);
Serge Pavlovb4b35782014-07-22 01:54:49 +0000355 Param->setDefaultArg(new(Context)
356 OpaqueValueExpr(EqualLoc, Param->getType(), VK_RValue));
Douglas Gregor4d87df52008-12-16 21:30:33 +0000357}
358
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000359/// CheckExtraCXXDefaultArguments - Check for any extra default
360/// arguments in the declarator, which is not a function declaration
361/// or definition and therefore is not permitted to have default
362/// arguments. This routine should be invoked for every declarator
363/// that is not a function declaration or definition.
364void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
365 // C++ [dcl.fct.default]p3
366 // A default argument expression shall be specified only in the
367 // parameter-declaration-clause of a function declaration or in a
368 // template-parameter (14.1). It shall not be specified for a
369 // parameter pack. If it is specified in a
370 // parameter-declaration-clause, it shall not occur within a
371 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000372 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattner83f095c2009-03-28 19:18:32 +0000373 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000374 DeclaratorChunk &chunk = D.getTypeObject(i);
375 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000376 if (MightBeFunction) {
377 // This is a function declaration. It can have default arguments, but
378 // keep looking in case its return type is a function type with default
379 // arguments.
380 MightBeFunction = false;
381 continue;
382 }
Alp Tokerc5350722014-02-26 22:27:52 +0000383 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
384 ++argIdx) {
385 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000386 if (Param->hasUnparsedDefaultArg()) {
Alp Tokerc5350722014-02-26 22:27:52 +0000387 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000388 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000389 << SourceRange((*Toks)[1].getLocation(),
390 Toks->back().getLocation());
Douglas Gregor4d87df52008-12-16 21:30:33 +0000391 delete Toks;
Craig Topperc3ec1492014-05-26 06:22:03 +0000392 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
Douglas Gregor58354032008-12-24 00:01:03 +0000393 } else if (Param->getDefaultArg()) {
394 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
395 << Param->getDefaultArg()->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +0000396 Param->setDefaultArg(nullptr);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000397 }
398 }
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000399 } else if (chunk.Kind != DeclaratorChunk::Paren) {
400 MightBeFunction = false;
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000401 }
402 }
403}
404
David Majnemer502b0ed2013-06-25 23:09:30 +0000405static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
406 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
407 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
408 if (!PVD->hasDefaultArg())
409 return false;
410 if (!PVD->hasInheritedDefaultArg())
411 return true;
412 }
413 return false;
414}
415
Craig Toppere4794282012-09-21 04:33:26 +0000416/// MergeCXXFunctionDecl - Merge two declarations of the same C++
417/// function, once we already know that they have the same
418/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
419/// error, false otherwise.
James Molloye9430032012-03-13 08:55:35 +0000420bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
421 Scope *S) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000422 bool Invalid = false;
423
Chris Lattner199abbc2008-04-08 05:04:30 +0000424 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000425 // For non-template functions, default arguments can be added in
426 // later declarations of a function in the same
427 // scope. Declarations in different scopes have completely
428 // distinct sets of default arguments. That is, declarations in
429 // inner scopes do not acquire default arguments from
430 // declarations in outer scopes, and vice versa. In a given
431 // function declaration, all parameters subsequent to a
432 // parameter with a default argument shall have default
433 // arguments supplied in this or previous declarations. A
434 // default argument shall not be redefined by a later
435 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000436 //
437 // C++ [dcl.fct.default]p6:
Richard Smith541b38b2013-09-20 01:15:31 +0000438 // Except for member functions of class templates, the default arguments
439 // in a member function definition that appears outside of the class
440 // definition are added to the set of default arguments provided by the
Douglas Gregorc732aba2009-09-11 18:44:32 +0000441 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000442 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
443 ParmVarDecl *OldParam = Old->getParamDecl(p);
444 ParmVarDecl *NewParam = New->getParamDecl(p);
445
James Molloye9430032012-03-13 08:55:35 +0000446 bool OldParamHasDfl = OldParam->hasDefaultArg();
447 bool NewParamHasDfl = NewParam->hasDefaultArg();
448
449 NamedDecl *ND = Old;
Richard Smith541b38b2013-09-20 01:15:31 +0000450
451 // The declaration context corresponding to the scope is the semantic
452 // parent, unless this is a local function declaration, in which case
453 // it is that surrounding function.
454 DeclContext *ScopeDC = New->getLexicalDeclContext();
455 if (!ScopeDC->isFunctionOrMethod())
456 ScopeDC = New->getDeclContext();
457 if (S && !isDeclInScope(ND, ScopeDC, S) &&
458 !New->getDeclContext()->isRecord())
James Molloye9430032012-03-13 08:55:35 +0000459 // Ignore default parameters of old decl if they are not in
Richard Smith541b38b2013-09-20 01:15:31 +0000460 // the same scope and this is not an out-of-line definition of
461 // a member function.
James Molloye9430032012-03-13 08:55:35 +0000462 OldParamHasDfl = false;
463
464 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000465
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000466 unsigned DiagDefaultParamID =
467 diag::err_param_default_argument_redefinition;
468
469 // MSVC accepts that default parameters be redefined for member functions
470 // of template class. The new default parameter's value is ignored.
471 Invalid = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000472 if (getLangOpts().MicrosoftExt) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000473 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
474 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000475 // Merge the old default argument into the new parameter.
476 NewParam->setHasInheritedDefaultArg();
477 if (OldParam->hasUninstantiatedDefaultArg())
478 NewParam->setUninstantiatedDefaultArg(
479 OldParam->getUninstantiatedDefaultArg());
480 else
481 NewParam->setDefaultArg(OldParam->getInit());
Richard Smith1b98ccc2014-07-19 01:39:17 +0000482 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000483 Invalid = false;
484 }
485 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000486
Francois Pichet8cb243a2011-04-10 04:58:30 +0000487 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
488 // hint here. Alternatively, we could walk the type-source information
489 // for NewParam to find the last source location in the type... but it
490 // isn't worth the effort right now. This is the kind of test case that
491 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000492 // int f(int);
493 // void g(int (*fp)(int) = f);
494 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000495 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000496 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000497
498 // Look for the function declaration where the default argument was
499 // actually written, which may be a declaration prior to Old.
Douglas Gregorec9fd132012-01-14 16:38:05 +0000500 for (FunctionDecl *Older = Old->getPreviousDecl();
501 Older; Older = Older->getPreviousDecl()) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000502 if (!Older->getParamDecl(p)->hasDefaultArg())
503 break;
504
505 OldParam = Older->getParamDecl(p);
506 }
507
508 Diag(OldParam->getLocation(), diag::note_previous_definition)
509 << OldParam->getDefaultArgRange();
James Molloye9430032012-03-13 08:55:35 +0000510 } else if (OldParamHasDfl) {
John McCalle61b02b2010-05-04 01:53:42 +0000511 // Merge the old default argument into the new parameter.
512 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000513 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000514 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000515 if (OldParam->hasUninstantiatedDefaultArg())
516 NewParam->setUninstantiatedDefaultArg(
517 OldParam->getUninstantiatedDefaultArg());
518 else
John McCalle61b02b2010-05-04 01:53:42 +0000519 NewParam->setDefaultArg(OldParam->getInit());
James Molloye9430032012-03-13 08:55:35 +0000520 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000521 if (New->getDescribedFunctionTemplate()) {
522 // Paragraph 4, quoted above, only applies to non-template functions.
523 Diag(NewParam->getLocation(),
524 diag::err_param_default_argument_template_redecl)
525 << NewParam->getDefaultArgRange();
526 Diag(Old->getLocation(), diag::note_template_prev_declaration)
527 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000528 } else if (New->getTemplateSpecializationKind()
529 != TSK_ImplicitInstantiation &&
530 New->getTemplateSpecializationKind() != TSK_Undeclared) {
531 // C++ [temp.expr.spec]p21:
532 // Default function arguments shall not be specified in a declaration
533 // or a definition for one of the following explicit specializations:
534 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000535 // - the explicit specialization of a member function template;
536 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000537 // template where the class template specialization to which the
538 // member function specialization belongs is implicitly
539 // instantiated.
540 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
541 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
542 << New->getDeclName()
543 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000544 } else if (New->getDeclContext()->isDependentContext()) {
545 // C++ [dcl.fct.default]p6 (DR217):
546 // Default arguments for a member function of a class template shall
547 // be specified on the initial declaration of the member function
548 // within the class template.
549 //
550 // Reading the tea leaves a bit in DR217 and its reference to DR205
551 // leads me to the conclusion that one cannot add default function
552 // arguments for an out-of-line definition of a member function of a
553 // dependent type.
554 int WhichKind = 2;
555 if (CXXRecordDecl *Record
556 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
557 if (Record->getDescribedClassTemplate())
558 WhichKind = 0;
559 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
560 WhichKind = 1;
561 else
562 WhichKind = 2;
563 }
564
565 Diag(NewParam->getLocation(),
566 diag::err_param_default_argument_member_template_redecl)
567 << WhichKind
568 << NewParam->getDefaultArgRange();
569 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000570 }
571 }
572
Richard Smith58c3cc12012-11-28 03:45:24 +0000573 // DR1344: If a default argument is added outside a class definition and that
574 // default argument makes the function a special member function, the program
575 // is ill-formed. This can only happen for constructors.
576 if (isa<CXXConstructorDecl>(New) &&
577 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
578 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
579 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
580 if (NewSM != OldSM) {
581 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
582 assert(NewParam->hasDefaultArg());
583 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
584 << NewParam->getDefaultArgRange() << NewSM;
585 Diag(Old->getLocation(), diag::note_previous_declaration);
586 }
587 }
588
David Majnemeree4f4022014-03-30 06:44:54 +0000589 const FunctionDecl *Def;
Richard Smith5b8b3db2012-02-20 23:28:05 +0000590 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000591 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000592 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000593 if (New->isConstexpr() != Old->isConstexpr()) {
594 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
595 << New << New->isConstexpr();
596 Diag(Old->getLocation(), diag::note_previous_declaration);
597 Invalid = true;
David Majnemeree4f4022014-03-30 06:44:54 +0000598 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) {
599 // C++11 [dcl.fcn.spec]p4:
600 // If the definition of a function appears in a translation unit before its
601 // first declaration as inline, the program is ill-formed.
602 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
603 Diag(Def->getLocation(), diag::note_previous_definition);
604 Invalid = true;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000605 }
606
David Majnemer502b0ed2013-06-25 23:09:30 +0000607 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000608 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000609 // the only declaration of the function or function template in the
610 // translation unit.
611 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
612 functionDeclHasDefaultArgument(Old)) {
613 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
614 Diag(Old->getLocation(), diag::note_previous_declaration);
615 Invalid = true;
616 }
617
Douglas Gregorf40863c2010-02-12 07:32:17 +0000618 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000619 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000620
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000621 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000622}
623
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000624/// \brief Merge the exception specifications of two variable declarations.
625///
626/// This is called when there's a redeclaration of a VarDecl. The function
627/// checks if the redeclaration might have an exception specification and
628/// validates compatibility and merges the specs if necessary.
629void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
630 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000631 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000632 return;
633
634 assert(Context.hasSameType(New->getType(), Old->getType()) &&
635 "Should only be called if types are otherwise the same.");
636
637 QualType NewType = New->getType();
638 QualType OldType = Old->getType();
639
640 // We're only interested in pointers and references to functions, as well
641 // as pointers to member functions.
642 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
643 NewType = R->getPointeeType();
644 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
645 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
646 NewType = P->getPointeeType();
647 OldType = OldType->getAs<PointerType>()->getPointeeType();
648 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
649 NewType = M->getPointeeType();
650 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
651 }
652
653 if (!NewType->isFunctionProtoType())
654 return;
655
656 // There's lots of special cases for functions. For function pointers, system
657 // libraries are hopefully not as broken so that we don't need these
658 // workarounds.
659 if (CheckEquivalentExceptionSpec(
660 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
661 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
662 New->setInvalidDecl();
663 }
664}
665
Chris Lattner199abbc2008-04-08 05:04:30 +0000666/// CheckCXXDefaultArguments - Verify that the default arguments for a
667/// function declaration are well-formed according to C++
668/// [dcl.fct.default].
669void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
670 unsigned NumParams = FD->getNumParams();
671 unsigned p;
672
673 // Find first parameter with a default argument
674 for (p = 0; p < NumParams; ++p) {
675 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +0000676 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000677 break;
678 }
679
680 // C++ [dcl.fct.default]p4:
681 // In a given function declaration, all parameters
682 // subsequent to a parameter with a default argument shall
683 // have default arguments supplied in this or previous
684 // declarations. A default argument shall not be redefined
685 // by a later declaration (not even to the same value).
686 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000687 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000688 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000689 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000690 if (Param->isInvalidDecl())
691 /* We already complained about this parameter. */;
692 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000693 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000694 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000695 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000696 else
Mike Stump11289f42009-09-09 15:08:12 +0000697 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000698 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000699
Chris Lattner199abbc2008-04-08 05:04:30 +0000700 LastMissingDefaultArg = p;
701 }
702 }
703
704 if (LastMissingDefaultArg > 0) {
705 // Some default arguments were missing. Clear out all of the
706 // default arguments up to (and including) the last missing
707 // default argument, so that we leave the function parameters
708 // in a semantically valid state.
709 for (p = 0; p <= LastMissingDefaultArg; ++p) {
710 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000711 if (Param->hasDefaultArg()) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000712 Param->setDefaultArg(nullptr);
Chris Lattner199abbc2008-04-08 05:04:30 +0000713 }
714 }
715 }
716}
Douglas Gregor556877c2008-04-13 21:30:24 +0000717
Richard Smitheb3c10c2011-10-01 02:31:28 +0000718// CheckConstexprParameterTypes - Check whether a function's parameter types
719// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +0000720// diagnostic and return false.
721static bool CheckConstexprParameterTypes(Sema &SemaRef,
722 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000723 unsigned ArgIndex = 0;
724 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +0000725 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
726 e = FT->param_type_end();
727 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000728 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
729 SourceLocation ParamLoc = PD->getLocation();
730 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000731 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000732 diag::err_constexpr_non_literal_param,
733 ArgIndex+1, PD->getSourceRange(),
734 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000735 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000736 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000737 return true;
738}
739
740/// \brief Get diagnostic %select index for tag kind for
741/// record diagnostic message.
742/// WARNING: Indexes apply to particular diagnostics only!
743///
744/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +0000745static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +0000746 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +0000747 case TTK_Struct: return 0;
748 case TTK_Interface: return 1;
749 case TTK_Class: return 2;
750 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +0000751 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000752}
753
754// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
755// the requirements of a constexpr function definition or a constexpr
756// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +0000757// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000758//
Richard Smith3607ffe2012-02-13 03:54:03 +0000759// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
760bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +0000761 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
762 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000763 // C++11 [dcl.constexpr]p4:
764 // The definition of a constexpr constructor shall satisfy the following
765 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000766 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +0000767 const CXXRecordDecl *RD = MD->getParent();
768 if (RD->getNumVBases()) {
769 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
770 << isa<CXXConstructorDecl>(NewFD)
771 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Aaron Ballman445a9392014-03-13 16:15:17 +0000772 for (const auto &I : RD->vbases())
773 Diag(I.getLocStart(),
774 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000775 return false;
776 }
Richard Smith7971b692012-01-13 04:54:00 +0000777 }
778
779 if (!isa<CXXConstructorDecl>(NewFD)) {
780 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000781 // The definition of a constexpr function shall satisfy the following
782 // constraints:
783 // - it shall not be virtual;
784 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
785 if (Method && Method->isVirtual()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000786 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000787
Richard Smith3607ffe2012-02-13 03:54:03 +0000788 // If it's not obvious why this function is virtual, find an overridden
789 // function which uses the 'virtual' keyword.
790 const CXXMethodDecl *WrittenVirtual = Method;
791 while (!WrittenVirtual->isVirtualAsWritten())
792 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
793 if (WrittenVirtual != Method)
794 Diag(WrittenVirtual->getLocation(),
795 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000796 return false;
797 }
798
799 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +0000800 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000801 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000802 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000803 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000804 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000805 }
806
Richard Smith7971b692012-01-13 04:54:00 +0000807 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +0000808 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +0000809 return false;
810
Richard Smitheb3c10c2011-10-01 02:31:28 +0000811 return true;
812}
813
814/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +0000815/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000816///
Richard Smithd9f663b2013-04-22 15:31:51 +0000817/// \return true if the body is OK (maybe only as an extension), false if we
818/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000819static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +0000820 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
821 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000822 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
823 // contain only
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000824 for (const auto *DclIt : DS->decls()) {
825 switch (DclIt->getKind()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000826 case Decl::StaticAssert:
827 case Decl::Using:
828 case Decl::UsingShadow:
829 case Decl::UsingDirective:
830 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +0000831 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000832 // - static_assert-declarations
833 // - using-declarations,
834 // - using-directives,
835 continue;
836
837 case Decl::Typedef:
838 case Decl::TypeAlias: {
839 // - typedef declarations and alias-declarations that do not define
840 // classes or enumerations,
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000841 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000842 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
843 // Don't allow variably-modified types in constexpr functions.
844 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
845 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
846 << TL.getSourceRange() << TL.getType()
847 << isa<CXXConstructorDecl>(Dcl);
848 return false;
849 }
850 continue;
851 }
852
853 case Decl::Enum:
854 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +0000855 // C++1y allows types to be defined, not just declared.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000856 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smithd9f663b2013-04-22 15:31:51 +0000857 SemaRef.Diag(DS->getLocStart(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000858 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +0000859 ? diag::warn_cxx11_compat_constexpr_type_definition
860 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000861 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000862 continue;
863
Richard Smithd9f663b2013-04-22 15:31:51 +0000864 case Decl::EnumConstant:
865 case Decl::IndirectField:
866 case Decl::ParmVar:
867 // These can only appear with other declarations which are banned in
868 // C++11 and permitted in C++1y, so ignore them.
869 continue;
870
871 case Decl::Var: {
872 // C++1y [dcl.constexpr]p3 allows anything except:
873 // a definition of a variable of non-literal type or of static or
874 // thread storage duration or for which no initialization is performed.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000875 const auto *VD = cast<VarDecl>(DclIt);
Richard Smithd9f663b2013-04-22 15:31:51 +0000876 if (VD->isThisDeclarationADefinition()) {
877 if (VD->isStaticLocal()) {
878 SemaRef.Diag(VD->getLocation(),
879 diag::err_constexpr_local_var_static)
880 << isa<CXXConstructorDecl>(Dcl)
881 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
882 return false;
883 }
Richard Smith3da88fa2013-04-26 14:36:30 +0000884 if (!VD->getType()->isDependentType() &&
885 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +0000886 VD->getLocation(), VD->getType(),
887 diag::err_constexpr_local_var_non_literal_type,
888 isa<CXXConstructorDecl>(Dcl)))
889 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +0000890 if (!VD->getType()->isDependentType() &&
891 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000892 SemaRef.Diag(VD->getLocation(),
893 diag::err_constexpr_local_var_no_init)
894 << isa<CXXConstructorDecl>(Dcl);
895 return false;
896 }
897 }
898 SemaRef.Diag(VD->getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000899 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +0000900 ? diag::warn_cxx11_compat_constexpr_local_var
901 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000902 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +0000903 continue;
904 }
905
906 case Decl::NamespaceAlias:
907 case Decl::Function:
908 // These are disallowed in C++11 and permitted in C++1y. Allow them
909 // everywhere as an extension.
910 if (!Cxx1yLoc.isValid())
911 Cxx1yLoc = DS->getLocStart();
912 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000913
914 default:
915 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
916 << isa<CXXConstructorDecl>(Dcl);
917 return false;
918 }
919 }
920
921 return true;
922}
923
924/// Check that the given field is initialized within a constexpr constructor.
925///
926/// \param Dcl The constexpr constructor being checked.
927/// \param Field The field being checked. This may be a member of an anonymous
928/// struct or union nested within the class being checked.
929/// \param Inits All declarations, including anonymous struct/union members and
930/// indirect members, for which any initialization was provided.
931/// \param Diagnosed Set to true if an error is produced.
932static void CheckConstexprCtorInitializer(Sema &SemaRef,
933 const FunctionDecl *Dcl,
934 FieldDecl *Field,
935 llvm::SmallSet<Decl*, 16> &Inits,
936 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +0000937 if (Field->isInvalidDecl())
938 return;
939
Douglas Gregor556e5862011-10-10 17:22:13 +0000940 if (Field->isUnnamedBitfield())
941 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +0000942
Richard Smithab44d5b2013-12-10 08:25:00 +0000943 // Anonymous unions with no variant members and empty anonymous structs do not
944 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
945 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +0000946 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +0000947 (Field->getType()->isUnionType()
948 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
949 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +0000950 return;
951
Richard Smitheb3c10c2011-10-01 02:31:28 +0000952 if (!Inits.count(Field)) {
953 if (!Diagnosed) {
954 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
955 Diagnosed = true;
956 }
957 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
958 } else if (Field->isAnonymousStructOrUnion()) {
959 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000960 for (auto *I : RD->fields())
Richard Smitheb3c10c2011-10-01 02:31:28 +0000961 // If an anonymous union contains an anonymous struct of which any member
962 // is initialized, all members must be initialized.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000963 if (!RD->isUnion() || Inits.count(I))
964 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000965 }
966}
967
Richard Smithd9f663b2013-04-22 15:31:51 +0000968/// Check the provided statement is allowed in a constexpr function
969/// definition.
970static bool
971CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +0000972 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +0000973 SourceLocation &Cxx1yLoc) {
974 // - its function-body shall be [...] a compound-statement that contains only
975 switch (S->getStmtClass()) {
976 case Stmt::NullStmtClass:
977 // - null statements,
978 return true;
979
980 case Stmt::DeclStmtClass:
981 // - static_assert-declarations
982 // - using-declarations,
983 // - using-directives,
984 // - typedef declarations and alias-declarations that do not define
985 // classes or enumerations,
986 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
987 return false;
988 return true;
989
990 case Stmt::ReturnStmtClass:
991 // - and exactly one return statement;
992 if (isa<CXXConstructorDecl>(Dcl)) {
993 // C++1y allows return statements in constexpr constructors.
994 if (!Cxx1yLoc.isValid())
995 Cxx1yLoc = S->getLocStart();
996 return true;
997 }
998
999 ReturnStmts.push_back(S->getLocStart());
1000 return true;
1001
1002 case Stmt::CompoundStmtClass: {
1003 // C++1y allows compound-statements.
1004 if (!Cxx1yLoc.isValid())
1005 Cxx1yLoc = S->getLocStart();
1006
1007 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001008 for (auto *BodyIt : CompStmt->body()) {
1009 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001010 Cxx1yLoc))
1011 return false;
1012 }
1013 return true;
1014 }
1015
1016 case Stmt::AttributedStmtClass:
1017 if (!Cxx1yLoc.isValid())
1018 Cxx1yLoc = S->getLocStart();
1019 return true;
1020
1021 case Stmt::IfStmtClass: {
1022 // C++1y allows if-statements.
1023 if (!Cxx1yLoc.isValid())
1024 Cxx1yLoc = S->getLocStart();
1025
1026 IfStmt *If = cast<IfStmt>(S);
1027 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1028 Cxx1yLoc))
1029 return false;
1030 if (If->getElse() &&
1031 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1032 Cxx1yLoc))
1033 return false;
1034 return true;
1035 }
1036
1037 case Stmt::WhileStmtClass:
1038 case Stmt::DoStmtClass:
1039 case Stmt::ForStmtClass:
1040 case Stmt::CXXForRangeStmtClass:
1041 case Stmt::ContinueStmtClass:
1042 // C++1y allows all of these. We don't allow them as extensions in C++11,
1043 // because they don't make sense without variable mutation.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001044 if (!SemaRef.getLangOpts().CPlusPlus14)
Richard Smithd9f663b2013-04-22 15:31:51 +00001045 break;
1046 if (!Cxx1yLoc.isValid())
1047 Cxx1yLoc = S->getLocStart();
1048 for (Stmt::child_range Children = S->children(); Children; ++Children)
1049 if (*Children &&
1050 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1051 Cxx1yLoc))
1052 return false;
1053 return true;
1054
1055 case Stmt::SwitchStmtClass:
1056 case Stmt::CaseStmtClass:
1057 case Stmt::DefaultStmtClass:
1058 case Stmt::BreakStmtClass:
1059 // C++1y allows switch-statements, and since they don't need variable
1060 // mutation, we can reasonably allow them in C++11 as an extension.
1061 if (!Cxx1yLoc.isValid())
1062 Cxx1yLoc = S->getLocStart();
1063 for (Stmt::child_range Children = S->children(); Children; ++Children)
1064 if (*Children &&
1065 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1066 Cxx1yLoc))
1067 return false;
1068 return true;
1069
1070 default:
1071 if (!isa<Expr>(S))
1072 break;
1073
1074 // C++1y allows expression-statements.
1075 if (!Cxx1yLoc.isValid())
1076 Cxx1yLoc = S->getLocStart();
1077 return true;
1078 }
1079
1080 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1081 << isa<CXXConstructorDecl>(Dcl);
1082 return false;
1083}
1084
Richard Smitheb3c10c2011-10-01 02:31:28 +00001085/// Check the body for the given constexpr function declaration only contains
1086/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1087///
1088/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001089bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001090 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001091 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001092 // The definition of a constexpr function shall satisfy the following
1093 // constraints: [...]
1094 // - its function-body shall be = delete, = default, or a
1095 // compound-statement
1096 //
Richard Smith74388b42012-02-04 00:33:54 +00001097 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001098 // In the definition of a constexpr constructor, [...]
1099 // - its function-body shall not be a function-try-block;
1100 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1101 << isa<CXXConstructorDecl>(Dcl);
1102 return false;
1103 }
1104
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001105 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001106
1107 // - its function-body shall be [...] a compound-statement that contains only
1108 // [... list of cases ...]
1109 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1110 SourceLocation Cxx1yLoc;
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001111 for (auto *BodyIt : CompBody->body()) {
1112 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smithd9f663b2013-04-22 15:31:51 +00001113 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001114 }
1115
Richard Smithd9f663b2013-04-22 15:31:51 +00001116 if (Cxx1yLoc.isValid())
1117 Diag(Cxx1yLoc,
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001118 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001119 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1120 : diag::ext_constexpr_body_invalid_stmt)
1121 << isa<CXXConstructorDecl>(Dcl);
1122
Richard Smitheb3c10c2011-10-01 02:31:28 +00001123 if (const CXXConstructorDecl *Constructor
1124 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1125 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001126 // DR1359:
1127 // - every non-variant non-static data member and base class sub-object
1128 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001129 // DR1460:
1130 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001131 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001132 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001133 if (Constructor->getNumCtorInitializers() == 0 &&
1134 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001135 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1136 return false;
1137 }
Richard Smithf368fb42011-10-10 16:38:04 +00001138 } else if (!Constructor->isDependentContext() &&
1139 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001140 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1141
1142 // Skip detailed checking if we have enough initializers, and we would
1143 // allow at most one initializer per member.
1144 bool AnyAnonStructUnionMembers = false;
1145 unsigned Fields = 0;
1146 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1147 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001148 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001149 AnyAnonStructUnionMembers = true;
1150 break;
1151 }
1152 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001153 // DR1460:
1154 // - if the class is a union-like class, but is not a union, for each of
1155 // its anonymous union members having variant members, exactly one of
1156 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001157 if (AnyAnonStructUnionMembers ||
1158 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1159 // Check initialization of non-static data members. Base classes are
1160 // always initialized so do not need to be checked. Dependent bases
1161 // might not have initializers in the member initializer list.
1162 llvm::SmallSet<Decl*, 16> Inits;
Aaron Ballman0ad78302014-03-13 17:34:31 +00001163 for (const auto *I: Constructor->inits()) {
1164 if (FieldDecl *FD = I->getMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001165 Inits.insert(FD);
Aaron Ballman0ad78302014-03-13 17:34:31 +00001166 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001167 Inits.insert(ID->chain_begin(), ID->chain_end());
1168 }
1169
1170 bool Diagnosed = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001171 for (auto *I : RD->fields())
1172 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001173 if (Diagnosed)
1174 return false;
1175 }
1176 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001177 } else {
1178 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001179 // C++1y doesn't require constexpr functions to contain a 'return'
Richard Smith06ffb452014-04-22 23:14:23 +00001180 // statement. We still do, unless the return type might be void, because
Richard Smithd9f663b2013-04-22 15:31:51 +00001181 // otherwise if there's no return statement, the function cannot
1182 // be used in a core constant expression.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001183 bool OK = getLangOpts().CPlusPlus14 &&
Richard Smith06ffb452014-04-22 23:14:23 +00001184 (Dcl->getReturnType()->isVoidType() ||
1185 Dcl->getReturnType()->isDependentType());
Richard Smithd9f663b2013-04-22 15:31:51 +00001186 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00001187 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1188 : diag::err_constexpr_body_no_return);
1189 return OK;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001190 }
1191 if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001192 Diag(ReturnStmts.back(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001193 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001194 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1195 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001196 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1197 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001198 }
1199 }
1200
Richard Smith74388b42012-02-04 00:33:54 +00001201 // C++11 [dcl.constexpr]p5:
1202 // if no function argument values exist such that the function invocation
1203 // substitution would produce a constant expression, the program is
1204 // ill-formed; no diagnostic required.
1205 // C++11 [dcl.constexpr]p3:
1206 // - every constructor call and implicit conversion used in initializing the
1207 // return value shall be one of those allowed in a constant expression.
1208 // C++11 [dcl.constexpr]p4:
1209 // - every constructor involved in initializing non-static data members and
1210 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001211 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00001212 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00001213 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00001214 << isa<CXXConstructorDecl>(Dcl);
1215 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1216 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00001217 // Don't return false here: we allow this for compatibility in
1218 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00001219 }
1220
Richard Smitheb3c10c2011-10-01 02:31:28 +00001221 return true;
1222}
1223
Douglas Gregor61956c42008-10-31 09:07:45 +00001224/// isCurrentClassName - Determine whether the identifier II is the
1225/// name of the class type currently being defined. In the case of
1226/// nested classes, this will only return true if II is the name of
1227/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001228bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1229 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001230 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00001231
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001232 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00001233 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00001234 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001235 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1236 } else
1237 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1238
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00001239 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00001240 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00001241 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00001242}
1243
Richard Smithfb8b7b92013-10-15 00:00:26 +00001244/// \brief Determine whether the identifier II is a typo for the name of
1245/// the class type currently being defined. If so, update it to the identifier
1246/// that should have been used.
1247bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1248 assert(getLangOpts().CPlusPlus && "No class names in C!");
1249
1250 if (!getLangOpts().SpellChecking)
1251 return false;
1252
1253 CXXRecordDecl *CurDecl;
1254 if (SS && SS->isSet() && !SS->isInvalid()) {
1255 DeclContext *DC = computeDeclContext(*SS, true);
1256 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1257 } else
1258 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1259
1260 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1261 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1262 < II->getLength()) {
1263 II = CurDecl->getIdentifier();
1264 return true;
1265 }
1266
1267 return false;
1268}
1269
Douglas Gregordc974572012-11-10 07:24:09 +00001270/// \brief Determine whether the given class is a base class of the given
1271/// class, including looking at dependent bases.
1272static bool findCircularInheritance(const CXXRecordDecl *Class,
1273 const CXXRecordDecl *Current) {
1274 SmallVector<const CXXRecordDecl*, 8> Queue;
1275
1276 Class = Class->getCanonicalDecl();
1277 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001278 for (const auto &I : Current->bases()) {
1279 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregordc974572012-11-10 07:24:09 +00001280 if (!Base)
1281 continue;
1282
1283 Base = Base->getDefinition();
1284 if (!Base)
1285 continue;
1286
1287 if (Base->getCanonicalDecl() == Class)
1288 return true;
1289
1290 Queue.push_back(Base);
1291 }
1292
1293 if (Queue.empty())
1294 return false;
1295
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001296 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00001297 }
1298
1299 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00001300}
1301
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00001302/// \brief Perform propagation of DLL attributes from a derived class to a
1303/// templated base class for MS compatibility.
1304static void propagateDLLAttrToBaseClassTemplate(
1305 Sema &S, CXXRecordDecl *Class, Attr *ClassAttr,
1306 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
1307 if (getDLLAttr(
1308 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
1309 // If the base class template has a DLL attribute, don't try to change it.
1310 return;
1311 }
1312
1313 if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
1314 // If the base class is not already specialized, we can do the propagation.
1315 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
1316 NewAttr->setInherited(true);
1317 BaseTemplateSpec->addAttr(NewAttr);
1318 return;
1319 }
1320
1321 bool DifferentAttribute = false;
1322 if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) {
1323 if (!SpecializationAttr->isInherited()) {
1324 // The template has previously been specialized or instantiated with an
1325 // explicit attribute. We should not try to change it.
1326 return;
1327 }
1328 if (SpecializationAttr->getKind() == ClassAttr->getKind()) {
1329 // The specialization already has the right attribute.
1330 return;
1331 }
1332 DifferentAttribute = true;
1333 }
1334
1335 // The template was previously instantiated or explicitly specialized without
1336 // a dll attribute, or the template was previously instantiated with a
1337 // different inherited attribute. It's too late for us to change the
1338 // attribute, so warn that this is unsupported.
1339 S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
1340 << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute;
1341 S.Diag(ClassAttr->getLocation(), diag::note_attribute);
1342 if (BaseTemplateSpec->isExplicitSpecialization()) {
1343 S.Diag(BaseTemplateSpec->getLocation(),
1344 diag::note_template_class_explicit_specialization_was_here)
1345 << BaseTemplateSpec;
1346 } else {
1347 S.Diag(BaseTemplateSpec->getPointOfInstantiation(),
1348 diag::note_template_class_instantiation_was_here)
1349 << BaseTemplateSpec;
1350 }
1351}
1352
Mike Stump11289f42009-09-09 15:08:12 +00001353/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001354///
1355/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1356/// and returns NULL otherwise.
1357CXXBaseSpecifier *
1358Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1359 SourceRange SpecifierRange,
1360 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001361 TypeSourceInfo *TInfo,
1362 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001363 QualType BaseType = TInfo->getType();
1364
Douglas Gregor463421d2009-03-03 04:44:36 +00001365 // C++ [class.union]p1:
1366 // A union shall not have base classes.
1367 if (Class->isUnion()) {
1368 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1369 << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001370 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001371 }
1372
Douglas Gregor752a5952011-01-03 22:36:02 +00001373 if (EllipsisLoc.isValid() &&
1374 !TInfo->getType()->containsUnexpandedParameterPack()) {
1375 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1376 << TInfo->getTypeLoc().getSourceRange();
1377 EllipsisLoc = SourceLocation();
1378 }
Douglas Gregor62004702012-11-10 01:18:17 +00001379
1380 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1381
1382 if (BaseType->isDependentType()) {
1383 // Make sure that we don't have circular inheritance among our dependent
1384 // bases. For non-dependent bases, the check for completeness below handles
1385 // this.
1386 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1387 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1388 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00001389 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00001390 Diag(BaseLoc, diag::err_circular_inheritance)
1391 << BaseType << Context.getTypeDeclType(Class);
1392
1393 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1394 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1395 << BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00001396
1397 return nullptr;
Douglas Gregor62004702012-11-10 01:18:17 +00001398 }
1399 }
1400
Mike Stump11289f42009-09-09 15:08:12 +00001401 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001402 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001403 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00001404 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001405
1406 // Base specifiers must be record types.
1407 if (!BaseType->isRecordType()) {
1408 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001409 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001410 }
1411
1412 // C++ [class.union]p1:
1413 // A union shall not be used as a base class.
1414 if (BaseType->isUnionType()) {
1415 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001416 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001417 }
1418
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00001419 // For the MS ABI, propagate DLL attributes to base class templates.
1420 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1421 if (Attr *ClassAttr = getDLLAttr(Class)) {
1422 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1423 BaseType->getAsCXXRecordDecl())) {
1424 propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr,
1425 BaseTemplate, BaseLoc);
1426 }
1427 }
1428 }
1429
Douglas Gregor463421d2009-03-03 04:44:36 +00001430 // C++ [class.derived]p2:
1431 // The class-name in a base-specifier shall not be an incompletely
1432 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001433 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001434 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00001435 Class->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00001436 return nullptr;
John McCall3696dcb2010-08-17 07:23:57 +00001437 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001438
Eli Friedmanc96d4962009-08-15 21:55:26 +00001439 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001440 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001441 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001442 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001443 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00001444 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00001445 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001446
David Majnemer9b1754d2013-11-02 12:00:36 +00001447 // A class which contains a flexible array member is not suitable for use as a
1448 // base class:
1449 // - If the layout determines that a base comes before another base,
1450 // the flexible array member would index into the subsequent base.
1451 // - If the layout determines that base comes before the derived class,
1452 // the flexible array member would index into the derived class.
1453 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1454 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1455 << CXXBaseDecl->getDeclName();
Craig Topperc3ec1492014-05-26 06:22:03 +00001456 return nullptr;
David Majnemer9b1754d2013-11-02 12:00:36 +00001457 }
1458
Anders Carlsson65c76d32011-03-25 14:55:14 +00001459 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00001460 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00001461 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00001462 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00001463 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00001464 << CXXBaseDecl->getDeclName()
1465 << FA->isSpelledAsSealed();
Alp Toker2afa8782014-05-28 12:20:14 +00001466 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1467 << CXXBaseDecl->getDeclName() << FA->getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00001468 return nullptr;
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001469 }
1470
John McCall3696dcb2010-08-17 07:23:57 +00001471 if (BaseDecl->isInvalidDecl())
1472 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00001473
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001474 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001475 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001476 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001477 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001478}
1479
Douglas Gregor556877c2008-04-13 21:30:24 +00001480/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1481/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001482/// example:
1483/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001484/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001485BaseResult
John McCall48871652010-08-21 09:40:31 +00001486Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00001487 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00001488 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001489 ParsedType basetype, SourceLocation BaseLoc,
1490 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001491 if (!classdecl)
1492 return true;
1493
Douglas Gregorc40290e2009-03-09 23:48:35 +00001494 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001495 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001496 if (!Class)
1497 return true;
1498
David Majnemer5ef4fe72014-06-13 06:43:46 +00001499 // We haven't yet attached the base specifiers.
1500 Class->setIsParsingBaseSpecifiers();
1501
Richard Smith4c96e992013-02-19 23:47:15 +00001502 // We do not support any C++11 attributes on base-specifiers yet.
1503 // Diagnose any attributes we see.
1504 if (!Attributes.empty()) {
1505 for (AttributeList *Attr = Attributes.getList(); Attr;
1506 Attr = Attr->getNext()) {
1507 if (Attr->isInvalid() ||
1508 Attr->getKind() == AttributeList::IgnoredAttribute)
1509 continue;
1510 Diag(Attr->getLoc(),
1511 Attr->getKind() == AttributeList::UnknownAttribute
1512 ? diag::warn_unknown_attribute_ignored
1513 : diag::err_base_specifier_attribute)
1514 << Attr->getName();
1515 }
1516 }
1517
Craig Topperc3ec1492014-05-26 06:22:03 +00001518 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001519 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001520
Douglas Gregor752a5952011-01-03 22:36:02 +00001521 if (EllipsisLoc.isInvalid() &&
1522 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001523 UPPC_BaseType))
1524 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001525
Douglas Gregor463421d2009-03-03 04:44:36 +00001526 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001527 Virtual, Access, TInfo,
1528 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001529 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001530 else
1531 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001532
Douglas Gregor463421d2009-03-03 04:44:36 +00001533 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001534}
Douglas Gregor556877c2008-04-13 21:30:24 +00001535
Douglas Gregor463421d2009-03-03 04:44:36 +00001536/// \brief Performs the actual work of attaching the given base class
1537/// specifiers to a C++ class.
1538bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1539 unsigned NumBases) {
1540 if (NumBases == 0)
1541 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001542
1543 // Used to keep track of which base types we have already seen, so
1544 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001545 // that the key is always the unqualified canonical type of the base
1546 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001547 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1548
1549 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001550 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001551 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001552 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001553 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001554 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001555 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001556
1557 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1558 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00001559 // C++ [class.mi]p3:
1560 // A class shall not be specified as a direct base class of a
1561 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001562 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001563 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001564 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001565 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001566
1567 // Delete the duplicate base class specifier; we're going to
1568 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001569 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001570
1571 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001572 } else {
1573 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001574 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00001575 Bases[NumGoodBases++] = Bases[idx];
John McCalldb632ac2012-09-25 07:32:39 +00001576 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1577 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1578 if (Class->isInterface() &&
1579 (!RD->isInterface() ||
1580 KnownBase->getAccessSpecifier() != AS_public)) {
1581 // The Microsoft extension __interface does not permit bases that
1582 // are not themselves public interfaces.
1583 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1584 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1585 << RD->getSourceRange();
1586 Invalid = true;
1587 }
1588 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00001589 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00001590 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001591 }
1592 }
1593
1594 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001595 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001596
1597 // Delete the remaining (good) base class specifiers, since their
1598 // data has been copied into the CXXRecordDecl.
1599 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001600 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001601
1602 return Invalid;
1603}
1604
1605/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1606/// class, after checking whether there are any duplicate base
1607/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001608void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001609 unsigned NumBases) {
1610 if (!ClassDecl || !Bases || !NumBases)
1611 return;
1612
1613 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelme3cea802013-07-22 05:04:01 +00001614 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001615}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001616
Douglas Gregor36d1b142009-10-06 17:59:45 +00001617/// \brief Determine whether the type \p Derived is a C++ class that is
1618/// derived from the type \p Base.
1619bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001620 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001621 return false;
John McCalle78aac42010-03-10 03:28:59 +00001622
Douglas Gregor45bb4832013-03-26 23:36:30 +00001623 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001624 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001625 return false;
1626
Douglas Gregor45bb4832013-03-26 23:36:30 +00001627 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001628 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001629 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00001630
1631 // If either the base or the derived type is invalid, don't try to
1632 // check whether one is derived from the other.
1633 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1634 return false;
1635
John McCall67da35c2010-02-04 22:26:26 +00001636 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1637 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001638}
1639
1640/// \brief Determine whether the type \p Derived is a C++ class that is
1641/// derived from the type \p Base.
1642bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001643 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001644 return false;
1645
Douglas Gregor45bb4832013-03-26 23:36:30 +00001646 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001647 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001648 return false;
1649
Douglas Gregor45bb4832013-03-26 23:36:30 +00001650 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001651 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001652 return false;
1653
Douglas Gregor36d1b142009-10-06 17:59:45 +00001654 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1655}
1656
Anders Carlssona70cff62010-04-24 19:06:50 +00001657void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001658 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001659 assert(BasePathArray.empty() && "Base path array must be empty!");
1660 assert(Paths.isRecordingPaths() && "Must record paths!");
1661
1662 const CXXBasePath &Path = Paths.front();
1663
1664 // We first go backward and check if we have a virtual base.
1665 // FIXME: It would be better if CXXBasePath had the base specifier for
1666 // the nearest virtual base.
1667 unsigned Start = 0;
1668 for (unsigned I = Path.size(); I != 0; --I) {
1669 if (Path[I - 1].Base->isVirtual()) {
1670 Start = I - 1;
1671 break;
1672 }
1673 }
1674
1675 // Now add all bases.
1676 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001677 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001678}
1679
Douglas Gregor88d292c2010-05-13 16:44:06 +00001680/// \brief Determine whether the given base path includes a virtual
1681/// base class.
John McCallcf142162010-08-07 06:22:56 +00001682bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1683 for (CXXCastPath::const_iterator B = BasePath.begin(),
1684 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +00001685 B != BEnd; ++B)
1686 if ((*B)->isVirtual())
1687 return true;
1688
1689 return false;
1690}
1691
Douglas Gregor36d1b142009-10-06 17:59:45 +00001692/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1693/// conversion (where Derived and Base are class types) is
1694/// well-formed, meaning that the conversion is unambiguous (and
1695/// that all of the base classes are accessible). Returns true
1696/// and emits a diagnostic if the code is ill-formed, returns false
1697/// otherwise. Loc is the location where this routine should point to
1698/// if there is an error, and Range is the source range to highlight
1699/// if there is an error.
1700bool
1701Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001702 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001703 unsigned AmbigiousBaseConvID,
1704 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001705 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001706 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001707 // First, determine whether the path from Derived to Base is
1708 // ambiguous. This is slightly more expensive than checking whether
1709 // the Derived to Base conversion exists, because here we need to
1710 // explore multiple paths to determine if there is an ambiguity.
1711 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1712 /*DetectVirtual=*/false);
1713 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1714 assert(DerivationOkay &&
1715 "Can only be used with a derived-to-base conversion");
1716 (void)DerivationOkay;
1717
1718 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001719 if (InaccessibleBaseID) {
1720 // Check that the base class can be accessed.
1721 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1722 InaccessibleBaseID)) {
1723 case AR_inaccessible:
1724 return true;
1725 case AR_accessible:
1726 case AR_dependent:
1727 case AR_delayed:
1728 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001729 }
John McCall5b0829a2010-02-10 09:31:12 +00001730 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001731
1732 // Build a base path if necessary.
1733 if (BasePath)
1734 BuildBasePathArray(Paths, *BasePath);
1735 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001736 }
1737
David Majnemer626032f2013-06-22 06:43:58 +00001738 if (AmbigiousBaseConvID) {
1739 // We know that the derived-to-base conversion is ambiguous, and
1740 // we're going to produce a diagnostic. Perform the derived-to-base
1741 // search just one more time to compute all of the possible paths so
1742 // that we can print them out. This is more expensive than any of
1743 // the previous derived-to-base checks we've done, but at this point
1744 // performance isn't as much of an issue.
1745 Paths.clear();
1746 Paths.setRecordingPaths(true);
1747 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1748 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1749 (void)StillOkay;
1750
1751 // Build up a textual representation of the ambiguous paths, e.g.,
1752 // D -> B -> A, that will be used to illustrate the ambiguous
1753 // conversions in the diagnostic. We only print one of the paths
1754 // to each base class subobject.
1755 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1756
1757 Diag(Loc, AmbigiousBaseConvID)
1758 << Derived << Base << PathDisplayStr << Range << Name;
1759 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00001760 return true;
1761}
1762
1763bool
1764Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001765 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001766 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001767 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001768 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001769 IgnoreAccess ? 0
1770 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001771 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001772 Loc, Range, DeclarationName(),
1773 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001774}
1775
1776
1777/// @brief Builds a string representing ambiguous paths from a
1778/// specific derived class to different subobjects of the same base
1779/// class.
1780///
1781/// This function builds a string that can be used in error messages
1782/// to show the different paths that one can take through the
1783/// inheritance hierarchy to go from the derived class to different
1784/// subobjects of a base class. The result looks something like this:
1785/// @code
1786/// struct D -> struct B -> struct A
1787/// struct D -> struct C -> struct A
1788/// @endcode
1789std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1790 std::string PathDisplayStr;
1791 std::set<unsigned> DisplayedPaths;
1792 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1793 Path != Paths.end(); ++Path) {
1794 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1795 // We haven't displayed a path to this particular base
1796 // class subobject yet.
1797 PathDisplayStr += "\n ";
1798 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1799 for (CXXBasePath::const_iterator Element = Path->begin();
1800 Element != Path->end(); ++Element)
1801 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1802 }
1803 }
1804
1805 return PathDisplayStr;
1806}
1807
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001808//===----------------------------------------------------------------------===//
1809// C++ class member Handling
1810//===----------------------------------------------------------------------===//
1811
Abramo Bagnarad7340582010-06-05 05:09:32 +00001812/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001813bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1814 SourceLocation ASLoc,
1815 SourceLocation ColonLoc,
1816 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001817 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001818 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001819 ASLoc, ColonLoc);
1820 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001821 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001822}
1823
Richard Smith18f07db2012-08-06 03:25:17 +00001824/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001825void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00001826 if (D->isInvalidDecl())
1827 return;
1828
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001829 // We only care about "override" and "final" declarations.
1830 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1831 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00001832
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001833 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001834
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001835 // We can't check dependent instance methods.
1836 if (MD && MD->isInstance() &&
1837 (MD->getParent()->hasAnyDependentBases() ||
1838 MD->getType()->isDependentType()))
1839 return;
1840
1841 if (MD && !MD->isVirtual()) {
1842 // If we have a non-virtual method, check if if hides a virtual method.
1843 // (In that case, it's most likely the method has the wrong type.)
1844 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1845 FindHiddenVirtualMethods(MD, OverloadedMethods);
1846
1847 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001848 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1849 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001850 diag::override_keyword_hides_virtual_member_function)
1851 << "override" << (OverloadedMethods.size() > 1);
1852 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001853 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001854 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00001855 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1856 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00001857 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001858 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1859 MD->setInvalidDecl();
1860 return;
1861 }
1862 // Fall through into the general case diagnostic.
1863 // FIXME: We might want to attempt typo correction here.
1864 }
1865
1866 if (!MD || !MD->isVirtual()) {
1867 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1868 Diag(OA->getLocation(),
1869 diag::override_keyword_only_allowed_on_virtual_member_functions)
1870 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1871 D->dropAttr<OverrideAttr>();
1872 }
1873 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1874 Diag(FA->getLocation(),
1875 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00001876 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1877 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001878 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00001879 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001880 return;
1881 }
Richard Smith18f07db2012-08-06 03:25:17 +00001882
Richard Smith18f07db2012-08-06 03:25:17 +00001883 // C++11 [class.virtual]p5:
1884 // If a virtual function is marked with the virt-specifier override and
1885 // does not override a member function of a base class, the program is
1886 // ill-formed.
1887 bool HasOverriddenMethods =
1888 MD->begin_overridden_methods() != MD->end_overridden_methods();
1889 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1890 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1891 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00001892}
1893
Richard Smith18f07db2012-08-06 03:25:17 +00001894/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00001895/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00001896/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00001897bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1898 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00001899 FinalAttr *FA = Old->getAttr<FinalAttr>();
1900 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00001901 return false;
1902
1903 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00001904 << New->getDeclName()
1905 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00001906 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1907 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001908}
1909
Daniel Jasper0baec5492012-06-06 08:32:04 +00001910static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00001911 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1912 // FIXME: Destruction of ObjC lifetime types has side-effects.
1913 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1914 return !RD->isCompleteDefinition() ||
1915 !RD->hasTrivialDefaultConstructor() ||
1916 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00001917 return false;
1918}
1919
John McCall5e77d762013-04-16 07:28:30 +00001920static AttributeList *getMSPropertyAttr(AttributeList *list) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001921 for (AttributeList *it = list; it != nullptr; it = it->getNext())
John McCall5e77d762013-04-16 07:28:30 +00001922 if (it->isDeclspecPropertyAttribute())
1923 return it;
Craig Topperc3ec1492014-05-26 06:22:03 +00001924 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +00001925}
1926
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001927/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1928/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001929/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00001930/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1931/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001932NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001933Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001934 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001935 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00001936 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001937 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001938 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1939 DeclarationName Name = NameInfo.getName();
1940 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001941
1942 // For anonymous bitfields, the location should point to the type.
1943 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001944 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001945
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001946 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001947
John McCallb1cd7da2010-06-04 08:34:12 +00001948 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001949 assert(!DS.isFriendSpecified());
1950
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001951 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001952
John McCalldb632ac2012-09-25 07:32:39 +00001953 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1954 // The Microsoft extension __interface only permits public member functions
1955 // and prohibits constructors, destructors, operators, non-public member
1956 // functions, static methods and data members.
1957 unsigned InvalidDecl;
1958 bool ShowDeclName = true;
1959 if (!isFunc)
1960 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1961 else if (AS != AS_public)
1962 InvalidDecl = 2;
1963 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1964 InvalidDecl = 3;
1965 else switch (Name.getNameKind()) {
1966 case DeclarationName::CXXConstructorName:
1967 InvalidDecl = 4;
1968 ShowDeclName = false;
1969 break;
1970
1971 case DeclarationName::CXXDestructorName:
1972 InvalidDecl = 5;
1973 ShowDeclName = false;
1974 break;
1975
1976 case DeclarationName::CXXOperatorName:
1977 case DeclarationName::CXXConversionFunctionName:
1978 InvalidDecl = 6;
1979 break;
1980
1981 default:
1982 InvalidDecl = 0;
1983 break;
1984 }
1985
1986 if (InvalidDecl) {
1987 if (ShowDeclName)
1988 Diag(Loc, diag::err_invalid_member_in_interface)
1989 << (InvalidDecl-1) << Name;
1990 else
1991 Diag(Loc, diag::err_invalid_member_in_interface)
1992 << (InvalidDecl-1) << "";
Craig Topperc3ec1492014-05-26 06:22:03 +00001993 return nullptr;
John McCalldb632ac2012-09-25 07:32:39 +00001994 }
1995 }
1996
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001997 // C++ 9.2p6: A member shall not be declared to have automatic storage
1998 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001999 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2000 // data members and cannot be applied to names declared const or static,
2001 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002002 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00002003 case DeclSpec::SCS_unspecified:
2004 case DeclSpec::SCS_typedef:
2005 case DeclSpec::SCS_static:
2006 break;
2007 case DeclSpec::SCS_mutable:
2008 if (isFunc) {
2009 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00002010
Richard Smithb4a9e862013-04-12 22:46:28 +00002011 // FIXME: It would be nicer if the keyword was ignored only for this
2012 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002013 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00002014 }
2015 break;
2016 default:
2017 Diag(DS.getStorageClassSpecLoc(),
2018 diag::err_storageclass_invalid_for_member);
2019 D.getMutableDeclSpec().ClearStorageClassSpecs();
2020 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002021 }
2022
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002023 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2024 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00002025 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002026
David Blaikie35506f82013-01-30 01:22:18 +00002027 if (DS.isConstexprSpecified() && isInstField) {
2028 SemaDiagnosticBuilder B =
2029 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2030 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2031 if (InitStyle == ICIS_NoInit) {
Richard Smith82dce552014-04-14 21:00:40 +00002032 B << 0 << 0;
2033 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2034 B << FixItHint::CreateRemoval(ConstexprLoc);
2035 else {
2036 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2037 D.getMutableDeclSpec().ClearConstexprSpec();
2038 const char *PrevSpec;
2039 unsigned DiagID;
2040 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2041 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2042 (void)Failed;
2043 assert(!Failed && "Making a constexpr member const shouldn't fail");
2044 }
David Blaikie35506f82013-01-30 01:22:18 +00002045 } else {
2046 B << 1;
2047 const char *PrevSpec;
2048 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00002049 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002050 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2051 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00002052 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00002053 "This is the only DeclSpec that should fail to be applied");
2054 B << 1;
2055 } else {
2056 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2057 isInstField = false;
2058 }
2059 }
2060 }
2061
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002062 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00002063 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00002064 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002065
2066 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00002067 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002068 Diag(Loc, diag::err_bad_variable_name)
2069 << Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002070 return nullptr;
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002071 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002072
Benjamin Kramer365082d2012-05-19 16:34:46 +00002073 IdentifierInfo *II = Name.getAsIdentifierInfo();
2074
Douglas Gregor7c26c042011-09-21 14:40:46 +00002075 // Member field could not be with "template" keyword.
2076 // So TemplateParameterLists should be empty in this case.
2077 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002078 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002079 if (TemplateParams->size()) {
2080 // There is no such thing as a member field template.
2081 Diag(D.getIdentifierLoc(), diag::err_template_member)
2082 << II
2083 << SourceRange(TemplateParams->getTemplateLoc(),
2084 TemplateParams->getRAngleLoc());
2085 } else {
2086 // There is an extraneous 'template<>' for this member.
2087 Diag(TemplateParams->getTemplateLoc(),
2088 diag::err_template_member_noparams)
2089 << II
2090 << SourceRange(TemplateParams->getTemplateLoc(),
2091 TemplateParams->getRAngleLoc());
2092 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002093 return nullptr;
Douglas Gregor7c26c042011-09-21 14:40:46 +00002094 }
2095
Douglas Gregora007d362010-10-13 22:19:53 +00002096 if (SS.isSet() && !SS.isInvalid()) {
2097 // The user provided a superfluous scope specifier inside a class
2098 // definition:
2099 //
2100 // class X {
2101 // int X::member;
2102 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002103 if (DeclContext *DC = computeDeclContext(SS, false))
2104 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002105 else
2106 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2107 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002108
Douglas Gregora007d362010-10-13 22:19:53 +00002109 SS.clear();
2110 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002111
John McCall5e77d762013-04-16 07:28:30 +00002112 AttributeList *MSPropertyAttr =
2113 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002114 if (MSPropertyAttr) {
2115 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2116 BitWidth, InitStyle, AS, MSPropertyAttr);
2117 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002118 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002119 isInstField = false;
2120 } else {
2121 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2122 BitWidth, InitStyle, AS);
2123 assert(Member && "HandleField never returns null");
2124 }
2125 } else {
2126 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2127
2128 Member = HandleDeclarator(S, D, TemplateParameterLists);
2129 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002130 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002131
2132 // Non-instance-fields can't have a bitfield.
2133 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002134 if (Member->isInvalidDecl()) {
2135 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00002136 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002137 // C++ 9.6p3: A bit-field shall not be a static member.
2138 // "static member 'A' cannot be a bit-field"
2139 Diag(Loc, diag::err_static_not_bitfield)
2140 << Name << BitWidth->getSourceRange();
2141 } else if (isa<TypedefDecl>(Member)) {
2142 // "typedef member 'x' cannot be a bit-field"
2143 Diag(Loc, diag::err_typedef_not_bitfield)
2144 << Name << BitWidth->getSourceRange();
2145 } else {
2146 // A function typedef ("typedef int f(); f a;").
2147 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2148 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002149 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002150 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002151 }
Mike Stump11289f42009-09-09 15:08:12 +00002152
Craig Topperc3ec1492014-05-26 06:22:03 +00002153 BitWidth = nullptr;
Chris Lattnerd26760a2009-03-05 23:01:03 +00002154 Member->setInvalidDecl();
2155 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002156
2157 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002158
Larisse Voufo39a1e502013-08-06 01:03:05 +00002159 // If we have declared a member function template or static data member
2160 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002161 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2162 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002163 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2164 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00002165 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002166
Richard Smith18f07db2012-08-06 03:25:17 +00002167 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00002168 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00002169 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00002170 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2171 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00002172
Douglas Gregorf2f08062011-03-08 17:10:18 +00002173 if (VS.getLastLocation().isValid()) {
2174 // Update the end location of a method that has a virt-specifiers.
2175 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2176 MD->setRangeEnd(VS.getLastLocation());
2177 }
Richard Smith18f07db2012-08-06 03:25:17 +00002178
Anders Carlssonc87f8612011-01-20 06:29:02 +00002179 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00002180
Douglas Gregor92751d42008-11-17 22:58:34 +00002181 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002182
Daniel Jasper0baec5492012-06-06 08:32:04 +00002183 if (isInstField) {
2184 FieldDecl *FD = cast<FieldDecl>(Member);
2185 FieldCollector->Add(FD);
2186
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002187 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
Daniel Jasper0baec5492012-06-06 08:32:04 +00002188 // Remember all explicit private FieldDecls that have a name, no side
2189 // effects and are not part of a dependent type declaration.
2190 if (!FD->isImplicit() && FD->getDeclName() &&
2191 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00002192 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00002193 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00002194 !InitializationHasSideEffects(*FD))
2195 UnusedPrivateFields.insert(FD);
2196 }
2197 }
2198
John McCall48871652010-08-21 09:40:31 +00002199 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002200}
2201
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002202namespace {
2203 class UninitializedFieldVisitor
2204 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2205 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00002206 // List of Decls to generate a warning on. Also remove Decls that become
2207 // initialized.
Craig Topper4dd9b432014-08-17 23:49:53 +00002208 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
Richard Trieu406e65c2013-09-20 03:03:06 +00002209 // If non-null, add a note to the warning pointing back to the constructor.
2210 const CXXConstructorDecl *Constructor;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002211 public:
2212 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00002213 UninitializedFieldVisitor(Sema &S,
Craig Topper4dd9b432014-08-17 23:49:53 +00002214 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
Richard Trieu406e65c2013-09-20 03:03:06 +00002215 const CXXConstructorDecl *Constructor)
Richard Trieuef64e942013-10-25 00:56:00 +00002216 : Inherited(S.Context), S(S), Decls(Decls),
2217 Constructor(Constructor) { }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002218
Richard Trieufd687772013-09-16 20:46:50 +00002219 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002220 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2221 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002222
Richard Trieu1bc22c12013-09-13 03:20:53 +00002223 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2224 // or union.
2225 MemberExpr *FieldME = ME;
2226
2227 Expr *Base = ME;
2228 while (isa<MemberExpr>(Base)) {
2229 ME = cast<MemberExpr>(Base);
2230
2231 if (isa<VarDecl>(ME->getMemberDecl()))
2232 return;
2233
2234 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2235 if (!FD->isAnonymousStructOrUnion())
2236 FieldME = ME;
2237
2238 Base = ME->getBase();
2239 }
2240
Richard Trieufd687772013-09-16 20:46:50 +00002241 if (!isa<CXXThisExpr>(Base))
2242 return;
2243
Richard Trieu406e65c2013-09-20 03:03:06 +00002244 ValueDecl* FoundVD = FieldME->getMemberDecl();
2245
Richard Trieuef64e942013-10-25 00:56:00 +00002246 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00002247 return;
2248
Richard Trieuef64e942013-10-25 00:56:00 +00002249 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00002250
Richard Trieuef64e942013-10-25 00:56:00 +00002251 // Prevent double warnings on use of unbounded references.
2252 if (IsReference != CheckReferenceOnly)
2253 return;
2254
2255 unsigned diag = IsReference
2256 ? diag::warn_reference_field_is_uninit
2257 : diag::warn_field_is_uninit;
2258 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2259 if (Constructor)
2260 S.Diag(Constructor->getLocation(),
2261 diag::note_uninit_in_this_constructor)
2262 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2263
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002264 }
2265
2266 void HandleValue(Expr *E) {
2267 E = E->IgnoreParens();
2268
2269 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieufd687772013-09-16 20:46:50 +00002270 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002271 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002272 }
2273
2274 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2275 HandleValue(CO->getTrueExpr());
2276 HandleValue(CO->getFalseExpr());
2277 return;
2278 }
2279
2280 if (BinaryConditionalOperator *BCO =
2281 dyn_cast<BinaryConditionalOperator>(E)) {
2282 HandleValue(BCO->getCommon());
2283 HandleValue(BCO->getFalseExpr());
2284 return;
2285 }
2286
2287 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2288 switch (BO->getOpcode()) {
2289 default:
2290 return;
2291 case(BO_PtrMemD):
2292 case(BO_PtrMemI):
2293 HandleValue(BO->getLHS());
2294 return;
2295 case(BO_Comma):
2296 HandleValue(BO->getRHS());
2297 return;
2298 }
2299 }
2300 }
2301
Richard Trieu1bc22c12013-09-13 03:20:53 +00002302 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00002303 // All uses of unbounded reference fields will warn.
Richard Trieufd687772013-09-16 20:46:50 +00002304 HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002305
2306 Inherited::VisitMemberExpr(ME);
2307 }
2308
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002309 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2310 if (E->getCastKind() == CK_LValueToRValue)
2311 HandleValue(E->getSubExpr());
2312
2313 Inherited::VisitImplicitCastExpr(E);
2314 }
2315
Richard Trieu1bc22c12013-09-13 03:20:53 +00002316 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu4834ad22014-08-12 21:05:04 +00002317 if (E->getConstructor()->isCopyConstructor()) {
2318 Expr *ArgExpr = E->getArg(0);
2319 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) {
2320 if (ICE->getCastKind() == CK_NoOp) {
2321 ArgExpr = ICE->getSubExpr();
2322 }
2323 }
2324
2325 if (MemberExpr *ME = dyn_cast<MemberExpr>(ArgExpr)) {
2326 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
2327 }
2328 }
Richard Trieu1bc22c12013-09-13 03:20:53 +00002329 Inherited::VisitCXXConstructExpr(E);
2330 }
2331
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002332 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2333 Expr *Callee = E->getCallee();
2334 if (isa<MemberExpr>(Callee))
2335 HandleValue(Callee);
2336
2337 Inherited::VisitCXXMemberCallExpr(E);
2338 }
Richard Trieu406e65c2013-09-20 03:03:06 +00002339
2340 void VisitBinaryOperator(BinaryOperator *E) {
2341 // If a field assignment is detected, remove the field from the
2342 // uninitiailized field set.
2343 if (E->getOpcode() == BO_Assign)
2344 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2345 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00002346 if (!FD->getType()->isReferenceType())
2347 Decls.erase(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00002348
2349 Inherited::VisitBinaryOperator(E);
2350 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002351 };
Richard Trieu406e65c2013-09-20 03:03:06 +00002352 static void CheckInitExprContainsUninitializedFields(
Craig Topper4dd9b432014-08-17 23:49:53 +00002353 Sema &S, Expr *E, llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
Richard Trieuef64e942013-10-25 00:56:00 +00002354 const CXXConstructorDecl *Constructor) {
2355 if (Decls.size() == 0)
Richard Trieu406e65c2013-09-20 03:03:06 +00002356 return;
2357
Richard Trieuef64e942013-10-25 00:56:00 +00002358 if (!E)
2359 return;
2360
2361 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) {
2362 E = Default->getExpr();
2363 if (!E)
2364 return;
2365 // In class initializers will point to the constructor.
2366 UninitializedFieldVisitor(S, Decls, Constructor).Visit(E);
2367 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00002368 UninitializedFieldVisitor(S, Decls, nullptr).Visit(E);
Richard Trieuef64e942013-10-25 00:56:00 +00002369 }
2370 }
2371
2372 // Diagnose value-uses of fields to initialize themselves, e.g.
2373 // foo(foo)
2374 // where foo is not also a parameter to the constructor.
2375 // Also diagnose across field uninitialized use such as
2376 // x(y), y(x)
2377 // TODO: implement -Wuninitialized and fold this into that framework.
2378 static void DiagnoseUninitializedFields(
2379 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2380
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002381 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2382 Constructor->getLocation())) {
Richard Trieuef64e942013-10-25 00:56:00 +00002383 return;
2384 }
2385
2386 if (Constructor->isInvalidDecl())
2387 return;
2388
2389 const CXXRecordDecl *RD = Constructor->getParent();
2390
2391 // Holds fields that are uninitialized.
2392 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2393
2394 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00002395 for (auto *I : RD->decls()) {
2396 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002397 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00002398 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002399 UninitializedFields.insert(IFD->getAnonField());
2400 }
2401 }
2402
Aaron Ballman0ad78302014-03-13 17:34:31 +00002403 for (const auto *FieldInit : Constructor->inits()) {
2404 Expr *InitExpr = FieldInit->getInit();
Richard Trieuef64e942013-10-25 00:56:00 +00002405
2406 CheckInitExprContainsUninitializedFields(
2407 SemaRef, InitExpr, UninitializedFields, Constructor);
2408
Aaron Ballman0ad78302014-03-13 17:34:31 +00002409 if (FieldDecl *Field = FieldInit->getAnyMember())
Richard Trieuef64e942013-10-25 00:56:00 +00002410 UninitializedFields.erase(Field);
2411 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002412 }
2413} // namespace
2414
Richard Smith74108172014-01-17 03:11:34 +00002415/// \brief Enter a new C++ default initializer scope. After calling this, the
2416/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2417/// parsing or instantiating the initializer failed.
2418void Sema::ActOnStartCXXInClassMemberInitializer() {
2419 // Create a synthetic function scope to represent the call to the constructor
2420 // that notionally surrounds a use of this initializer.
2421 PushFunctionScope();
2422}
2423
2424/// \brief This is invoked after parsing an in-class initializer for a
2425/// non-static C++ class member, and after instantiating an in-class initializer
2426/// in a class template. Such actions are deferred until the class is complete.
2427void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2428 SourceLocation InitLoc,
2429 Expr *InitExpr) {
2430 // Pop the notional constructor scope we created earlier.
Craig Topperc3ec1492014-05-26 06:22:03 +00002431 PopFunctionScopeInfo(nullptr, D);
Richard Smith74108172014-01-17 03:11:34 +00002432
Richard Smith938f40b2011-06-11 17:19:42 +00002433 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smith2b013182012-06-10 03:12:00 +00002434 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2435 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00002436
2437 if (!InitExpr) {
2438 FD->setInvalidDecl();
2439 FD->removeInClassInitializer();
2440 return;
2441 }
2442
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002443 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2444 FD->setInvalidDecl();
2445 FD->removeInClassInitializer();
2446 return;
2447 }
2448
Richard Smith938f40b2011-06-11 17:19:42 +00002449 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00002450 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002451 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00002452 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00002453 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00002454 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002455 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2456 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00002457 if (Init.isInvalid()) {
2458 FD->setInvalidDecl();
2459 return;
2460 }
Richard Smith938f40b2011-06-11 17:19:42 +00002461 }
2462
Richard Smith945f8d32013-01-14 22:39:08 +00002463 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00002464 // The initialization of each base and member constitutes a
2465 // full-expression.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002466 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00002467 if (Init.isInvalid()) {
2468 FD->setInvalidDecl();
2469 return;
2470 }
2471
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002472 InitExpr = Init.get();
Richard Smith938f40b2011-06-11 17:19:42 +00002473
2474 FD->setInClassInitializer(InitExpr);
2475}
2476
Douglas Gregor15e77a22009-12-31 09:10:24 +00002477/// \brief Find the direct and/or virtual base specifiers that
2478/// correspond to the given base type, for use in base initialization
2479/// within a constructor.
2480static bool FindBaseInitializer(Sema &SemaRef,
2481 CXXRecordDecl *ClassDecl,
2482 QualType BaseType,
2483 const CXXBaseSpecifier *&DirectBaseSpec,
2484 const CXXBaseSpecifier *&VirtualBaseSpec) {
2485 // First, check for a direct base class.
Craig Topperc3ec1492014-05-26 06:22:03 +00002486 DirectBaseSpec = nullptr;
Aaron Ballman574705e2014-03-13 15:41:46 +00002487 for (const auto &Base : ClassDecl->bases()) {
2488 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002489 // We found a direct base of this type. That's what we're
2490 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00002491 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002492 break;
2493 }
2494 }
2495
2496 // Check for a virtual base class.
2497 // FIXME: We might be able to short-circuit this if we know in advance that
2498 // there are no virtual bases.
Craig Topperc3ec1492014-05-26 06:22:03 +00002499 VirtualBaseSpec = nullptr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002500 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2501 // We haven't found a base yet; search the class hierarchy for a
2502 // virtual base class.
2503 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2504 /*DetectVirtual=*/false);
2505 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2506 BaseType, Paths)) {
2507 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2508 Path != Paths.end(); ++Path) {
2509 if (Path->back().Base->isVirtual()) {
2510 VirtualBaseSpec = Path->back().Base;
2511 break;
2512 }
2513 }
2514 }
2515 }
2516
2517 return DirectBaseSpec || VirtualBaseSpec;
2518}
2519
Sebastian Redla74948d2011-09-24 17:48:25 +00002520/// \brief Handle a C++ member initializer using braced-init-list syntax.
2521MemInitResult
2522Sema::ActOnMemInitializer(Decl *ConstructorD,
2523 Scope *S,
2524 CXXScopeSpec &SS,
2525 IdentifierInfo *MemberOrBase,
2526 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002527 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002528 SourceLocation IdLoc,
2529 Expr *InitList,
2530 SourceLocation EllipsisLoc) {
2531 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002532 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00002533 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002534}
2535
2536/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00002537MemInitResult
John McCall48871652010-08-21 09:40:31 +00002538Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00002539 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002540 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002541 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00002542 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002543 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002544 SourceLocation IdLoc,
2545 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002546 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002547 SourceLocation RParenLoc,
2548 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00002549 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002550 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002551 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002552 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002553}
2554
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002555namespace {
2556
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00002557// Callback to only accept typo corrections that can be a valid C++ member
2558// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002559class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002560public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002561 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2562 : ClassDecl(ClassDecl) {}
2563
Craig Toppera798a9d2014-03-02 09:32:10 +00002564 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002565 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2566 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2567 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002568 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002569 }
2570 return false;
2571 }
2572
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002573private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002574 CXXRecordDecl *ClassDecl;
2575};
2576
2577}
2578
Sebastian Redla74948d2011-09-24 17:48:25 +00002579/// \brief Handle a C++ member initializer.
2580MemInitResult
2581Sema::BuildMemInitializer(Decl *ConstructorD,
2582 Scope *S,
2583 CXXScopeSpec &SS,
2584 IdentifierInfo *MemberOrBase,
2585 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002586 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002587 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00002588 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002589 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002590 if (!ConstructorD)
2591 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002592
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002593 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00002594
2595 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002596 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00002597 if (!Constructor) {
2598 // The user wrote a constructor initializer on a function that is
2599 // not a C++ constructor. Ignore the error for now, because we may
2600 // have more member initializers coming; we'll diagnose it just
2601 // once in ActOnMemInitializers.
2602 return true;
2603 }
2604
2605 CXXRecordDecl *ClassDecl = Constructor->getParent();
2606
2607 // C++ [class.base.init]p2:
2608 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00002609 // constructor's class and, if not found in that scope, are looked
2610 // up in the scope containing the constructor's definition.
2611 // [Note: if the constructor's class contains a member with the
2612 // same name as a direct or virtual base class of the class, a
2613 // mem-initializer-id naming the member or base class and composed
2614 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00002615 // mem-initializer-id for the hidden base class may be specified
2616 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00002617 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002618 // Look for a member, first.
Mike Stump11289f42009-09-09 15:08:12 +00002619 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002620 = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00002621 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00002622 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00002623 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2624 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00002625 if (EllipsisLoc.isValid())
2626 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00002627 << MemberOrBase
2628 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002629
Sebastian Redla9351792012-02-11 23:51:47 +00002630 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00002631 }
Francois Pichetd583da02010-12-04 09:14:42 +00002632 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002633 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002634 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002635 QualType BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002636 TypeSourceInfo *TInfo = nullptr;
John McCallb5a0d312009-12-21 10:41:20 +00002637
2638 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00002639 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00002640 } else if (DS.getTypeSpecType() == TST_decltype) {
2641 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00002642 } else {
2643 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2644 LookupParsedName(R, S, &SS);
2645
2646 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2647 if (!TyD) {
2648 if (R.isAmbiguous()) return true;
2649
John McCallda6841b2010-04-09 19:01:14 +00002650 // We don't want access-control diagnostics here.
2651 R.suppressDiagnostics();
2652
Douglas Gregora3b624a2010-01-19 06:46:48 +00002653 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2654 bool NotUnknownSpecialization = false;
2655 DeclContext *DC = computeDeclContext(SS, false);
2656 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2657 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2658
2659 if (!NotUnknownSpecialization) {
2660 // When the scope specifier can refer to a member of an unknown
2661 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00002662 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2663 SS.getWithLocInContext(Context),
2664 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00002665 if (BaseType.isNull())
2666 return true;
2667
Douglas Gregora3b624a2010-01-19 06:46:48 +00002668 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002669 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002670 }
2671 }
2672
Douglas Gregor15e77a22009-12-31 09:10:24 +00002673 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002674 TypoCorrection Corr;
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002675 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002676 if (R.empty() && BaseType.isNull() &&
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002677 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
John Thompson2255f2c2014-04-23 12:57:01 +00002678 Validator, CTK_ErrorRecovery, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002679 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002680 // We have found a non-static data member with a similar
2681 // name to what was typed; complain and initialize that
2682 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00002683 diagnoseTypo(Corr,
2684 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2685 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00002686 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002687 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002688 const CXXBaseSpecifier *DirectBaseSpec;
2689 const CXXBaseSpecifier *VirtualBaseSpec;
2690 if (FindBaseInitializer(*this, ClassDecl,
2691 Context.getTypeDeclType(Type),
2692 DirectBaseSpec, VirtualBaseSpec)) {
2693 // We have found a direct or virtual base class with a
2694 // similar name to what was typed; complain and initialize
2695 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00002696 diagnoseTypo(Corr,
2697 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2698 << MemberOrBase << false,
2699 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00002700
Richard Smithf9b15102013-08-17 00:46:16 +00002701 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2702 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002703 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00002704 diag::note_base_class_specified_here)
2705 << BaseSpec->getType()
2706 << BaseSpec->getSourceRange();
2707
Douglas Gregor15e77a22009-12-31 09:10:24 +00002708 TyD = Type;
2709 }
2710 }
2711 }
2712
Douglas Gregora3b624a2010-01-19 06:46:48 +00002713 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002714 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00002715 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00002716 return true;
2717 }
John McCallb5a0d312009-12-21 10:41:20 +00002718 }
2719
Douglas Gregora3b624a2010-01-19 06:46:48 +00002720 if (BaseType.isNull()) {
2721 BaseType = Context.getTypeDeclType(TyD);
Aaron Ballman4a979672014-01-03 13:56:08 +00002722 if (SS.isSet())
Douglas Gregora3b624a2010-01-19 06:46:48 +00002723 // FIXME: preserve source range information
Aaron Ballman4a979672014-01-03 13:56:08 +00002724 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2725 BaseType);
John McCallb5a0d312009-12-21 10:41:20 +00002726 }
2727 }
Mike Stump11289f42009-09-09 15:08:12 +00002728
John McCallbcd03502009-12-07 02:54:59 +00002729 if (!TInfo)
2730 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002731
Sebastian Redla9351792012-02-11 23:51:47 +00002732 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00002733}
2734
Chandler Carruth599deef2011-09-03 01:14:15 +00002735/// Checks a member initializer expression for cases where reference (or
2736/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00002737static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2738 Expr *Init,
2739 SourceLocation IdLoc) {
2740 QualType MemberTy = Member->getType();
2741
2742 // We only handle pointers and references currently.
2743 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2744 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2745 return;
2746
2747 const bool IsPointer = MemberTy->isPointerType();
2748 if (IsPointer) {
2749 if (const UnaryOperator *Op
2750 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2751 // The only case we're worried about with pointers requires taking the
2752 // address.
2753 if (Op->getOpcode() != UO_AddrOf)
2754 return;
2755
2756 Init = Op->getSubExpr();
2757 } else {
2758 // We only handle address-of expression initializers for pointers.
2759 return;
2760 }
2761 }
2762
Richard Smithe3b28bc2013-06-12 21:51:50 +00002763 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002764 // We only warn when referring to a non-reference parameter declaration.
2765 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2766 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00002767 return;
2768
2769 S.Diag(Init->getExprLoc(),
2770 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2771 : diag::warn_bind_ref_member_to_parameter)
2772 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002773 } else {
2774 // Other initializers are fine.
2775 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00002776 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002777
2778 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2779 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00002780}
2781
John McCallfaf5fb42010-08-26 23:41:50 +00002782MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002783Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002784 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002785 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2786 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2787 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00002788 "Member must be a FieldDecl or IndirectFieldDecl");
2789
Sebastian Redla9351792012-02-11 23:51:47 +00002790 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002791 return true;
2792
Douglas Gregor266bb5f2010-11-05 22:21:31 +00002793 if (Member->isInvalidDecl())
2794 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00002795
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002796 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00002797 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002798 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00002799 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002800 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00002801 } else {
2802 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002803 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00002804 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00002805
Sebastian Redla9351792012-02-11 23:51:47 +00002806 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002807
Sebastian Redla9351792012-02-11 23:51:47 +00002808 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002809 // Can't check initialization for a member of dependent type or when
2810 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00002811 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00002812 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00002813 bool InitList = false;
2814 if (isa<InitListExpr>(Init)) {
2815 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002816 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002817 }
2818
Chandler Carruthd44c3102010-12-06 09:23:57 +00002819 // Initialize the member.
2820 InitializedEntity MemberEntity =
Craig Topperc3ec1492014-05-26 06:22:03 +00002821 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
2822 : InitializedEntity::InitializeMember(IndirectMember,
2823 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002824 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002825 InitList ? InitializationKind::CreateDirectList(IdLoc)
2826 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2827 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00002828
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002829 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00002830 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
2831 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002832 if (MemberInit.isInvalid())
2833 return true;
2834
Richard Smith736a9472013-06-12 20:42:33 +00002835 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2836
Richard Smith945f8d32013-01-14 22:39:08 +00002837 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00002838 // The initialization of each base and member constitutes a
2839 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002840 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002841 if (MemberInit.isInvalid())
2842 return true;
2843
Richard Smithd59b8322012-12-19 01:39:02 +00002844 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002845 }
2846
Chandler Carruthd44c3102010-12-06 09:23:57 +00002847 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00002848 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2849 InitRange.getBegin(), Init,
2850 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002851 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00002852 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2853 InitRange.getBegin(), Init,
2854 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002855 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00002856}
2857
John McCallfaf5fb42010-08-26 23:41:50 +00002858MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002859Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002860 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002861 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002862 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002863 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002864 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002865 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00002866
Sebastian Redl0501c632012-02-12 16:37:36 +00002867 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002868 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00002869 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2870 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002871 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00002872 }
2873
Sebastian Redla9351792012-02-11 23:51:47 +00002874 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00002875 // Initialize the object.
2876 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2877 QualType(ClassDecl->getTypeForDecl(), 0));
2878 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00002879 InitList ? InitializationKind::CreateDirectList(NameLoc)
2880 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2881 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002882 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00002883 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Craig Topperc3ec1492014-05-26 06:22:03 +00002884 Args, nullptr);
Alexis Huntc5575cc2011-02-26 19:13:13 +00002885 if (DelegationInit.isInvalid())
2886 return true;
2887
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00002888 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2889 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00002890
Richard Smith945f8d32013-01-14 22:39:08 +00002891 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00002892 // The initialization of each base and member constitutes a
2893 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00002894 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2895 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002896 if (DelegationInit.isInvalid())
2897 return true;
2898
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00002899 // If we are in a dependent context, template instantiation will
2900 // perform this type-checking again. Just save the arguments that we
2901 // received in a ParenListExpr.
2902 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2903 // of the information that we have about the base
2904 // initializer. However, deconstructing the ASTs is a dicey process,
2905 // and this approach is far more likely to get the corner cases right.
2906 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002907 DelegationInit = Init;
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00002908
Sebastian Redla9351792012-02-11 23:51:47 +00002909 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002910 DelegationInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00002911 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002912}
2913
2914MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00002915Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00002916 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002917 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002918 SourceLocation BaseLoc
2919 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00002920
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002921 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2922 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2923 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2924
2925 // C++ [class.base.init]p2:
2926 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00002927 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002928 // of that class, the mem-initializer is ill-formed. A
2929 // mem-initializer-list can initialize a base class using any
2930 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00002931 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002932
Sebastian Redla9351792012-02-11 23:51:47 +00002933 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00002934 if (EllipsisLoc.isValid()) {
2935 // This is a pack expansion.
2936 if (!BaseType->containsUnexpandedParameterPack()) {
2937 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00002938 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002939
Douglas Gregor44e7df62011-01-04 00:32:56 +00002940 EllipsisLoc = SourceLocation();
2941 }
2942 } else {
2943 // Check for any unexpanded parameter packs.
2944 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2945 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00002946
Sebastian Redla9351792012-02-11 23:51:47 +00002947 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00002948 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00002949 }
Sebastian Redla74948d2011-09-24 17:48:25 +00002950
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002951 // Check for direct and virtual base classes.
Craig Topperc3ec1492014-05-26 06:22:03 +00002952 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
2953 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002954 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002955 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2956 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00002957 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002958
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002959 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2960 VirtualBaseSpec);
2961
2962 // C++ [base.class.init]p2:
2963 // Unless the mem-initializer-id names a nonstatic data member of the
2964 // constructor's class or a direct or virtual base of that class, the
2965 // mem-initializer is ill-formed.
2966 if (!DirectBaseSpec && !VirtualBaseSpec) {
2967 // If the class has any dependent bases, then it's possible that
2968 // one of those types will resolve to the same type as
2969 // BaseType. Therefore, just treat this as a dependent base
2970 // class initialization. FIXME: Should we try to check the
2971 // initialization anyway? It seems odd.
2972 if (ClassDecl->hasAnyDependentBases())
2973 Dependent = true;
2974 else
2975 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2976 << BaseType << Context.getTypeDeclType(ClassDecl)
2977 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2978 }
2979 }
2980
2981 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00002982 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002983
Sebastian Redla74948d2011-09-24 17:48:25 +00002984 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2985 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00002986 InitRange.getBegin(), Init,
2987 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002988 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002989
2990 // C++ [base.class.init]p2:
2991 // If a mem-initializer-id is ambiguous because it designates both
2992 // a direct non-virtual base class and an inherited virtual base
2993 // class, the mem-initializer is ill-formed.
2994 if (DirectBaseSpec && VirtualBaseSpec)
2995 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002996 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002997
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002998 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002999 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003000 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003001
3002 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00003003 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003004 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003005 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00003006 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003007 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00003008 }
Sebastian Redl0501c632012-02-12 16:37:36 +00003009
3010 InitializedEntity BaseEntity =
3011 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3012 InitializationKind Kind =
3013 InitList ? InitializationKind::CreateDirectList(BaseLoc)
3014 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3015 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003016 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003017 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003018 if (BaseInit.isInvalid())
3019 return true;
John McCallacf0ee52010-10-08 02:01:28 +00003020
Richard Smith945f8d32013-01-14 22:39:08 +00003021 // C++11 [class.base.init]p7:
3022 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003023 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003024 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003025 if (BaseInit.isInvalid())
3026 return true;
3027
3028 // If we are in a dependent context, template instantiation will
3029 // perform this type-checking again. Just save the arguments that we
3030 // received in a ParenListExpr.
3031 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3032 // of the information that we have about the base
3033 // initializer. However, deconstructing the ASTs is a dicey process,
3034 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00003035 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003036 BaseInit = Init;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003037
Alexis Hunt1d792652011-01-08 20:30:50 +00003038 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00003039 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00003040 InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003041 BaseInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003042 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003043}
3044
Sebastian Redl22653ba2011-08-30 19:58:05 +00003045// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00003046static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3047 if (T.isNull()) T = E->getType();
3048 QualType TargetType = SemaRef.BuildReferenceType(
3049 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003050 SourceLocation ExprLoc = E->getLocStart();
3051 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3052 TargetType, ExprLoc);
3053
3054 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3055 SourceRange(ExprLoc, ExprLoc),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003056 E->getSourceRange()).get();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003057}
3058
Anders Carlsson1b00e242010-04-23 03:10:23 +00003059/// ImplicitInitializerKind - How an implicit base or member initializer should
3060/// initialize its base or member.
3061enum ImplicitInitializerKind {
3062 IIK_Default,
3063 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00003064 IIK_Move,
3065 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00003066};
3067
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003068static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00003069BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003070 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00003071 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003072 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00003073 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003074 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00003075 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3076 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003077
John McCalldadc5752010-08-24 06:29:42 +00003078 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003079
3080 switch (ImplicitInitKind) {
Richard Smithc2bc61b2013-03-18 21:12:30 +00003081 case IIK_Inherit: {
3082 const CXXRecordDecl *Inherited =
3083 Constructor->getInheritedConstructor()->getParent();
3084 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3085 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3086 // C++11 [class.inhctor]p8:
3087 // Each expression in the expression-list is of the form
3088 // static_cast<T&&>(p), where p is the name of the corresponding
3089 // constructor parameter and T is the declared type of p.
3090 SmallVector<Expr*, 16> Args;
3091 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3092 ParmVarDecl *PD = Constructor->getParamDecl(I);
3093 ExprResult ArgExpr =
3094 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3095 VK_LValue, SourceLocation());
3096 if (ArgExpr.isInvalid())
3097 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003098 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
Richard Smithc2bc61b2013-03-18 21:12:30 +00003099 }
3100
3101 InitializationKind InitKind = InitializationKind::CreateDirect(
3102 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003103 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smithc2bc61b2013-03-18 21:12:30 +00003104 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3105 break;
3106 }
3107 }
3108 // Fall through.
Anders Carlsson1b00e242010-04-23 03:10:23 +00003109 case IIK_Default: {
3110 InitializationKind InitKind
3111 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003112 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3113 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003114 break;
3115 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003116
Sebastian Redl22653ba2011-08-30 19:58:05 +00003117 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00003118 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003119 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003120 ParmVarDecl *Param = Constructor->getParamDecl(0);
3121 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00003122
Anders Carlsson1b00e242010-04-23 03:10:23 +00003123 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003124 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003125 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003126 Constructor->getLocation(), ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003127 VK_LValue, nullptr);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003128
Eli Friedmanfa0df832012-02-02 03:46:19 +00003129 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3130
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003131 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00003132 QualType ArgTy =
3133 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3134 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00003135
Sebastian Redl22653ba2011-08-30 19:58:05 +00003136 if (Moving) {
3137 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3138 }
3139
John McCallcf142162010-08-07 06:22:56 +00003140 CXXCastPath BasePath;
3141 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00003142 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3143 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003144 Moving ? VK_XValue : VK_LValue,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003145 &BasePath).get();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003146
Anders Carlsson1b00e242010-04-23 03:10:23 +00003147 InitializationKind InitKind
3148 = InitializationKind::CreateDirect(Constructor->getLocation(),
3149 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003150 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3151 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003152 break;
3153 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00003154 }
John McCallb268a282010-08-23 23:25:46 +00003155
Douglas Gregora40433a2010-12-07 00:41:46 +00003156 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003157 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003158 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003159
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003160 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00003161 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003162 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3163 SourceLocation()),
3164 BaseSpec->isVirtual(),
3165 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003166 BaseInit.getAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003167 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003168 SourceLocation());
3169
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003170 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003171}
3172
Sebastian Redl22653ba2011-08-30 19:58:05 +00003173static bool RefersToRValueRef(Expr *MemRef) {
3174 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3175 return Referenced->getType()->isRValueReferenceType();
3176}
3177
Anders Carlsson3c1db572010-04-23 02:15:47 +00003178static bool
3179BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003180 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00003181 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00003182 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003183 if (Field->isInvalidDecl())
3184 return true;
3185
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003186 SourceLocation Loc = Constructor->getLocation();
3187
Sebastian Redl22653ba2011-08-30 19:58:05 +00003188 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3189 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00003190 ParmVarDecl *Param = Constructor->getParamDecl(0);
3191 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00003192
3193 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00003194 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3195 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003196
Anders Carlsson423f5d82010-04-23 16:04:08 +00003197 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003198 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003199 SourceLocation(), Param, false,
Craig Topperc3ec1492014-05-26 06:22:03 +00003200 Loc, ParamType, VK_LValue, nullptr);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003201
Eli Friedmanfa0df832012-02-02 03:46:19 +00003202 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3203
Sebastian Redl22653ba2011-08-30 19:58:05 +00003204 if (Moving) {
3205 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3206 }
3207
Douglas Gregor94f9a482010-05-05 05:51:00 +00003208 // Build a reference to this field within the parameter.
3209 CXXScopeSpec SS;
3210 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3211 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003212 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3213 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003214 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00003215 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00003216 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003217 ParamType, Loc,
3218 /*IsArrow=*/false,
3219 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003220 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003221 /*FirstQualifierInScope=*/nullptr,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003222 MemberLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00003223 /*TemplateArgs=*/nullptr);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003224 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00003225 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003226
3227 // C++11 [class.copy]p15:
3228 // - if a member m has rvalue reference type T&&, it is direct-initialized
3229 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003230 if (RefersToRValueRef(CtorArg.get())) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003231 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003232 }
3233
Douglas Gregor94f9a482010-05-05 05:51:00 +00003234 // When the field we are copying is an array, create index variables for
3235 // each dimension of the array. We use these index variables to subscript
3236 // the source array, and other clients (e.g., CodeGen) will perform the
3237 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003238 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003239 QualType BaseType = Field->getType();
3240 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003241 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003242 while (const ConstantArrayType *Array
3243 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003244 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003245 // Create the iteration variable for this array index.
Craig Topperc3ec1492014-05-26 06:22:03 +00003246 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003247 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003248 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003249 llvm::raw_svector_ostream OS(Str);
3250 OS << "__i" << IndexVariables.size();
3251 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3252 }
3253 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00003254 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003255 IterationVarName, SizeType,
3256 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003257 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003258 IndexVariables.push_back(IterationVar);
3259
3260 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00003261 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00003262 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003263 assert(!IterationVarRef.isInvalid() &&
3264 "Reference to invented variable cannot fail!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003265 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
Eli Friedman844f9452012-01-23 02:35:22 +00003266 assert(!IterationVarRef.isInvalid() &&
3267 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00003268
Douglas Gregor94f9a482010-05-05 05:51:00 +00003269 // Subscript the array with this iteration variable.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003270 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3271 IterationVarRef.get(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00003272 Loc);
3273 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00003274 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003275
Douglas Gregor94f9a482010-05-05 05:51:00 +00003276 BaseType = Array->getElementType();
3277 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00003278
3279 // The array subscript expression is an lvalue, which is wrong for moving.
3280 if (Moving && InitializingArray)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003281 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003282
Douglas Gregor94f9a482010-05-05 05:51:00 +00003283 // Construct the entity that we will be initializing. For an array, this
3284 // will be first element in the array, which may require several levels
3285 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003286 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003287 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00003288 if (Indirect)
3289 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3290 else
3291 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00003292 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3293 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3294 0,
3295 Entities.back()));
3296
3297 // Direct-initialize to use the copy constructor.
3298 InitializationKind InitKind =
3299 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3300
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003301 Expr *CtorArgE = CtorArg.getAs<Expr>();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003302 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003303
John McCalldadc5752010-08-24 06:29:42 +00003304 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00003305 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003306 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00003307 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003308 if (MemberInit.isInvalid())
3309 return true;
3310
Douglas Gregor493627b2011-08-10 15:22:55 +00003311 if (Indirect) {
3312 assert(IndexVariables.size() == 0 &&
3313 "Indirect field improperly initialized");
3314 CXXMemberInit
3315 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3316 Loc, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003317 MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003318 Loc);
3319 } else
3320 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003321 Loc, MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003322 Loc,
3323 IndexVariables.data(),
3324 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00003325 return false;
3326 }
3327
Richard Smithc2bc61b2013-03-18 21:12:30 +00003328 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3329 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00003330
Anders Carlsson3c1db572010-04-23 02:15:47 +00003331 QualType FieldBaseElementType =
3332 SemaRef.Context.getBaseElementType(Field->getType());
3333
Anders Carlsson3c1db572010-04-23 02:15:47 +00003334 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003335 InitializedEntity InitEntity
3336 = Indirect? InitializedEntity::InitializeMember(Indirect)
3337 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00003338 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003339 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003340
3341 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3342 ExprResult MemberInit =
3343 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00003344
Douglas Gregora40433a2010-12-07 00:41:46 +00003345 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003346 if (MemberInit.isInvalid())
3347 return true;
3348
Douglas Gregor493627b2011-08-10 15:22:55 +00003349 if (Indirect)
3350 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3351 Indirect, Loc,
3352 Loc,
3353 MemberInit.get(),
3354 Loc);
3355 else
3356 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3357 Field, Loc, Loc,
3358 MemberInit.get(),
3359 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003360 return false;
3361 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003362
Alexis Hunt8b455182011-05-17 00:19:05 +00003363 if (!Field->getParent()->isUnion()) {
3364 if (FieldBaseElementType->isReferenceType()) {
3365 SemaRef.Diag(Constructor->getLocation(),
3366 diag::err_uninitialized_member_in_ctor)
3367 << (int)Constructor->isImplicit()
3368 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3369 << 0 << Field->getDeclName();
3370 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3371 return true;
3372 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003373
Alexis Hunt8b455182011-05-17 00:19:05 +00003374 if (FieldBaseElementType.isConstQualified()) {
3375 SemaRef.Diag(Constructor->getLocation(),
3376 diag::err_uninitialized_member_in_ctor)
3377 << (int)Constructor->isImplicit()
3378 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3379 << 1 << Field->getDeclName();
3380 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3381 return true;
3382 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003383 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00003384
David Blaikiebbafb8a2012-03-11 07:00:24 +00003385 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003386 FieldBaseElementType->isObjCRetainableType() &&
3387 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3388 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00003389 // ARC:
John McCall31168b02011-06-15 23:02:42 +00003390 // Default-initialize Objective-C pointers to NULL.
3391 CXXMemberInit
3392 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3393 Loc, Loc,
3394 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3395 Loc);
3396 return false;
3397 }
3398
Anders Carlsson3c1db572010-04-23 02:15:47 +00003399 // Nothing to initialize.
Craig Topperc3ec1492014-05-26 06:22:03 +00003400 CXXMemberInit = nullptr;
Anders Carlsson3c1db572010-04-23 02:15:47 +00003401 return false;
3402}
John McCallbc83b3f2010-05-20 23:23:51 +00003403
3404namespace {
3405struct BaseAndFieldInfo {
3406 Sema &S;
3407 CXXConstructorDecl *Ctor;
3408 bool AnyErrorsInInits;
3409 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00003410 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003411 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00003412 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00003413
3414 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3415 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003416 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3417 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00003418 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003419 else if (Generated && Ctor->isMoveConstructor())
3420 IIK = IIK_Move;
Richard Smithc2bc61b2013-03-18 21:12:30 +00003421 else if (Ctor->getInheritedConstructor())
3422 IIK = IIK_Inherit;
John McCallbc83b3f2010-05-20 23:23:51 +00003423 else
3424 IIK = IIK_Default;
3425 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00003426
3427 bool isImplicitCopyOrMove() const {
3428 switch (IIK) {
3429 case IIK_Copy:
3430 case IIK_Move:
3431 return true;
3432
3433 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00003434 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00003435 return false;
3436 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003437
3438 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00003439 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00003440
3441 bool addFieldInitializer(CXXCtorInitializer *Init) {
3442 AllToInit.push_back(Init);
3443
3444 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00003445 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003446 S.UnusedPrivateFields.remove(Init->getAnyMember());
3447
3448 return false;
3449 }
John McCallbc83b3f2010-05-20 23:23:51 +00003450
Richard Smithab44d5b2013-12-10 08:25:00 +00003451 bool isInactiveUnionMember(FieldDecl *Field) {
3452 RecordDecl *Record = Field->getParent();
3453 if (!Record->isUnion())
3454 return false;
3455
Richard Smith8d183852013-12-10 20:56:03 +00003456 if (FieldDecl *Active =
3457 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00003458 return Active != Field->getCanonicalDecl();
3459
3460 // In an implicit copy or move constructor, ignore any in-class initializer.
3461 if (isImplicitCopyOrMove())
3462 return true;
3463
3464 // If there's no explicit initialization, the field is active only if it
3465 // has an in-class initializer...
3466 if (Field->hasInClassInitializer())
3467 return false;
3468 // ... or it's an anonymous struct or union whose class has an in-class
3469 // initializer.
3470 if (!Field->isAnonymousStructOrUnion())
3471 return true;
3472 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3473 return !FieldRD->hasInClassInitializer();
3474 }
3475
3476 /// \brief Determine whether the given field is, or is within, a union member
3477 /// that is inactive (because there was an initializer given for a different
3478 /// member of the union, or because the union was not initialized at all).
3479 bool isWithinInactiveUnionMember(FieldDecl *Field,
3480 IndirectFieldDecl *Indirect) {
3481 if (!Indirect)
3482 return isInactiveUnionMember(Field);
3483
Aaron Ballman29c94602014-03-07 18:36:15 +00003484 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003485 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003486 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00003487 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00003488 }
3489 return false;
3490 }
3491};
Richard Smithc94ec842011-09-19 13:34:43 +00003492}
3493
Douglas Gregor10f939c2011-11-02 23:04:16 +00003494/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3495/// array type.
3496static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3497 if (T->isIncompleteArrayType())
3498 return true;
3499
3500 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3501 if (!ArrayT->getSize())
3502 return true;
3503
3504 T = ArrayT->getElementType();
3505 }
3506
3507 return false;
3508}
3509
Richard Smith938f40b2011-06-11 17:19:42 +00003510static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00003511 FieldDecl *Field,
Craig Topperc3ec1492014-05-26 06:22:03 +00003512 IndirectFieldDecl *Indirect = nullptr) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003513 if (Field->isInvalidDecl())
3514 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00003515
Chandler Carruth139e9622010-06-30 02:59:29 +00003516 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smithcd45dbc2014-04-19 03:48:30 +00003517 if (CXXCtorInitializer *Init =
3518 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003519 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003520
Richard Smithab44d5b2013-12-10 08:25:00 +00003521 // C++11 [class.base.init]p8:
3522 // if the entity is a non-static data member that has a
3523 // brace-or-equal-initializer and either
3524 // -- the constructor's class is a union and no other variant member of that
3525 // union is designated by a mem-initializer-id or
3526 // -- the constructor's class is not a union, and, if the entity is a member
3527 // of an anonymous union, no other member of that union is designated by
3528 // a mem-initializer-id,
3529 // the entity is initialized as specified in [dcl.init].
3530 //
3531 // We also apply the same rules to handle anonymous structs within anonymous
3532 // unions.
3533 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3534 return false;
3535
Douglas Gregor7db3e952011-11-28 20:03:15 +00003536 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smith852c9db2013-04-20 22:23:05 +00003537 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3538 Info.Ctor->getLocation(), Field);
Douglas Gregor493627b2011-08-10 15:22:55 +00003539 CXXCtorInitializer *Init;
3540 if (Indirect)
3541 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3542 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003543 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003544 SourceLocation());
3545 else
3546 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3547 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003548 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003549 SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00003550 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003551 }
3552
Douglas Gregor10f939c2011-11-02 23:04:16 +00003553 // Don't initialize incomplete or zero-length arrays.
3554 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3555 return false;
3556
John McCallbc83b3f2010-05-20 23:23:51 +00003557 // Don't try to build an implicit initializer if there were semantic
3558 // errors in any of the initializers (and therefore we might be
3559 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003560 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00003561 return false;
3562
Craig Topperc3ec1492014-05-26 06:22:03 +00003563 CXXCtorInitializer *Init = nullptr;
Douglas Gregor493627b2011-08-10 15:22:55 +00003564 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3565 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00003566 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00003567
Richard Smith0a8cfc72012-08-07 21:30:42 +00003568 if (!Init)
3569 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00003570
Richard Smith0a8cfc72012-08-07 21:30:42 +00003571 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003572}
Alexis Hunt61bc1732011-05-01 07:04:31 +00003573
3574bool
3575Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3576 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00003577 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00003578 Constructor->setNumCtorInitializers(1);
3579 CXXCtorInitializer **initializer =
3580 new (Context) CXXCtorInitializer*[1];
3581 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3582 Constructor->setCtorInitializers(initializer);
3583
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003584 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003585 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003586 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3587 }
3588
Alexis Hunte2622992011-05-05 00:05:47 +00003589 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00003590
Alexis Hunt61bc1732011-05-01 07:04:31 +00003591 return false;
3592}
Douglas Gregor493627b2011-08-10 15:22:55 +00003593
David Blaikie3fc2f912013-01-17 05:26:25 +00003594bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3595 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00003596 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003597 // Just store the initializers as written, they will be checked during
3598 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00003599 if (!Initializers.empty()) {
3600 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00003601 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00003602 new (Context) CXXCtorInitializer*[Initializers.size()];
3603 memcpy(baseOrMemberInitializers, Initializers.data(),
3604 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00003605 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003606 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00003607
3608 // Let template instantiation know whether we had errors.
3609 if (AnyErrors)
3610 Constructor->setInvalidDecl();
3611
Anders Carlssondb0a9652010-04-02 06:26:44 +00003612 return false;
3613 }
3614
John McCallbc83b3f2010-05-20 23:23:51 +00003615 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003616
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003617 // We need to build the initializer AST according to order of construction
3618 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003619 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00003620 if (!ClassDecl)
3621 return true;
3622
Eli Friedman9cf6b592009-11-09 19:20:36 +00003623 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00003624
David Blaikie3fc2f912013-01-17 05:26:25 +00003625 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003626 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00003627
Anders Carlssondb0a9652010-04-02 06:26:44 +00003628 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00003629 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003630 else {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003631 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003632
3633 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00003634 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003635 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003636 if (FD && FD->getParent()->isUnion())
3637 Info.ActiveUnionMember.insert(std::make_pair(
3638 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3639 }
3640 } else if (FieldDecl *FD = Member->getMember()) {
3641 if (FD->getParent()->isUnion())
3642 Info.ActiveUnionMember.insert(std::make_pair(
3643 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3644 }
3645 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00003646 }
3647
Anders Carlsson43c64af2010-04-21 19:52:01 +00003648 // Keep track of the direct virtual bases.
3649 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00003650 for (auto &I : ClassDecl->bases()) {
3651 if (I.isVirtual())
3652 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00003653 }
3654
Anders Carlssondb0a9652010-04-02 06:26:44 +00003655 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00003656 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003657 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00003658 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00003659 // [class.base.init]p7, per DR257:
3660 // A mem-initializer where the mem-initializer-id names a virtual base
3661 // class is ignored during execution of a constructor of any class that
3662 // is not the most derived class.
3663 if (ClassDecl->isAbstract()) {
3664 // FIXME: Provide a fixit to remove the base specifier. This requires
3665 // tracking the location of the associated comma for a base specifier.
3666 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00003667 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00003668 DiagnoseAbstractType(ClassDecl);
3669 }
3670
John McCallbc83b3f2010-05-20 23:23:51 +00003671 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00003672 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3673 // [class.base.init]p8, per DR257:
3674 // If a given [...] base class is not named by a mem-initializer-id
3675 // [...] and the entity is not a virtual base class of an abstract
3676 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00003677 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00003678 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003679 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00003680 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003681 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003682 HadError = true;
3683 continue;
3684 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003685
John McCallbc83b3f2010-05-20 23:23:51 +00003686 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003687 }
3688 }
Mike Stump11289f42009-09-09 15:08:12 +00003689
John McCallbc83b3f2010-05-20 23:23:51 +00003690 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003691 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003692 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00003693 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00003694 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003695
Alexis Hunt1d792652011-01-08 20:30:50 +00003696 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00003697 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00003698 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003699 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003700 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003701 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00003702 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003703 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003704 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003705 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003706 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00003707
John McCallbc83b3f2010-05-20 23:23:51 +00003708 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003709 }
3710 }
Mike Stump11289f42009-09-09 15:08:12 +00003711
John McCallbc83b3f2010-05-20 23:23:51 +00003712 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00003713 for (auto *Mem : ClassDecl->decls()) {
3714 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003715 // C++ [class.bit]p2:
3716 // A declaration for a bit-field that omits the identifier declares an
3717 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3718 // initialized.
3719 if (F->isUnnamedBitfield())
3720 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003721
Sebastian Redl22653ba2011-08-30 19:58:05 +00003722 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00003723 // handle anonymous struct/union fields based on their individual
3724 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003725 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003726 continue;
3727
3728 if (CollectFieldInitializer(*this, Info, F))
3729 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003730 continue;
3731 }
Douglas Gregor493627b2011-08-10 15:22:55 +00003732
3733 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003734 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003735 continue;
3736
Aaron Ballman629afae2014-03-07 19:56:05 +00003737 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003738 if (F->getType()->isIncompleteArrayType()) {
3739 assert(ClassDecl->hasFlexibleArrayMember() &&
3740 "Incomplete array type is not valid");
3741 continue;
3742 }
3743
Douglas Gregor493627b2011-08-10 15:22:55 +00003744 // Initialize each field of an anonymous struct individually.
3745 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3746 HadError = true;
3747
3748 continue;
3749 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003750 }
Mike Stump11289f42009-09-09 15:08:12 +00003751
David Blaikie3fc2f912013-01-17 05:26:25 +00003752 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003753 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003754 Constructor->setNumCtorInitializers(NumInitializers);
3755 CXXCtorInitializer **baseOrMemberInitializers =
3756 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00003757 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00003758 NumInitializers * sizeof(CXXCtorInitializer*));
3759 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00003760
John McCalla6309952010-03-16 21:39:52 +00003761 // Constructors implicitly reference the base and member
3762 // destructors.
3763 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3764 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003765 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00003766
3767 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003768}
3769
David Blaikieb61b8152013-01-17 08:49:22 +00003770static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003771 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00003772 const RecordDecl *RD = RT->getDecl();
3773 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003774 for (auto *Field : RD->fields())
3775 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00003776 return;
3777 }
Eli Friedman952c15d2009-07-21 19:28:10 +00003778 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003779 IdealInits.push_back(Field->getCanonicalDecl());
Eli Friedman952c15d2009-07-21 19:28:10 +00003780}
3781
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003782static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3783 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00003784}
3785
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003786static const void *GetKeyForMember(ASTContext &Context,
3787 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00003788 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003789 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00003790
Richard Smithcd45dbc2014-04-19 03:48:30 +00003791 return Member->getAnyMember()->getCanonicalDecl();
Eli Friedman952c15d2009-07-21 19:28:10 +00003792}
3793
David Blaikie3fc2f912013-01-17 05:26:25 +00003794static void DiagnoseBaseOrMemInitializerOrder(
3795 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3796 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00003797 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00003798 return;
Mike Stump11289f42009-09-09 15:08:12 +00003799
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003800 // Don't check initializers order unless the warning is enabled at the
3801 // location of at least one initializer.
3802 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003803 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003804 CXXCtorInitializer *Init = Inits[InitIndex];
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00003805 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
3806 Init->getSourceLocation())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003807 ShouldCheckOrder = true;
3808 break;
3809 }
3810 }
3811 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00003812 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003813
John McCallbb7b6582010-04-10 07:37:23 +00003814 // Build the list of bases and members in the order that they'll
3815 // actually be initialized. The explicit initializers should be in
3816 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003817 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00003818
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003819 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3820
John McCallbb7b6582010-04-10 07:37:23 +00003821 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00003822 for (const auto &VBase : ClassDecl->vbases())
3823 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00003824
John McCallbb7b6582010-04-10 07:37:23 +00003825 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003826 for (const auto &Base : ClassDecl->bases()) {
3827 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00003828 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00003829 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00003830 }
Mike Stump11289f42009-09-09 15:08:12 +00003831
John McCallbb7b6582010-04-10 07:37:23 +00003832 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003833 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003834 if (Field->isUnnamedBitfield())
3835 continue;
3836
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003837 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00003838 }
3839
John McCallbb7b6582010-04-10 07:37:23 +00003840 unsigned NumIdealInits = IdealInitKeys.size();
3841 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00003842
Craig Topperc3ec1492014-05-26 06:22:03 +00003843 CXXCtorInitializer *PrevInit = nullptr;
David Blaikie3fc2f912013-01-17 05:26:25 +00003844 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003845 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003846 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00003847
3848 // Scan forward to try to find this initializer in the idealized
3849 // initializers list.
3850 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3851 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003852 break;
John McCallbb7b6582010-04-10 07:37:23 +00003853
3854 // If we didn't find this initializer, it must be because we
3855 // scanned past it on a previous iteration. That can only
3856 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00003857 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00003858 Sema::SemaDiagnosticBuilder D =
3859 SemaRef.Diag(PrevInit->getSourceLocation(),
3860 diag::warn_initializer_out_of_order);
3861
Francois Pichetd583da02010-12-04 09:14:42 +00003862 if (PrevInit->isAnyMemberInitializer())
3863 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003864 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003865 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003866
Francois Pichetd583da02010-12-04 09:14:42 +00003867 if (Init->isAnyMemberInitializer())
3868 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003869 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003870 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003871
3872 // Move back to the initializer's location in the ideal list.
3873 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3874 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003875 break;
John McCallbb7b6582010-04-10 07:37:23 +00003876
3877 assert(IdealIndex != NumIdealInits &&
3878 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003879 }
John McCallbb7b6582010-04-10 07:37:23 +00003880
3881 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003882 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00003883}
3884
John McCall23eebd92010-04-10 09:28:51 +00003885namespace {
3886bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003887 CXXCtorInitializer *Init,
3888 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00003889 if (!PrevInit) {
3890 PrevInit = Init;
3891 return false;
3892 }
3893
Douglas Gregorea306a12013-03-25 23:28:23 +00003894 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00003895 S.Diag(Init->getSourceLocation(),
3896 diag::err_multiple_mem_initialization)
3897 << Field->getDeclName()
3898 << Init->getSourceRange();
3899 else {
John McCall424cec92011-01-19 06:33:43 +00003900 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00003901 assert(BaseClass && "neither field nor base");
3902 S.Diag(Init->getSourceLocation(),
3903 diag::err_multiple_base_initialization)
3904 << QualType(BaseClass, 0)
3905 << Init->getSourceRange();
3906 }
3907 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3908 << 0 << PrevInit->getSourceRange();
3909
3910 return true;
3911}
3912
Alexis Hunt1d792652011-01-08 20:30:50 +00003913typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00003914typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3915
3916bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003917 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00003918 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00003919 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003920 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00003921 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00003922
3923 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00003924 if (Parent->isUnion()) {
3925 UnionEntry &En = Unions[Parent];
3926 if (En.first && En.first != Child) {
3927 S.Diag(Init->getSourceLocation(),
3928 diag::err_multiple_mem_union_initialization)
3929 << Field->getDeclName()
3930 << Init->getSourceRange();
3931 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3932 << 0 << En.second->getSourceRange();
3933 return true;
David Blaikie256ee192011-11-12 20:54:14 +00003934 }
3935 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00003936 En.first = Child;
3937 En.second = Init;
3938 }
David Blaikie0f65d592011-11-17 06:01:57 +00003939 if (!Parent->isAnonymousStructOrUnion())
3940 return false;
John McCall23eebd92010-04-10 09:28:51 +00003941 }
3942
3943 Child = Parent;
3944 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00003945 }
John McCall23eebd92010-04-10 09:28:51 +00003946
3947 return false;
3948}
3949}
3950
Anders Carlssone857b292010-04-02 03:37:03 +00003951/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00003952void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00003953 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00003954 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00003955 bool AnyErrors) {
3956 if (!ConstructorDecl)
3957 return;
3958
3959 AdjustDeclIfTemplate(ConstructorDecl);
3960
3961 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003962 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00003963
3964 if (!Constructor) {
3965 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3966 return;
3967 }
3968
John McCall23eebd92010-04-10 09:28:51 +00003969 // Mapping for the duplicate initializers check.
3970 // For member initializers, this is keyed with a FieldDecl*.
3971 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003972 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00003973
3974 // Mapping for the inconsistent anonymous-union initializers check.
3975 RedundantUnionMap MemberUnions;
3976
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003977 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00003978 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003979 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00003980
Abramo Bagnara341d7832010-05-26 18:09:23 +00003981 // Set the source order index.
3982 Init->setSourceOrder(i);
3983
Francois Pichetd583da02010-12-04 09:14:42 +00003984 if (Init->isAnyMemberInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003985 const void *Key = GetKeyForMember(Context, Init);
3986 if (CheckRedundantInit(*this, Init, Members[Key]) ||
John McCall23eebd92010-04-10 09:28:51 +00003987 CheckRedundantUnionInit(*this, Init, MemberUnions))
3988 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003989 } else if (Init->isBaseInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003990 const void *Key = GetKeyForMember(Context, Init);
John McCall23eebd92010-04-10 09:28:51 +00003991 if (CheckRedundantInit(*this, Init, Members[Key]))
3992 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003993 } else {
3994 assert(Init->isDelegatingInitializer());
3995 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00003996 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00003997 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00003998 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00003999 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00004000 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00004001 }
Alexis Hunt6118d662011-05-04 05:57:24 +00004002 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00004003 // Return immediately as the initializer is set.
4004 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004005 }
Anders Carlssone857b292010-04-02 03:37:03 +00004006 }
4007
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004008 if (HadError)
4009 return;
4010
David Blaikie3fc2f912013-01-17 05:26:25 +00004011 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00004012
David Blaikie3fc2f912013-01-17 05:26:25 +00004013 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00004014
Richard Trieuef64e942013-10-25 00:56:00 +00004015 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00004016}
4017
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004018void
John McCalla6309952010-03-16 21:39:52 +00004019Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4020 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00004021 // Ignore dependent contexts. Also ignore unions, since their members never
4022 // have destructors implicitly called.
4023 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00004024 return;
John McCall1064d7e2010-03-16 05:22:47 +00004025
4026 // FIXME: all the access-control diagnostics are positioned on the
4027 // field/base declaration. That's probably good; that said, the
4028 // user might reasonably want to know why the destructor is being
4029 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00004030
Anders Carlssondee9a302009-11-17 04:44:12 +00004031 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004032 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00004033 if (Field->isInvalidDecl())
4034 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004035
4036 // Don't destroy incomplete or zero-length arrays.
4037 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4038 continue;
4039
Anders Carlssondee9a302009-11-17 04:44:12 +00004040 QualType FieldType = Context.getBaseElementType(Field->getType());
4041
4042 const RecordType* RT = FieldType->getAs<RecordType>();
4043 if (!RT)
4044 continue;
4045
4046 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004047 if (FieldClassDecl->isInvalidDecl())
4048 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004049 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004050 continue;
Richard Smith921bd202012-02-26 09:11:52 +00004051 // The destructor for an implicit anonymous union member is never invoked.
4052 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4053 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00004054
Douglas Gregore71edda2010-07-01 22:47:18 +00004055 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004056 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004057 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004058 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00004059 << Field->getDeclName()
4060 << FieldType);
4061
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004062 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004063 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004064 }
4065
John McCall1064d7e2010-03-16 05:22:47 +00004066 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4067
Anders Carlssondee9a302009-11-17 04:44:12 +00004068 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004069 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004070 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00004071 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004072
4073 // Remember direct virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004074 if (Base.isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00004075 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00004076
John McCall1064d7e2010-03-16 05:22:47 +00004077 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004078 // If our base class is invalid, we probably can't get its dtor anyway.
4079 if (BaseClassDecl->isInvalidDecl())
4080 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004081 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004082 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004083
Douglas Gregore71edda2010-07-01 22:47:18 +00004084 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004085 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004086
4087 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00004088 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004089 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00004090 << Base.getType()
4091 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00004092 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00004093
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004094 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004095 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004096 }
4097
4098 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004099 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004100 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00004101 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004102
4103 // Ignore direct virtual bases.
4104 if (DirectVirtualBases.count(RT))
4105 continue;
4106
John McCall1064d7e2010-03-16 05:22:47 +00004107 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004108 // If our base class is invalid, we probably can't get its dtor anyway.
4109 if (BaseClassDecl->isInvalidDecl())
4110 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004111 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004112 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004113
Douglas Gregore71edda2010-07-01 22:47:18 +00004114 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004115 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00004116 if (CheckDestructorAccess(
4117 ClassDecl->getLocation(), Dtor,
4118 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00004119 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004120 Context.getTypeDeclType(ClassDecl)) ==
4121 AR_accessible) {
4122 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00004123 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004124 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00004125 SourceRange(), DeclarationName(), nullptr);
David Majnemer626032f2013-06-22 06:43:58 +00004126 }
John McCall1064d7e2010-03-16 05:22:47 +00004127
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004128 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004129 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004130 }
4131}
4132
John McCall48871652010-08-21 09:40:31 +00004133void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00004134 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004135 return;
Mike Stump11289f42009-09-09 15:08:12 +00004136
Mike Stump11289f42009-09-09 15:08:12 +00004137 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00004138 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00004139 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00004140 DiagnoseUninitializedFields(*this, Constructor);
4141 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004142}
4143
Mike Stump11289f42009-09-09 15:08:12 +00004144bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00004145 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregorae298422012-05-04 17:09:59 +00004146 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4147 unsigned DiagID;
4148 AbstractDiagSelID SelID;
4149
4150 public:
4151 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4152 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004153
Craig Toppera798a9d2014-03-02 09:32:10 +00004154 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004155 if (Suppressed) return;
Douglas Gregorae298422012-05-04 17:09:59 +00004156 if (SelID == -1)
4157 S.Diag(Loc, DiagID) << T;
4158 else
4159 S.Diag(Loc, DiagID) << SelID << T;
4160 }
4161 } Diagnoser(DiagID, SelID);
4162
4163 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004164}
4165
Anders Carlssoneabf7702009-08-27 00:13:57 +00004166bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregorae298422012-05-04 17:09:59 +00004167 TypeDiagnoser &Diagnoser) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004168 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004169 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004170
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004171 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregorae298422012-05-04 17:09:59 +00004172 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004173
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004174 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004175 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004176 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004177 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00004178
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004179 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregorae298422012-05-04 17:09:59 +00004180 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004181 }
Mike Stump11289f42009-09-09 15:08:12 +00004182
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004183 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004184 if (!RT)
4185 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004186
John McCall67da35c2010-02-04 22:26:26 +00004187 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004188
John McCall02db245d2010-08-18 09:41:07 +00004189 // We can't answer whether something is abstract until it has a
4190 // definition. If it's currently being defined, we'll walk back
4191 // over all the declarations when we have a full definition.
4192 const CXXRecordDecl *Def = RD->getDefinition();
4193 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00004194 return false;
4195
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004196 if (!RD->isAbstract())
4197 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004198
Douglas Gregorae298422012-05-04 17:09:59 +00004199 Diagnoser.diagnose(*this, Loc, T);
John McCall02db245d2010-08-18 09:41:07 +00004200 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00004201
John McCall02db245d2010-08-18 09:41:07 +00004202 return true;
4203}
4204
4205void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4206 // Check if we've already emitted the list of pure virtual functions
4207 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004208 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00004209 return;
Mike Stump11289f42009-09-09 15:08:12 +00004210
Richard Smithbc46e432013-07-22 02:56:56 +00004211 // If the diagnostic is suppressed, don't emit the notes. We're only
4212 // going to emit them once, so try to attach them to a diagnostic we're
4213 // actually going to show.
4214 if (Diags.isLastDiagnosticIgnored())
4215 return;
4216
Douglas Gregor4165bd62010-03-23 23:47:56 +00004217 CXXFinalOverriderMap FinalOverriders;
4218 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00004219
Anders Carlssona2f74f32010-06-03 01:00:02 +00004220 // Keep a set of seen pure methods so we won't diagnose the same method
4221 // more than once.
4222 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4223
Douglas Gregor4165bd62010-03-23 23:47:56 +00004224 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4225 MEnd = FinalOverriders.end();
4226 M != MEnd;
4227 ++M) {
4228 for (OverridingMethods::iterator SO = M->second.begin(),
4229 SOEnd = M->second.end();
4230 SO != SOEnd; ++SO) {
4231 // C++ [class.abstract]p4:
4232 // A class is abstract if it contains or inherits at least one
4233 // pure virtual function for which the final overrider is pure
4234 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00004235
Douglas Gregor4165bd62010-03-23 23:47:56 +00004236 //
4237 if (SO->second.size() != 1)
4238 continue;
4239
4240 if (!SO->second.front().Method->isPure())
4241 continue;
4242
Anders Carlssona2f74f32010-06-03 01:00:02 +00004243 if (!SeenPureMethods.insert(SO->second.front().Method))
4244 continue;
4245
Douglas Gregor4165bd62010-03-23 23:47:56 +00004246 Diag(SO->second.front().Method->getLocation(),
4247 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00004248 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00004249 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004250 }
4251
4252 if (!PureVirtualClassDiagSet)
4253 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4254 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004255}
4256
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004257namespace {
John McCall02db245d2010-08-18 09:41:07 +00004258struct AbstractUsageInfo {
4259 Sema &S;
4260 CXXRecordDecl *Record;
4261 CanQualType AbstractType;
4262 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00004263
John McCall02db245d2010-08-18 09:41:07 +00004264 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4265 : S(S), Record(Record),
4266 AbstractType(S.Context.getCanonicalType(
4267 S.Context.getTypeDeclType(Record))),
4268 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004269
John McCall02db245d2010-08-18 09:41:07 +00004270 void DiagnoseAbstractType() {
4271 if (Invalid) return;
4272 S.DiagnoseAbstractType(Record);
4273 Invalid = true;
4274 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00004275
John McCall02db245d2010-08-18 09:41:07 +00004276 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4277};
4278
4279struct CheckAbstractUsage {
4280 AbstractUsageInfo &Info;
4281 const NamedDecl *Ctx;
4282
4283 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4284 : Info(Info), Ctx(Ctx) {}
4285
4286 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4287 switch (TL.getTypeLocClass()) {
4288#define ABSTRACT_TYPELOC(CLASS, PARENT)
4289#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00004290 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00004291#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004292 }
John McCall02db245d2010-08-18 09:41:07 +00004293 }
Mike Stump11289f42009-09-09 15:08:12 +00004294
John McCall02db245d2010-08-18 09:41:07 +00004295 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00004296 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004297 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4298 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00004299 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004300
4301 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00004302 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004303 }
John McCall02db245d2010-08-18 09:41:07 +00004304 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004305
John McCall02db245d2010-08-18 09:41:07 +00004306 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4307 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4308 }
Mike Stump11289f42009-09-09 15:08:12 +00004309
John McCall02db245d2010-08-18 09:41:07 +00004310 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4311 // Visit the type parameters from a permissive context.
4312 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4313 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4314 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4315 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4316 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4317 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004318 }
John McCall02db245d2010-08-18 09:41:07 +00004319 }
Mike Stump11289f42009-09-09 15:08:12 +00004320
John McCall02db245d2010-08-18 09:41:07 +00004321 // Visit pointee types from a permissive context.
4322#define CheckPolymorphic(Type) \
4323 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4324 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4325 }
4326 CheckPolymorphic(PointerTypeLoc)
4327 CheckPolymorphic(ReferenceTypeLoc)
4328 CheckPolymorphic(MemberPointerTypeLoc)
4329 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00004330 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00004331
John McCall02db245d2010-08-18 09:41:07 +00004332 /// Handle all the types we haven't given a more specific
4333 /// implementation for above.
4334 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4335 // Every other kind of type that we haven't called out already
4336 // that has an inner type is either (1) sugar or (2) contains that
4337 // inner type in some way as a subobject.
4338 if (TypeLoc Next = TL.getNextTypeLoc())
4339 return Visit(Next, Sel);
4340
4341 // If there's no inner type and we're in a permissive context,
4342 // don't diagnose.
4343 if (Sel == Sema::AbstractNone) return;
4344
4345 // Check whether the type matches the abstract type.
4346 QualType T = TL.getType();
4347 if (T->isArrayType()) {
4348 Sel = Sema::AbstractArrayType;
4349 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004350 }
John McCall02db245d2010-08-18 09:41:07 +00004351 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4352 if (CT != Info.AbstractType) return;
4353
4354 // It matched; do some magic.
4355 if (Sel == Sema::AbstractArrayType) {
4356 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4357 << T << TL.getSourceRange();
4358 } else {
4359 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4360 << Sel << T << TL.getSourceRange();
4361 }
4362 Info.DiagnoseAbstractType();
4363 }
4364};
4365
4366void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4367 Sema::AbstractDiagSelID Sel) {
4368 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4369}
4370
4371}
4372
4373/// Check for invalid uses of an abstract type in a method declaration.
4374static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4375 CXXMethodDecl *MD) {
4376 // No need to do the check on definitions, which require that
4377 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004378 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00004379 return;
4380
4381 // For safety's sake, just ignore it if we don't have type source
4382 // information. This should never happen for non-implicit methods,
4383 // but...
4384 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4385 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4386}
4387
4388/// Check for invalid uses of an abstract type within a class definition.
4389static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4390 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00004391 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00004392 if (D->isImplicit()) continue;
4393
4394 // Methods and method templates.
4395 if (isa<CXXMethodDecl>(D)) {
4396 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4397 } else if (isa<FunctionTemplateDecl>(D)) {
4398 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4399 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4400
4401 // Fields and static variables.
4402 } else if (isa<FieldDecl>(D)) {
4403 FieldDecl *FD = cast<FieldDecl>(D);
4404 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4405 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4406 } else if (isa<VarDecl>(D)) {
4407 VarDecl *VD = cast<VarDecl>(D);
4408 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4409 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4410
4411 // Nested classes and class templates.
4412 } else if (isa<CXXRecordDecl>(D)) {
4413 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4414 } else if (isa<ClassTemplateDecl>(D)) {
4415 CheckAbstractClassUsage(Info,
4416 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4417 }
4418 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004419}
4420
Hans Wennborg853ae942014-05-30 16:59:42 +00004421/// \brief Check class-level dllimport/dllexport attribute.
4422static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) {
4423 Attr *ClassAttr = getDLLAttr(Class);
Hans Wennborg205c39b2014-08-23 22:34:43 +00004424
4425 // MSVC inherits DLL attributes to partial class template specializations.
4426 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
4427 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4428 if (Attr *TemplateAttr =
4429 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
4430 auto *A = cast<InheritableAttr>(TemplateAttr->clone(S.getASTContext()));
4431 A->setInherited(true);
4432 ClassAttr = A;
4433 }
4434 }
4435 }
4436
Hans Wennborg853ae942014-05-30 16:59:42 +00004437 if (!ClassAttr)
4438 return;
4439
4440 bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4441
4442 // Force declaration of implicit members so they can inherit the attribute.
4443 S.ForceDeclarationOfImplicitMembers(Class);
4444
4445 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4446 // seem to be true in practice?
4447
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004448 TemplateSpecializationKind TSK =
4449 Class->getTemplateSpecializationKind();
4450
Hans Wennborg853ae942014-05-30 16:59:42 +00004451 for (Decl *Member : Class->decls()) {
Hans Wennborge8ad3832014-06-11 22:44:39 +00004452 VarDecl *VD = dyn_cast<VarDecl>(Member);
4453 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4454
4455 // Only methods and static fields inherit the attributes.
4456 if (!VD && !MD)
Hans Wennborg853ae942014-05-30 16:59:42 +00004457 continue;
Hans Wennborge8ad3832014-06-11 22:44:39 +00004458
4459 // Don't process deleted methods.
4460 if (MD && MD->isDeleted())
Hans Wennborg9d06a8d2014-06-10 17:53:23 +00004461 continue;
Hans Wennborg853ae942014-05-30 16:59:42 +00004462
Hans Wennborge8ad3832014-06-11 22:44:39 +00004463 if (MD && MD->isMoveAssignmentOperator() && !ClassExported &&
4464 MD->isInlined()) {
4465 // Current MSVC versions don't export the move assignment operators, so
4466 // don't attempt to import them if we have a definition.
4467 continue;
4468 }
4469
Hans Wennborg496524b2014-05-31 02:08:49 +00004470 if (InheritableAttr *MemberAttr = getDLLAttr(Member)) {
4471 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00004472 !MemberAttr->isInherited() && !ClassAttr->isInherited()) {
Hans Wennborg496524b2014-05-31 02:08:49 +00004473 S.Diag(MemberAttr->getLocation(),
4474 diag::err_attribute_dll_member_of_dll_class)
4475 << MemberAttr << ClassAttr;
4476 S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4477 Member->setInvalidDecl();
4478 continue;
4479 }
4480 } else {
4481 auto *NewAttr =
4482 cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
4483 NewAttr->setInherited(true);
4484 Member->addAttr(NewAttr);
4485 }
Hans Wennborg853ae942014-05-30 16:59:42 +00004486
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004487 if (MD && ClassExported) {
4488 if (MD->isUserProvided()) {
4489 // Instantiate non-default methods..
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004490
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004491 // .. except for certain kinds of template specializations.
4492 if (TSK == TSK_ExplicitInstantiationDeclaration)
4493 continue;
4494 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4495 continue;
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004496
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004497 S.MarkFunctionReferenced(Class->getLocation(), MD);
4498 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4499 MD->isCopyAssignmentOperator() ||
4500 MD->isMoveAssignmentOperator()) {
4501 // Instantiate non-trivial or explicitly defaulted methods, and the
4502 // copy assignment / move assignment operators.
4503 S.MarkFunctionReferenced(Class->getLocation(), MD);
4504 // Resolve its exception specification; CodeGen needs it.
4505 auto *FPT = MD->getType()->getAs<FunctionProtoType>();
4506 S.ResolveExceptionSpec(Class->getLocation(), FPT);
4507 S.ActOnFinishInlineMethodDef(MD);
Hans Wennborg853ae942014-05-30 16:59:42 +00004508 }
4509 }
4510 }
4511}
4512
Douglas Gregorc99f1552009-12-03 18:33:45 +00004513/// \brief Perform semantic checks on a class definition that has been
4514/// completing, introducing implicitly-declared members, checking for
4515/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004516void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00004517 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00004518 return;
4519
John McCall02db245d2010-08-18 09:41:07 +00004520 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4521 AbstractUsageInfo Info(*this, Record);
4522 CheckAbstractClassUsage(Info, Record);
4523 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00004524
4525 // If this is not an aggregate type and has no user-declared constructor,
4526 // complain about any non-static data members of reference or const scalar
4527 // type, since they will never get initializers.
4528 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00004529 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4530 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004531 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004532 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004533 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004534 continue;
4535
Douglas Gregor454a5b62010-04-15 00:00:53 +00004536 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00004537 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004538 if (!Complained) {
4539 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4540 << Record->getTagKind() << Record;
4541 Complained = true;
4542 }
4543
4544 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4545 << F->getType()->isReferenceType()
4546 << F->getDeclName();
4547 }
4548 }
4549 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004550
Anders Carlssone771e762011-01-25 18:08:22 +00004551 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00004552 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00004553
4554 if (Record->getIdentifier()) {
4555 // C++ [class.mem]p13:
4556 // If T is the name of a class, then each of the following shall have a
4557 // name different from T:
4558 // - every member of every anonymous union that is a member of class T.
4559 //
4560 // C++ [class.mem]p14:
4561 // In addition, if class T has a user-declared constructor (12.1), every
4562 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00004563 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4564 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4565 ++I) {
4566 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004567 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4568 isa<IndirectFieldDecl>(D)) {
4569 Diag(D->getLocation(), diag::err_member_name_of_class)
4570 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00004571 break;
4572 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00004573 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00004574 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004575
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004576 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00004577 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004578 CXXDestructorDecl *dtor = Record->getDestructor();
David Blaikie04e2e662014-05-09 22:02:28 +00004579 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4580 !Record->hasAttr<FinalAttr>())
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004581 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4582 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4583 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004584
David Majnemera5433082013-10-18 00:33:31 +00004585 if (Record->isAbstract()) {
4586 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4587 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4588 << FA->isSpelledAsSealed();
4589 DiagnoseAbstractType(Record);
4590 }
David Blaikie348df502012-09-21 03:21:07 +00004591 }
4592
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004593 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004594 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00004595 // See if a method overloads virtual methods in a base
4596 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004597 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004598 DiagnoseHiddenVirtualMethods(M);
Richard Smithbd305122012-12-11 01:14:52 +00004599
4600 // Check whether the explicitly-defaulted special members are valid.
4601 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004602 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004603
4604 // For an explicitly defaulted or deleted special member, we defer
4605 // determining triviality until the class is complete. That time is now!
4606 if (!M->isImplicit() && !M->isUserProvided()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004607 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004608 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004609 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00004610
4611 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00004612 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004613 }
4614 }
4615 }
4616 }
4617
4618 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4619 // function that is not a constructor declares that member function to be
4620 // const. [...] The class of which that function is a member shall be
4621 // a literal type.
4622 //
4623 // If the class has virtual bases, any constexpr members will already have
4624 // been diagnosed by the checks performed on the member declaration, so
4625 // suppress this (less useful) diagnostic.
4626 //
4627 // We delay this until we know whether an explicitly-defaulted (or deleted)
4628 // destructor for the class is trivial.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004629 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smithbd305122012-12-11 01:14:52 +00004630 !Record->isLiteral() && !Record->getNumVBases()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004631 for (const auto *M : Record->methods()) {
4632 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) {
Richard Smithbd305122012-12-11 01:14:52 +00004633 switch (Record->getTemplateSpecializationKind()) {
4634 case TSK_ImplicitInstantiation:
4635 case TSK_ExplicitInstantiationDeclaration:
4636 case TSK_ExplicitInstantiationDefinition:
4637 // If a template instantiates to a non-literal type, but its members
4638 // instantiate to constexpr functions, the template is technically
4639 // ill-formed, but we allow it for sanity.
4640 continue;
4641
4642 case TSK_Undeclared:
4643 case TSK_ExplicitSpecialization:
4644 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4645 diag::err_constexpr_method_non_literal);
4646 break;
4647 }
4648
4649 // Only produce one error per class.
4650 break;
4651 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004652 }
4653 }
Sebastian Redl08905022011-02-05 19:23:19 +00004654
John McCall95833f32014-02-27 20:30:49 +00004655 // ms_struct is a request to use the same ABI rules as MSVC. Check
4656 // whether this class uses any C++ features that are implemented
4657 // completely differently in MSVC, and if so, emit a diagnostic.
4658 // That diagnostic defaults to an error, but we allow projects to
4659 // map it down to a warning (or ignore it). It's a fairly common
4660 // practice among users of the ms_struct pragma to mass-annotate
4661 // headers, sweeping up a bunch of types that the project doesn't
4662 // really rely on MSVC-compatible layout for. We must therefore
4663 // support "ms_struct except for C++ stuff" as a secondary ABI.
4664 if (Record->isMsStruct(Context) &&
4665 (Record->isPolymorphic() || Record->getNumBases())) {
4666 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00004667 }
4668
Richard Smithc2bc61b2013-03-18 21:12:30 +00004669 // Declare inheriting constructors. We do this eagerly here because:
4670 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redl08905022011-02-05 19:23:19 +00004671 // constructors from different classes.
4672 // - The lazy declaration of the other implicit constructors is so as to not
4673 // waste space and performance on classes that are not meant to be
4674 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smithc2bc61b2013-03-18 21:12:30 +00004675 // have inheriting constructors.
4676 DeclareInheritingConstructors(Record);
Hans Wennborg853ae942014-05-30 16:59:42 +00004677
4678 checkDLLAttribute(*this, Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004679}
4680
Richard Smith41c35d62013-11-27 03:39:20 +00004681/// Look up the special member function that would be called by a special
4682/// member function for a subobject of class type.
4683///
4684/// \param Class The class type of the subobject.
4685/// \param CSM The kind of special member function.
4686/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4687/// \param ConstRHS True if this is a copy operation with a const object
4688/// on its RHS, that is, if the argument to the outer special member
4689/// function is 'const' and this is not a field marked 'mutable'.
4690static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4691 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4692 unsigned FieldQuals, bool ConstRHS) {
4693 unsigned LHSQuals = 0;
4694 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4695 LHSQuals = FieldQuals;
4696
4697 unsigned RHSQuals = FieldQuals;
4698 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4699 RHSQuals = 0;
4700 else if (ConstRHS)
4701 RHSQuals |= Qualifiers::Const;
4702
4703 return S.LookupSpecialMember(Class, CSM,
4704 RHSQuals & Qualifiers::Const,
4705 RHSQuals & Qualifiers::Volatile,
4706 false,
4707 LHSQuals & Qualifiers::Const,
4708 LHSQuals & Qualifiers::Volatile);
4709}
4710
Richard Smithb5800092012-06-10 05:43:50 +00004711/// Is the special member function which would be selected to perform the
4712/// specified operation on the specified class type a constexpr constructor?
4713static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4714 Sema::CXXSpecialMember CSM,
Richard Smith41c35d62013-11-27 03:39:20 +00004715 unsigned Quals, bool ConstRHS) {
Richard Smithb5800092012-06-10 05:43:50 +00004716 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00004717 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00004718 if (!SMOR || !SMOR->getMethod())
4719 // A constructor we wouldn't select can't be "involved in initializing"
4720 // anything.
4721 return true;
4722 return SMOR->getMethod()->isConstexpr();
4723}
4724
4725/// Determine whether the specified special member function would be constexpr
4726/// if it were implicitly defined.
4727static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4728 Sema::CXXSpecialMember CSM,
4729 bool ConstArg) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004730 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00004731 return false;
4732
4733 // C++11 [dcl.constexpr]p4:
4734 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00004735 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00004736 switch (CSM) {
4737 case Sema::CXXDefaultConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004738 // Since default constructor lookup is essentially trivial (and cannot
4739 // involve, for instance, template instantiation), we compute whether a
4740 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4741 //
4742 // This is important for performance; we need to know whether the default
4743 // constructor is constexpr to determine whether the type is a literal type.
4744 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4745
Richard Smithb5800092012-06-10 05:43:50 +00004746 case Sema::CXXCopyConstructor:
4747 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004748 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00004749 break;
4750
4751 case Sema::CXXCopyAssignment:
4752 case Sema::CXXMoveAssignment:
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004753 if (!S.getLangOpts().CPlusPlus14)
Richard Smith99005e62013-05-07 03:19:20 +00004754 return false;
4755 // In C++1y, we need to perform overload resolution.
4756 Ctor = false;
4757 break;
4758
Richard Smithb5800092012-06-10 05:43:50 +00004759 case Sema::CXXDestructor:
4760 case Sema::CXXInvalid:
4761 return false;
4762 }
4763
4764 // -- if the class is a non-empty union, or for each non-empty anonymous
4765 // union member of a non-union class, exactly one non-static data member
4766 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00004767 //
4768 // If we squint, this is guaranteed, since exactly one non-static data member
4769 // will be initialized (if the constructor isn't deleted), we just don't know
4770 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00004771 if (Ctor && ClassDecl->isUnion())
Richard Smith4086a132012-06-10 07:07:24 +00004772 return true;
Richard Smithb5800092012-06-10 05:43:50 +00004773
4774 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00004775 if (Ctor && ClassDecl->getNumVBases())
4776 return false;
4777
4778 // C++1y [class.copy]p26:
4779 // -- [the class] is a literal type, and
4780 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00004781 return false;
4782
4783 // -- every constructor involved in initializing [...] base class
4784 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00004785 // -- the assignment operator selected to copy/move each direct base
4786 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00004787 for (const auto &B : ClassDecl->bases()) {
4788 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00004789 if (!BaseType) continue;
4790
4791 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004792 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smithb5800092012-06-10 05:43:50 +00004793 return false;
4794 }
4795
4796 // -- every constructor involved in initializing non-static data members
4797 // [...] shall be a constexpr constructor;
4798 // -- every non-static data member and base class sub-object shall be
4799 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00004800 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00004801 // thereof), the assignment operator selected to copy/move that member is
4802 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004803 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00004804 if (F->isInvalidDecl())
4805 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00004806 QualType BaseType = S.Context.getBaseElementType(F->getType());
4807 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00004808 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00004809 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
4810 BaseType.getCVRQualifiers(),
4811 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00004812 return false;
Richard Smithb5800092012-06-10 05:43:50 +00004813 }
4814 }
4815
4816 // All OK, it's constexpr!
4817 return true;
4818}
4819
Richard Smithd3b5c9082012-07-27 04:22:15 +00004820static Sema::ImplicitExceptionSpecification
4821computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4822 switch (S.getSpecialMember(MD)) {
4823 case Sema::CXXDefaultConstructor:
4824 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4825 case Sema::CXXCopyConstructor:
4826 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4827 case Sema::CXXCopyAssignment:
4828 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4829 case Sema::CXXMoveConstructor:
4830 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4831 case Sema::CXXMoveAssignment:
4832 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4833 case Sema::CXXDestructor:
4834 return S.ComputeDefaultedDtorExceptionSpec(MD);
4835 case Sema::CXXInvalid:
4836 break;
4837 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00004838 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4839 "only special members have implicit exception specs");
4840 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00004841}
4842
Reid Kleckner78af0702013-08-27 23:08:25 +00004843static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4844 CXXMethodDecl *MD) {
4845 FunctionProtoType::ExtProtoInfo EPI;
4846
4847 // Build an exception specification pointing back at this member.
Richard Smith8acb4282014-07-31 21:57:55 +00004848 EPI.ExceptionSpec.Type = EST_Unevaluated;
4849 EPI.ExceptionSpec.SourceDecl = MD;
Reid Kleckner78af0702013-08-27 23:08:25 +00004850
4851 // Set the calling convention to the default for C++ instance methods.
4852 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4853 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4854 /*IsCXXMethod=*/true));
4855 return EPI;
4856}
4857
Richard Smithd3b5c9082012-07-27 04:22:15 +00004858void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4859 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4860 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4861 return;
4862
Richard Smith7f782272012-07-30 23:48:14 +00004863 // Evaluate the exception specification.
Richard Smith8acb4282014-07-31 21:57:55 +00004864 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
Richard Smith564417a2014-03-20 21:47:22 +00004865
Richard Smith7f782272012-07-30 23:48:14 +00004866 // Update the type of the special member to use it.
Richard Smith8acb4282014-07-31 21:57:55 +00004867 UpdateExceptionSpec(MD, ESI);
Richard Smith7f782272012-07-30 23:48:14 +00004868
4869 // A user-provided destructor can be defined outside the class. When that
4870 // happens, be sure to update the exception specification on both
4871 // declarations.
4872 const FunctionProtoType *CanonicalFPT =
4873 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4874 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smith8acb4282014-07-31 21:57:55 +00004875 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00004876}
4877
Richard Smithb9e90b12012-05-15 04:39:51 +00004878void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4879 CXXRecordDecl *RD = MD->getParent();
4880 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004881
Richard Smithb9e90b12012-05-15 04:39:51 +00004882 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4883 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00004884
4885 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00004886 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00004887 bool First = MD == MD->getCanonicalDecl();
4888
4889 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004890
4891 // C++11 [dcl.fct.def.default]p1:
4892 // A function that is explicitly defaulted shall
4893 // -- be a special member function (checked elsewhere),
4894 // -- have the same type (except for ref-qualifiers, and except that a
4895 // copy operation can take a non-const reference) as an implicit
4896 // declaration, and
4897 // -- not have default arguments.
4898 unsigned ExpectedParams = 1;
4899 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4900 ExpectedParams = 0;
4901 if (MD->getNumParams() != ExpectedParams) {
4902 // This also checks for default arguments: a copy or move constructor with a
4903 // default argument is classified as a default constructor, and assignment
4904 // operations and destructors can't have default arguments.
4905 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4906 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00004907 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00004908 } else if (MD->isVariadic()) {
4909 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4910 << CSM << MD->getSourceRange();
4911 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00004912 }
4913
Richard Smithb9e90b12012-05-15 04:39:51 +00004914 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00004915
Richard Smithb5800092012-06-10 05:43:50 +00004916 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00004917 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00004918 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00004919 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00004920 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00004921
Richard Smithb9e90b12012-05-15 04:39:51 +00004922 QualType ReturnType = Context.VoidTy;
4923 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4924 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00004925 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00004926 QualType ExpectedReturnType =
4927 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4928 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4929 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4930 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4931 HadError = true;
4932 }
4933
4934 // A defaulted special member cannot have cv-qualifiers.
4935 if (Type->getTypeQuals()) {
4936 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004937 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
Richard Smithb9e90b12012-05-15 04:39:51 +00004938 HadError = true;
4939 }
4940 }
4941
4942 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00004943 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00004944 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00004945 if (ExpectedParams && ArgType->isReferenceType()) {
4946 // Argument must be reference to possibly-const T.
4947 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00004948 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00004949
4950 if (ReferentType.isVolatileQualified()) {
4951 Diag(MD->getLocation(),
4952 diag::err_defaulted_special_member_volatile_param) << CSM;
4953 HadError = true;
4954 }
4955
Richard Smithb5800092012-06-10 05:43:50 +00004956 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00004957 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4958 Diag(MD->getLocation(),
4959 diag::err_defaulted_special_member_copy_const_param)
4960 << (CSM == CXXCopyAssignment);
4961 // FIXME: Explain why this special member can't be const.
4962 } else {
4963 Diag(MD->getLocation(),
4964 diag::err_defaulted_special_member_move_const_param)
4965 << (CSM == CXXMoveAssignment);
4966 }
4967 HadError = true;
4968 }
Richard Smithb9e90b12012-05-15 04:39:51 +00004969 } else if (ExpectedParams) {
4970 // A copy assignment operator can take its argument by value, but a
4971 // defaulted one cannot.
4972 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00004973 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00004974 HadError = true;
4975 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00004976
Richard Smithcc36f692011-12-22 02:22:31 +00004977 // C++11 [dcl.fct.def.default]p2:
4978 // An explicitly-defaulted function may be declared constexpr only if it
4979 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00004980 // Do not apply this rule to members of class templates, since core issue 1358
4981 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00004982 // functions which cannot be constexpr (for non-constructors in C++11 and for
4983 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00004984 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4985 HasConstParam);
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004986 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
Richard Smith99005e62013-05-07 03:19:20 +00004987 : isa<CXXConstructorDecl>(MD)) &&
4988 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00004989 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4990 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00004991 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00004992 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00004993 }
Richard Smithbd305122012-12-11 01:14:52 +00004994
Richard Smithcc36f692011-12-22 02:22:31 +00004995 // and may have an explicit exception-specification only if it is compatible
4996 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00004997 if (Type->hasExceptionSpec()) {
4998 // Delay the check if this is the first declaration of the special member,
4999 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00005000 if (First) {
5001 // If the exception specification needs to be instantiated, do so now,
5002 // before we clobber it with an EST_Unevaluated specification below.
5003 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5004 InstantiateExceptionSpec(MD->getLocStart(), MD);
5005 Type = MD->getType()->getAs<FunctionProtoType>();
5006 }
Richard Smithbd305122012-12-11 01:14:52 +00005007 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00005008 } else
Richard Smithbd305122012-12-11 01:14:52 +00005009 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5010 }
Richard Smithcc36f692011-12-22 02:22:31 +00005011
5012 // If a function is explicitly defaulted on its first declaration,
5013 if (First) {
5014 // -- it is implicitly considered to be constexpr if the implicit
5015 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00005016 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00005017
Richard Smithb9e90b12012-05-15 04:39:51 +00005018 // -- it is implicitly considered to have the same exception-specification
5019 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00005020 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00005021 EPI.ExceptionSpec.Type = EST_Unevaluated;
5022 EPI.ExceptionSpec.SourceDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00005023 MD->setType(Context.getFunctionType(ReturnType,
5024 ArrayRef<QualType>(&ArgType,
5025 ExpectedParams),
5026 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00005027 }
5028
Richard Smithb9e90b12012-05-15 04:39:51 +00005029 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00005030 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00005031 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00005032 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00005033 // C++11 [dcl.fct.def.default]p4:
5034 // [For a] user-provided explicitly-defaulted function [...] if such a
5035 // function is implicitly defined as deleted, the program is ill-formed.
5036 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith566184a2014-01-22 20:09:10 +00005037 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00005038 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00005039 }
5040 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00005041
Richard Smithb9e90b12012-05-15 04:39:51 +00005042 if (HadError)
5043 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00005044}
5045
Richard Smithbd305122012-12-11 01:14:52 +00005046/// Check whether the exception specification provided for an
5047/// explicitly-defaulted special member matches the exception specification
5048/// that would have been generated for an implicit special member, per
5049/// C++11 [dcl.fct.def.default]p2.
5050void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5051 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
5052 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00005053 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5054 /*IsCXXMethod=*/true);
5055 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smith8acb4282014-07-31 21:57:55 +00005056 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5057 .getExceptionSpec();
Richard Smithbd305122012-12-11 01:14:52 +00005058 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005059 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00005060
5061 // Ensure that it matches.
5062 CheckEquivalentExceptionSpec(
5063 PDiag(diag::err_incorrect_defaulted_exception_spec)
5064 << getSpecialMember(MD), PDiag(),
5065 ImplicitType, SourceLocation(),
5066 SpecifiedType, MD->getLocation());
5067}
5068
Alp Tokerae3a9442013-10-18 05:54:19 +00005069void Sema::CheckDelayedMemberExceptionSpecs() {
5070 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
5071 2> Checks;
5072 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
Richard Smithbd305122012-12-11 01:14:52 +00005073
Alp Tokerae3a9442013-10-18 05:54:19 +00005074 std::swap(Checks, DelayedDestructorExceptionSpecChecks);
5075 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5076
5077 // Perform any deferred checking of exception specifications for virtual
5078 // destructors.
5079 for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
5080 const CXXDestructorDecl *Dtor = Checks[i].first;
5081 assert(!Dtor->getParent()->isDependentType() &&
5082 "Should not ever add destructors of templates into the list.");
5083 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
5084 }
5085
5086 // Check that any explicitly-defaulted methods have exception specifications
5087 // compatible with their implicit exception specifications.
5088 for (unsigned I = 0, N = Specs.size(); I != N; ++I)
5089 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
5090 Specs[I].second);
Richard Smithbd305122012-12-11 01:14:52 +00005091}
5092
Richard Smithd951a1d2012-02-18 02:02:13 +00005093namespace {
5094struct SpecialMemberDeletionInfo {
5095 Sema &S;
5096 CXXMethodDecl *MD;
5097 Sema::CXXSpecialMember CSM;
Richard Smith852265f2012-03-30 20:53:28 +00005098 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00005099
5100 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00005101 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00005102 SourceLocation Loc;
5103
5104 bool AllFieldsAreConst;
5105
5106 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith852265f2012-03-30 20:53:28 +00005107 Sema::CXXSpecialMember CSM, bool Diagnose)
5108 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smithd951a1d2012-02-18 02:02:13 +00005109 IsConstructor(false), IsAssignment(false), IsMove(false),
Richard Smith41c35d62013-11-27 03:39:20 +00005110 ConstArg(false), Loc(MD->getLocation()),
Richard Smithd951a1d2012-02-18 02:02:13 +00005111 AllFieldsAreConst(true) {
5112 switch (CSM) {
5113 case Sema::CXXDefaultConstructor:
5114 case Sema::CXXCopyConstructor:
5115 IsConstructor = true;
5116 break;
5117 case Sema::CXXMoveConstructor:
5118 IsConstructor = true;
5119 IsMove = true;
5120 break;
5121 case Sema::CXXCopyAssignment:
5122 IsAssignment = true;
5123 break;
5124 case Sema::CXXMoveAssignment:
5125 IsAssignment = true;
5126 IsMove = true;
5127 break;
5128 case Sema::CXXDestructor:
5129 break;
5130 case Sema::CXXInvalid:
5131 llvm_unreachable("invalid special member kind");
5132 }
5133
5134 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00005135 if (const ReferenceType *RT =
5136 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5137 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00005138 }
5139 }
5140
5141 bool inUnion() const { return MD->getParent()->isUnion(); }
5142
5143 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00005144 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00005145 unsigned Quals, bool IsMutable) {
5146 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5147 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00005148 }
5149
Richard Smith852265f2012-03-30 20:53:28 +00005150 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00005151
Richard Smith852265f2012-03-30 20:53:28 +00005152 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00005153 bool shouldDeleteForField(FieldDecl *FD);
5154 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00005155
Richard Smithaf136f82012-07-18 03:51:16 +00005156 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5157 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00005158 bool shouldDeleteForSubobjectCall(Subobject Subobj,
5159 Sema::SpecialMemberOverloadResult *SMOR,
5160 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00005161
5162 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00005163};
5164}
5165
John McCalld4274212012-04-09 20:53:23 +00005166/// Is the given special member inaccessible when used on the given
5167/// sub-object.
5168bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5169 CXXMethodDecl *target) {
5170 /// If we're operating on a base class, the object type is the
5171 /// type of this special member.
5172 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005173 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00005174 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5175 objectTy = S.Context.getTypeDeclType(MD->getParent());
5176 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5177
5178 // If we're operating on a field, the object type is the type of the field.
5179 } else {
5180 objectTy = S.Context.getTypeDeclType(target->getParent());
5181 }
5182
5183 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5184}
5185
Richard Smith852265f2012-03-30 20:53:28 +00005186/// Check whether we should delete a special member due to the implicit
5187/// definition containing a call to a special member of a subobject.
5188bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5189 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5190 bool IsDtorCallInCtor) {
5191 CXXMethodDecl *Decl = SMOR->getMethod();
5192 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5193
5194 int DiagKind = -1;
5195
5196 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5197 DiagKind = !Decl ? 0 : 1;
5198 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5199 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00005200 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00005201 DiagKind = 3;
5202 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5203 !Decl->isTrivial()) {
5204 // A member of a union must have a trivial corresponding special member.
5205 // As a weird special case, a destructor call from a union's constructor
5206 // must be accessible and non-deleted, but need not be trivial. Such a
5207 // destructor is never actually called, but is semantically checked as
5208 // if it were.
5209 DiagKind = 4;
5210 }
5211
5212 if (DiagKind == -1)
5213 return false;
5214
5215 if (Diagnose) {
5216 if (Field) {
5217 S.Diag(Field->getLocation(),
5218 diag::note_deleted_special_member_class_subobject)
5219 << CSM << MD->getParent() << /*IsField*/true
5220 << Field << DiagKind << IsDtorCallInCtor;
5221 } else {
5222 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5223 S.Diag(Base->getLocStart(),
5224 diag::note_deleted_special_member_class_subobject)
5225 << CSM << MD->getParent() << /*IsField*/false
5226 << Base->getType() << DiagKind << IsDtorCallInCtor;
5227 }
5228
5229 if (DiagKind == 1)
5230 S.NoteDeletedFunction(Decl);
5231 // FIXME: Explain inaccessibility if DiagKind == 3.
5232 }
5233
5234 return true;
5235}
5236
Richard Smith921bd202012-02-26 09:11:52 +00005237/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00005238/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00005239bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00005240 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00005241 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00005242 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00005243
5244 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00005245 // -- any direct or virtual base class, or non-static data member with no
5246 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00005247 // either M has no default constructor or overload resolution as applied
5248 // to M's default constructor results in an ambiguity or in a function
5249 // that is deleted or inaccessible
5250 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5251 // -- a direct or virtual base class B that cannot be copied/moved because
5252 // overload resolution, as applied to B's corresponding special member,
5253 // results in an ambiguity or a function that is deleted or inaccessible
5254 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00005255 // C++11 [class.dtor]p5:
5256 // -- any direct or virtual base class [...] has a type with a destructor
5257 // that is deleted or inaccessible
5258 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005259 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00005260 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5261 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005262 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005263
Richard Smith852265f2012-03-30 20:53:28 +00005264 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5265 // -- any direct or virtual base class or non-static data member has a
5266 // type with a destructor that is deleted or inaccessible
5267 if (IsConstructor) {
5268 Sema::SpecialMemberOverloadResult *SMOR =
5269 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5270 false, false, false, false, false);
5271 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5272 return true;
5273 }
5274
Richard Smith921bd202012-02-26 09:11:52 +00005275 return false;
5276}
5277
5278/// Check whether we should delete a special member function due to the class
5279/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00005280bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005281 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smithaf136f82012-07-18 03:51:16 +00005282 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00005283}
5284
5285/// Check whether we should delete a special member function due to the class
5286/// having a particular non-static data member.
5287bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5288 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5289 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5290
5291 if (CSM == Sema::CXXDefaultConstructor) {
5292 // For a default constructor, all references must be initialized in-class
5293 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00005294 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5295 if (Diagnose)
5296 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5297 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005298 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005299 }
Richard Smith619ecdc2012-02-27 06:07:25 +00005300 // C++11 [class.ctor]p5: any non-variant non-static data member of
5301 // const-qualified type (or array thereof) with no
5302 // brace-or-equal-initializer does not have a user-provided default
5303 // constructor.
5304 if (!inUnion() && FieldType.isConstQualified() &&
5305 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00005306 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5307 if (Diagnose)
5308 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005309 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00005310 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005311 }
5312
5313 if (inUnion() && !FieldType.isConstQualified())
5314 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005315 } else if (CSM == Sema::CXXCopyConstructor) {
5316 // For a copy constructor, data members must not be of rvalue reference
5317 // type.
Richard Smith852265f2012-03-30 20:53:28 +00005318 if (FieldType->isRValueReferenceType()) {
5319 if (Diagnose)
5320 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5321 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00005322 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005323 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005324 } else if (IsAssignment) {
5325 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00005326 if (FieldType->isReferenceType()) {
5327 if (Diagnose)
5328 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5329 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005330 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005331 }
5332 if (!FieldRecord && FieldType.isConstQualified()) {
5333 // C++11 [class.copy]p23:
5334 // -- a non-static data member of const non-class type (or array thereof)
5335 if (Diagnose)
5336 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005337 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00005338 return true;
5339 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005340 }
5341
5342 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005343 // Some additional restrictions exist on the variant members.
5344 if (!inUnion() && FieldRecord->isUnion() &&
5345 FieldRecord->isAnonymousStructOrUnion()) {
5346 bool AllVariantFieldsAreConst = true;
5347
Richard Smith5704fe82012-03-29 19:00:10 +00005348 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005349 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005350 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00005351
5352 if (!UnionFieldType.isConstQualified())
5353 AllVariantFieldsAreConst = false;
5354
Richard Smith921bd202012-02-26 09:11:52 +00005355 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5356 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005357 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00005358 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00005359 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005360 }
5361
5362 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00005363 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005364 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005365 if (Diagnose)
5366 S.Diag(FieldRecord->getLocation(),
5367 diag::note_deleted_default_ctor_all_const)
5368 << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00005369 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005370 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005371
Richard Smith5704fe82012-03-29 19:00:10 +00005372 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00005373 // This is technically non-conformant, but sanity demands it.
5374 return false;
5375 }
5376
Richard Smithaf136f82012-07-18 03:51:16 +00005377 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5378 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00005379 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005380 }
5381
5382 return false;
5383}
5384
5385/// C++11 [class.ctor] p5:
5386/// A defaulted default constructor for a class X is defined as deleted if
5387/// X is a union and all of its variant members are of const-qualified type.
5388bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00005389 // This is a silly definition, because it gives an empty union a deleted
5390 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00005391 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005392 !MD->getParent()->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005393 if (Diagnose)
5394 S.Diag(MD->getParent()->getLocation(),
5395 diag::note_deleted_default_ctor_all_const)
5396 << MD->getParent() << /*not anonymous union*/0;
5397 return true;
5398 }
5399 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005400}
5401
5402/// Determine whether a defaulted special member function should be defined as
5403/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5404/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00005405bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5406 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00005407 if (MD->isInvalidDecl())
5408 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00005409 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00005410 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005411 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00005412 return false;
5413
Richard Smithd951a1d2012-02-18 02:02:13 +00005414 // C++11 [expr.lambda.prim]p19:
5415 // The closure type associated with a lambda-expression has a
5416 // deleted (8.4.3) default constructor and a deleted copy
5417 // assignment operator.
5418 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00005419 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5420 if (Diagnose)
5421 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00005422 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005423 }
5424
Richard Smith6f1e2c62012-04-02 20:59:25 +00005425 // For an anonymous struct or union, the copy and assignment special members
5426 // will never be used, so skip the check. For an anonymous union declared at
5427 // namespace scope, the constructor and destructor are used.
5428 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5429 RD->isAnonymousStructOrUnion())
5430 return false;
5431
Richard Smith852265f2012-03-30 20:53:28 +00005432 // C++11 [class.copy]p7, p18:
5433 // If the class definition declares a move constructor or move assignment
5434 // operator, an implicitly declared copy constructor or copy assignment
5435 // operator is defined as deleted.
5436 if (MD->isImplicit() &&
5437 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005438 CXXMethodDecl *UserDeclaredMove = nullptr;
Richard Smith852265f2012-03-30 20:53:28 +00005439
5440 // In Microsoft mode, a user-declared move only causes the deletion of the
5441 // corresponding copy operation, not both copy operations.
5442 if (RD->hasUserDeclaredMoveConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005443 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00005444 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005445
5446 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005447 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005448 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005449 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005450 break;
5451 }
5452 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005453 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005454 } else if (RD->hasUserDeclaredMoveAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005455 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00005456 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005457
5458 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005459 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005460 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005461 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005462 break;
5463 }
5464 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005465 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005466 }
5467
5468 if (UserDeclaredMove) {
5469 Diag(UserDeclaredMove->getLocation(),
5470 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00005471 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00005472 << UserDeclaredMove->isMoveAssignmentOperator();
5473 return true;
5474 }
5475 }
Alexis Huntd6da8762011-10-10 06:18:57 +00005476
Richard Smith6f1e2c62012-04-02 20:59:25 +00005477 // Do access control from the special member function
5478 ContextRAII MethodContext(*this, MD);
5479
Richard Smith921bd202012-02-26 09:11:52 +00005480 // C++11 [class.dtor]p5:
5481 // -- for a virtual destructor, lookup of the non-array deallocation function
5482 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00005483 if (CSM == CXXDestructor && MD->isVirtual()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005484 FunctionDecl *OperatorDelete = nullptr;
Richard Smith921bd202012-02-26 09:11:52 +00005485 DeclarationName Name =
5486 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5487 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00005488 OperatorDelete, false)) {
5489 if (Diagnose)
5490 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00005491 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005492 }
Richard Smith921bd202012-02-26 09:11:52 +00005493 }
5494
Richard Smith852265f2012-03-30 20:53:28 +00005495 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00005496
Aaron Ballman574705e2014-03-13 15:41:46 +00005497 for (auto &BI : RD->bases())
5498 if (!BI.isVirtual() &&
5499 SMI.shouldDeleteForBase(&BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005500 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005501
Richard Smithd1627032013-07-22 18:06:23 +00005502 // Per DR1611, do not consider virtual bases of constructors of abstract
5503 // classes, since we are not going to construct them.
Richard Smithbc46e432013-07-22 02:56:56 +00005504 if (!RD->isAbstract() || !SMI.IsConstructor) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005505 for (auto &BI : RD->vbases())
5506 if (SMI.shouldDeleteForBase(&BI))
Richard Smithbc46e432013-07-22 02:56:56 +00005507 return true;
5508 }
Alexis Huntea6f0322011-05-11 22:34:38 +00005509
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005510 for (auto *FI : RD->fields())
Richard Smithd951a1d2012-02-18 02:02:13 +00005511 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005512 SMI.shouldDeleteForField(FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00005513 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005514
Richard Smithd951a1d2012-02-18 02:02:13 +00005515 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00005516 return true;
5517
5518 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005519}
5520
Richard Smith92f241f2012-12-08 02:53:02 +00005521/// Perform lookup for a special member of the specified kind, and determine
5522/// whether it is trivial. If the triviality can be determined without the
5523/// lookup, skip it. This is intended for use when determining whether a
5524/// special member of a containing object is trivial, and thus does not ever
5525/// perform overload resolution for default constructors.
5526///
5527/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5528/// member that was most likely to be intended to be trivial, if any.
5529static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5530 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00005531 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00005532 if (Selected)
Craig Topperc3ec1492014-05-26 06:22:03 +00005533 *Selected = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005534
5535 switch (CSM) {
5536 case Sema::CXXInvalid:
5537 llvm_unreachable("not a special member");
5538
5539 case Sema::CXXDefaultConstructor:
5540 // C++11 [class.ctor]p5:
5541 // A default constructor is trivial if:
5542 // - all the [direct subobjects] have trivial default constructors
5543 //
5544 // Note, no overload resolution is performed in this case.
5545 if (RD->hasTrivialDefaultConstructor())
5546 return true;
5547
5548 if (Selected) {
5549 // If there's a default constructor which could have been trivial, dig it
5550 // out. Otherwise, if there's any user-provided default constructor, point
5551 // to that as an example of why there's not a trivial one.
Craig Topperc3ec1492014-05-26 06:22:03 +00005552 CXXConstructorDecl *DefCtor = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005553 if (RD->needsImplicitDefaultConstructor())
5554 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005555 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005556 if (!CI->isDefaultConstructor())
5557 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005558 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005559 if (!DefCtor->isUserProvided())
5560 break;
5561 }
5562
5563 *Selected = DefCtor;
5564 }
5565
5566 return false;
5567
5568 case Sema::CXXDestructor:
5569 // C++11 [class.dtor]p5:
5570 // A destructor is trivial if:
5571 // - all the direct [subobjects] have trivial destructors
5572 if (RD->hasTrivialDestructor())
5573 return true;
5574
5575 if (Selected) {
5576 if (RD->needsImplicitDestructor())
5577 S.DeclareImplicitDestructor(RD);
5578 *Selected = RD->getDestructor();
5579 }
5580
5581 return false;
5582
5583 case Sema::CXXCopyConstructor:
5584 // C++11 [class.copy]p12:
5585 // A copy constructor is trivial if:
5586 // - the constructor selected to copy each direct [subobject] is trivial
5587 if (RD->hasTrivialCopyConstructor()) {
5588 if (Quals == Qualifiers::Const)
5589 // We must either select the trivial copy constructor or reach an
5590 // ambiguity; no need to actually perform overload resolution.
5591 return true;
5592 } else if (!Selected) {
5593 return false;
5594 }
5595 // In C++98, we are not supposed to perform overload resolution here, but we
5596 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5597 // cases like B as having a non-trivial copy constructor:
5598 // struct A { template<typename T> A(T&); };
5599 // struct B { mutable A a; };
5600 goto NeedOverloadResolution;
5601
5602 case Sema::CXXCopyAssignment:
5603 // C++11 [class.copy]p25:
5604 // A copy assignment operator is trivial if:
5605 // - the assignment operator selected to copy each direct [subobject] is
5606 // trivial
5607 if (RD->hasTrivialCopyAssignment()) {
5608 if (Quals == Qualifiers::Const)
5609 return true;
5610 } else if (!Selected) {
5611 return false;
5612 }
5613 // In C++98, we are not supposed to perform overload resolution here, but we
5614 // treat that as a language defect.
5615 goto NeedOverloadResolution;
5616
5617 case Sema::CXXMoveConstructor:
5618 case Sema::CXXMoveAssignment:
5619 NeedOverloadResolution:
5620 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005621 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00005622
5623 // The standard doesn't describe how to behave if the lookup is ambiguous.
5624 // We treat it as not making the member non-trivial, just like the standard
5625 // mandates for the default constructor. This should rarely matter, because
5626 // the member will also be deleted.
5627 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5628 return true;
5629
5630 if (!SMOR->getMethod()) {
5631 assert(SMOR->getKind() ==
5632 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5633 return false;
5634 }
5635
5636 // We deliberately don't check if we found a deleted special member. We're
5637 // not supposed to!
5638 if (Selected)
5639 *Selected = SMOR->getMethod();
5640 return SMOR->getMethod()->isTrivial();
5641 }
5642
5643 llvm_unreachable("unknown special method kind");
5644}
5645
Benjamin Kramer3e350262013-02-15 12:30:38 +00005646static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005647 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00005648 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005649 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005650
5651 // Look for constructor templates.
5652 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5653 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5654 if (CXXConstructorDecl *CD =
5655 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5656 return CD;
5657 }
5658
Craig Topperc3ec1492014-05-26 06:22:03 +00005659 return nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005660}
5661
5662/// The kind of subobject we are checking for triviality. The values of this
5663/// enumeration are used in diagnostics.
5664enum TrivialSubobjectKind {
5665 /// The subobject is a base class.
5666 TSK_BaseClass,
5667 /// The subobject is a non-static data member.
5668 TSK_Field,
5669 /// The object is actually the complete object.
5670 TSK_CompleteObject
5671};
5672
5673/// Check whether the special member selected for a given type would be trivial.
5674static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00005675 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00005676 Sema::CXXSpecialMember CSM,
5677 TrivialSubobjectKind Kind,
5678 bool Diagnose) {
5679 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5680 if (!SubRD)
5681 return true;
5682
5683 CXXMethodDecl *Selected;
5684 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005685 ConstRHS, Diagnose ? &Selected : nullptr))
Richard Smith92f241f2012-12-08 02:53:02 +00005686 return true;
5687
5688 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00005689 if (ConstRHS)
5690 SubType.addConst();
5691
Richard Smith92f241f2012-12-08 02:53:02 +00005692 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5693 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5694 << Kind << SubType.getUnqualifiedType();
5695 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5696 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5697 } else if (!Selected)
5698 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5699 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5700 else if (Selected->isUserProvided()) {
5701 if (Kind == TSK_CompleteObject)
5702 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5703 << Kind << SubType.getUnqualifiedType() << CSM;
5704 else {
5705 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5706 << Kind << SubType.getUnqualifiedType() << CSM;
5707 S.Diag(Selected->getLocation(), diag::note_declared_at);
5708 }
5709 } else {
5710 if (Kind != TSK_CompleteObject)
5711 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5712 << Kind << SubType.getUnqualifiedType() << CSM;
5713
5714 // Explain why the defaulted or deleted special member isn't trivial.
5715 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5716 }
5717 }
5718
5719 return false;
5720}
5721
5722/// Check whether the members of a class type allow a special member to be
5723/// trivial.
5724static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5725 Sema::CXXSpecialMember CSM,
5726 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005727 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005728 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5729 continue;
5730
5731 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5732
5733 // Pretend anonymous struct or union members are members of this class.
5734 if (FI->isAnonymousStructOrUnion()) {
5735 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5736 CSM, ConstArg, Diagnose))
5737 return false;
5738 continue;
5739 }
5740
5741 // C++11 [class.ctor]p5:
5742 // A default constructor is trivial if [...]
5743 // -- no non-static data member of its class has a
5744 // brace-or-equal-initializer
5745 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5746 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005747 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00005748 return false;
5749 }
5750
5751 // Objective C ARC 4.3.5:
5752 // [...] nontrivally ownership-qualified types are [...] not trivially
5753 // default constructible, copy constructible, move constructible, copy
5754 // assignable, move assignable, or destructible [...]
5755 if (S.getLangOpts().ObjCAutoRefCount &&
5756 FieldType.hasNonTrivialObjCLifetime()) {
5757 if (Diagnose)
5758 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5759 << RD << FieldType.getObjCLifetime();
5760 return false;
5761 }
5762
Richard Smith41c35d62013-11-27 03:39:20 +00005763 bool ConstRHS = ConstArg && !FI->isMutable();
5764 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
5765 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005766 return false;
5767 }
5768
5769 return true;
5770}
5771
5772/// Diagnose why the specified class does not have a trivial special member of
5773/// the given kind.
5774void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5775 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00005776
Richard Smith41c35d62013-11-27 03:39:20 +00005777 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
5778 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00005779 TSK_CompleteObject, /*Diagnose*/true);
5780}
5781
5782/// Determine whether a defaulted or deleted special member function is trivial,
5783/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5784/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5785bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5786 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00005787 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5788
5789 CXXRecordDecl *RD = MD->getParent();
5790
5791 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00005792
Richard Smith2002bfe2013-11-04 02:02:27 +00005793 // C++11 [class.copy]p12, p25: [DR1593]
5794 // A [special member] is trivial if [...] its parameter-type-list is
5795 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00005796 switch (CSM) {
5797 case CXXDefaultConstructor:
5798 case CXXDestructor:
5799 // Trivial default constructors and destructors cannot have parameters.
5800 break;
5801
5802 case CXXCopyConstructor:
5803 case CXXCopyAssignment: {
5804 // Trivial copy operations always have const, non-volatile parameter types.
5805 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00005806 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005807 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5808 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5809 if (Diagnose)
5810 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5811 << Param0->getSourceRange() << Param0->getType()
5812 << Context.getLValueReferenceType(
5813 Context.getRecordType(RD).withConst());
5814 return false;
5815 }
5816 break;
5817 }
5818
5819 case CXXMoveConstructor:
5820 case CXXMoveAssignment: {
5821 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00005822 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00005823 const RValueReferenceType *RT =
5824 Param0->getType()->getAs<RValueReferenceType>();
5825 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5826 if (Diagnose)
5827 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5828 << Param0->getSourceRange() << Param0->getType()
5829 << Context.getRValueReferenceType(Context.getRecordType(RD));
5830 return false;
5831 }
5832 break;
5833 }
5834
5835 case CXXInvalid:
5836 llvm_unreachable("not a special member");
5837 }
5838
Richard Smith92f241f2012-12-08 02:53:02 +00005839 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5840 if (Diagnose)
5841 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5842 diag::note_nontrivial_default_arg)
5843 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5844 return false;
5845 }
5846 if (MD->isVariadic()) {
5847 if (Diagnose)
5848 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5849 return false;
5850 }
5851
5852 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5853 // A copy/move [constructor or assignment operator] is trivial if
5854 // -- the [member] selected to copy/move each direct base class subobject
5855 // is trivial
5856 //
5857 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5858 // A [default constructor or destructor] is trivial if
5859 // -- all the direct base classes have trivial [default constructors or
5860 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00005861 for (const auto &BI : RD->bases())
5862 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00005863 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00005864 return false;
5865
5866 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5867 // A copy/move [constructor or assignment operator] for a class X is
5868 // trivial if
5869 // -- for each non-static data member of X that is of class type (or array
5870 // thereof), the constructor selected to copy/move that member is
5871 // trivial
5872 //
5873 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5874 // A [default constructor or destructor] is trivial if
5875 // -- for all of the non-static data members of its class that are of class
5876 // type (or array thereof), each such class has a trivial [default
5877 // constructor or destructor]
5878 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5879 return false;
5880
5881 // C++11 [class.dtor]p5:
5882 // A destructor is trivial if [...]
5883 // -- the destructor is not virtual
5884 if (CSM == CXXDestructor && MD->isVirtual()) {
5885 if (Diagnose)
5886 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5887 return false;
5888 }
5889
5890 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5891 // A [special member] for class X is trivial if [...]
5892 // -- class X has no virtual functions and no virtual base classes
5893 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5894 if (!Diagnose)
5895 return false;
5896
5897 if (RD->getNumVBases()) {
5898 // Check for virtual bases. We already know that the corresponding
5899 // member in all bases is trivial, so vbases must all be direct.
5900 CXXBaseSpecifier &BS = *RD->vbases_begin();
5901 assert(BS.isVirtual());
5902 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5903 return false;
5904 }
5905
5906 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005907 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005908 if (MI->isVirtual()) {
5909 SourceLocation MLoc = MI->getLocStart();
5910 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5911 return false;
5912 }
5913 }
5914
5915 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5916 }
5917
5918 // Looks like it's trivial!
5919 return true;
5920}
5921
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005922/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00005923namespace {
5924 struct FindHiddenVirtualMethodData {
5925 Sema *S;
5926 CXXMethodDecl *Method;
5927 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005928 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00005929 };
5930}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005931
David Blaikie282c92a2012-10-19 00:53:08 +00005932/// \brief Check whether any most overriden method from MD in Methods
5933static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00005934 const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00005935 if (MD->size_overridden_methods() == 0)
5936 return Methods.count(MD->getCanonicalDecl());
5937 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5938 E = MD->end_overridden_methods();
5939 I != E; ++I)
5940 if (CheckMostOverridenMethods(*I, Methods))
5941 return true;
5942 return false;
5943}
5944
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005945/// \brief Member lookup function that determines whether a given C++
5946/// method overloads virtual methods in a base class without overriding any,
5947/// to be used with CXXRecordDecl::lookupInBases().
5948static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5949 CXXBasePath &Path,
5950 void *UserData) {
5951 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5952
5953 FindHiddenVirtualMethodData &Data
5954 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5955
5956 DeclarationName Name = Data.Method->getDeclName();
5957 assert(Name.getNameKind() == DeclarationName::Identifier);
5958
5959 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005960 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005961 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00005962 !Path.Decls.empty();
5963 Path.Decls = Path.Decls.slice(1)) {
5964 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005965 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00005966 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005967 foundSameNameMethod = true;
5968 // Interested only in hidden virtual methods.
5969 if (!MD->isVirtual())
5970 continue;
5971 // If the method we are checking overrides a method from its base
Aaron Ballman04559a72014-07-30 23:50:53 +00005972 // don't warn about the other overloaded methods. Clang deviates from GCC
5973 // by only diagnosing overloads of inherited virtual functions that do not
5974 // override any other virtual functions in the base. GCC's
5975 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
5976 // function from a base class. These cases may be better served by a
5977 // warning (not specific to virtual functions) on call sites when the call
5978 // would select a different function from the base class, were it visible.
5979 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005980 if (!Data.S->IsOverload(Data.Method, MD, false))
5981 return true;
5982 // Collect the overload only if its hidden.
David Blaikie282c92a2012-10-19 00:53:08 +00005983 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005984 overloadedMethods.push_back(MD);
5985 }
5986 }
5987
5988 if (foundSameNameMethod)
5989 Data.OverloadedMethods.append(overloadedMethods.begin(),
5990 overloadedMethods.end());
5991 return foundSameNameMethod;
5992}
5993
David Blaikie282c92a2012-10-19 00:53:08 +00005994/// \brief Add the most overriden methods from MD to Methods
5995static void AddMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00005996 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00005997 if (MD->size_overridden_methods() == 0)
5998 Methods.insert(MD->getCanonicalDecl());
5999 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6000 E = MD->end_overridden_methods();
6001 I != E; ++I)
6002 AddMostOverridenMethods(*I, Methods);
6003}
6004
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006005/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006006/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006007void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6008 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00006009 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006010 return;
6011
6012 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6013 /*bool RecordPaths=*/false,
6014 /*bool DetectVirtual=*/false);
6015 FindHiddenVirtualMethodData Data;
6016 Data.Method = MD;
6017 Data.S = this;
6018
6019 // Keep the base methods that were overriden or introduced in the subclass
6020 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006021 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00006022 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6023 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6024 NamedDecl *ND = *I;
6025 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00006026 ND = shad->getTargetDecl();
6027 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6028 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006029 }
6030
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006031 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
6032 OverloadedMethods = Data.OverloadedMethods;
6033}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006034
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006035void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6036 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6037 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6038 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6039 PartialDiagnostic PD = PDiag(
6040 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6041 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6042 Diag(overloadedMD->getLocation(), PD);
6043 }
6044}
6045
6046/// \brief Diagnose methods which overload virtual methods in a base class
6047/// without overriding any.
6048void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6049 if (MD->isInvalidDecl())
6050 return;
6051
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006052 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006053 return;
6054
6055 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6056 FindHiddenVirtualMethods(MD, OverloadedMethods);
6057 if (!OverloadedMethods.empty()) {
6058 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6059 << MD << (OverloadedMethods.size() > 1);
6060
6061 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006062 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00006063}
6064
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006065void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00006066 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006067 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00006068 SourceLocation RBrac,
6069 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006070 if (!TagDecl)
6071 return;
Mike Stump11289f42009-09-09 15:08:12 +00006072
Douglas Gregorc9f9b862009-05-11 19:58:34 +00006073 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00006074
Rafael Espindola06e1b132012-07-12 04:32:30 +00006075 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6076 if (l->getKind() != AttributeList::AT_Visibility)
6077 continue;
6078 l->setInvalid();
6079 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6080 l->getName();
6081 }
6082
David Blaikie751c5582011-09-22 02:58:26 +00006083 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00006084 // strict aliasing violation!
6085 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00006086 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00006087
Douglas Gregor0be31a22010-07-02 17:43:08 +00006088 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00006089 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006090}
6091
Douglas Gregor05379422008-11-03 17:51:48 +00006092/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6093/// special functions, such as the default constructor, copy
6094/// constructor, or destructor, to the given C++ class (C++
6095/// [special]p1). This routine can only be executed just before the
6096/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00006097void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006098 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00006099 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006100
Richard Smith6b02d462012-12-08 08:32:28 +00006101 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00006102 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006103
Richard Smith6b02d462012-12-08 08:32:28 +00006104 // If the properties or semantics of the copy constructor couldn't be
6105 // determined while the class was being declared, force a declaration
6106 // of it now.
6107 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6108 DeclareImplicitCopyConstructor(ClassDecl);
6109 }
6110
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006111 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006112 ++ASTContext::NumImplicitMoveConstructors;
6113
Richard Smith6b02d462012-12-08 08:32:28 +00006114 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6115 DeclareImplicitMoveConstructor(ClassDecl);
6116 }
6117
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006118 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6119 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00006120
6121 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006122 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00006123 // it shows up in the right place in the vtable and that we diagnose
6124 // problems with the implicit exception specification.
6125 if (ClassDecl->isDynamicClass() ||
6126 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006127 DeclareImplicitCopyAssignment(ClassDecl);
6128 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006129
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006130 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006131 ++ASTContext::NumImplicitMoveAssignmentOperators;
6132
6133 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00006134 if (ClassDecl->isDynamicClass() ||
6135 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00006136 DeclareImplicitMoveAssignment(ClassDecl);
6137 }
6138
Douglas Gregor7454c562010-07-02 20:37:36 +00006139 if (!ClassDecl->hasUserDeclaredDestructor()) {
6140 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00006141
6142 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00006143 // have to declare the destructor immediately. This ensures that, e.g., it
6144 // shows up in the right place in the vtable and that we diagnose problems
6145 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00006146 if (ClassDecl->isDynamicClass() ||
6147 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00006148 DeclareImplicitDestructor(ClassDecl);
6149 }
Douglas Gregor05379422008-11-03 17:51:48 +00006150}
6151
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006152unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Francois Pichet1c229c02011-04-22 22:18:13 +00006153 if (!D)
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006154 return 0;
Francois Pichet1c229c02011-04-22 22:18:13 +00006155
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006156 // The order of template parameters is not important here. All names
6157 // get added to the same scope.
6158 SmallVector<TemplateParameterList *, 4> ParameterLists;
6159
6160 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6161 D = TD->getTemplatedDecl();
6162
6163 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6164 ParameterLists.push_back(PSD->getTemplateParameters());
6165
6166 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6167 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6168 ParameterLists.push_back(DD->getTemplateParameterList(i));
6169
6170 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6171 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6172 ParameterLists.push_back(FTD->getTemplateParameters());
6173 }
6174 }
6175
6176 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6177 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6178 ParameterLists.push_back(TD->getTemplateParameterList(i));
6179
6180 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6181 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6182 ParameterLists.push_back(CTD->getTemplateParameters());
6183 }
6184 }
6185
6186 unsigned Count = 0;
6187 for (TemplateParameterList *Params : ParameterLists) {
6188 if (Params->size() > 0)
6189 // Ignore explicit specializations; they don't contribute to the template
6190 // depth.
6191 ++Count;
6192 for (NamedDecl *Param : *Params) {
6193 if (Param->getDeclName()) {
6194 S->AddDecl(Param);
6195 IdResolver.AddDecl(Param);
Francois Pichet1c229c02011-04-22 22:18:13 +00006196 }
6197 }
6198 }
Francois Pichet1c229c02011-04-22 22:18:13 +00006199
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006200 return Count;
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006201}
6202
John McCall48871652010-08-21 09:40:31 +00006203void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006204 if (!RecordD) return;
6205 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00006206 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00006207 PushDeclContext(S, Record);
6208}
6209
John McCall48871652010-08-21 09:40:31 +00006210void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006211 if (!RecordD) return;
6212 PopDeclContext();
6213}
6214
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006215/// This is used to implement the constant expression evaluation part of the
6216/// attribute enable_if extension. There is nothing in standard C++ which would
6217/// require reentering parameters.
6218void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6219 if (!Param)
6220 return;
6221
6222 S->AddDecl(Param);
6223 if (Param->getDeclName())
6224 IdResolver.AddDecl(Param);
6225}
6226
Douglas Gregor4d87df52008-12-16 21:30:33 +00006227/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6228/// parsing a top-level (non-nested) C++ class, and we are now
6229/// parsing those parts of the given Method declaration that could
6230/// not be parsed earlier (C++ [class.mem]p2), such as default
6231/// arguments. This action should enter the scope of the given
6232/// Method declaration as if we had just parsed the qualified method
6233/// name. However, it should not bring the parameters into scope;
6234/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00006235void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006236}
6237
6238/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6239/// C++ method declaration. We're (re-)introducing the given
6240/// function parameter into scope for use in parsing later parts of
6241/// the method declaration. For example, we could see an
6242/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00006243void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006244 if (!ParamD)
6245 return;
Mike Stump11289f42009-09-09 15:08:12 +00006246
John McCall48871652010-08-21 09:40:31 +00006247 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00006248
6249 // If this parameter has an unparsed default argument, clear it out
6250 // to make way for the parsed default argument.
6251 if (Param->hasUnparsedDefaultArg())
Craig Topperc3ec1492014-05-26 06:22:03 +00006252 Param->setDefaultArg(nullptr);
Douglas Gregor58354032008-12-24 00:01:03 +00006253
John McCall48871652010-08-21 09:40:31 +00006254 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006255 if (Param->getDeclName())
6256 IdResolver.AddDecl(Param);
6257}
6258
6259/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6260/// processing the delayed method declaration for Method. The method
6261/// declaration is now considered finished. There may be a separate
6262/// ActOnStartOfFunctionDef action later (not necessarily
6263/// immediately!) for this method, if it was also defined inside the
6264/// class body.
John McCall48871652010-08-21 09:40:31 +00006265void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006266 if (!MethodD)
6267 return;
Mike Stump11289f42009-09-09 15:08:12 +00006268
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006269 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00006270
John McCall48871652010-08-21 09:40:31 +00006271 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006272
6273 // Now that we have our default arguments, check the constructor
6274 // again. It could produce additional diagnostics or affect whether
6275 // the class has implicitly-declared destructors, among other
6276 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006277 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6278 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006279
6280 // Check the default arguments, which we may have added.
6281 if (!Method->isInvalidDecl())
6282 CheckCXXDefaultArguments(Method);
6283}
6284
Douglas Gregor831c93f2008-11-05 20:51:48 +00006285/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00006286/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00006287/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006288/// emit diagnostics and set the invalid bit to true. In any case, the type
6289/// will be updated to reflect a well-formed type for the constructor and
6290/// returned.
6291QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006292 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006293 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006294
6295 // C++ [class.ctor]p3:
6296 // A constructor shall not be virtual (10.3) or static (9.4). A
6297 // constructor can be invoked for a const, volatile or const
6298 // volatile object. A constructor shall not be declared const,
6299 // volatile, or const volatile (9.3.2).
6300 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006301 if (!D.isInvalidType())
6302 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6303 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6304 << SourceRange(D.getIdentifierLoc());
6305 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006306 }
John McCall8e7d6562010-08-26 03:08:43 +00006307 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006308 if (!D.isInvalidType())
6309 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6310 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6311 << SourceRange(D.getIdentifierLoc());
6312 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006313 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006314 }
Mike Stump11289f42009-09-09 15:08:12 +00006315
David Majnemer03f705f2014-07-08 18:18:04 +00006316 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6317 diagnoseIgnoredQualifiers(
6318 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6319 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6320 D.getDeclSpec().getRestrictSpecLoc(),
6321 D.getDeclSpec().getAtomicSpecLoc());
6322 D.setInvalidType();
6323 }
6324
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006325 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006326 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00006327 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006328 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6329 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006330 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006331 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6332 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006333 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006334 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6335 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00006336 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006337 }
Mike Stump11289f42009-09-09 15:08:12 +00006338
Douglas Gregordb9d6642011-01-26 05:01:58 +00006339 // C++0x [class.ctor]p4:
6340 // A constructor shall not be declared with a ref-qualifier.
6341 if (FTI.hasRefQualifier()) {
6342 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6343 << FTI.RefQualifierIsLValueRef
6344 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6345 D.setInvalidType();
6346 }
6347
Douglas Gregor831c93f2008-11-05 20:51:48 +00006348 // Rebuild the function type "R" without any type qualifiers (in
6349 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00006350 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00006351 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006352 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00006353 return R;
6354
6355 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6356 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006357 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00006358
6359 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006360}
6361
Douglas Gregor4d87df52008-12-16 21:30:33 +00006362/// CheckConstructor - Checks a fully-formed constructor for
6363/// well-formedness, issuing any diagnostics required. Returns true if
6364/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006365void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00006366 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006367 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6368 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006369 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006370
6371 // C++ [class.copy]p3:
6372 // A declaration of a constructor for a class X is ill-formed if
6373 // its first parameter is of type (optionally cv-qualified) X and
6374 // either there are no other parameters or else all other
6375 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006376 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00006377 ((Constructor->getNumParams() == 1) ||
6378 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00006379 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6380 Constructor->getTemplateSpecializationKind()
6381 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006382 QualType ParamType = Constructor->getParamDecl(0)->getType();
6383 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6384 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00006385 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00006386 const char *ConstRef
6387 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6388 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00006389 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00006390 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00006391
6392 // FIXME: Rather that making the constructor invalid, we should endeavor
6393 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006394 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006395 }
6396 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00006397}
6398
John McCalldeb646e2010-08-04 01:04:25 +00006399/// CheckDestructor - Checks a fully-formed destructor definition for
6400/// well-formedness, issuing any diagnostics required. Returns true
6401/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00006402bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006403 CXXRecordDecl *RD = Destructor->getParent();
6404
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006405 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006406 SourceLocation Loc;
6407
6408 if (!Destructor->isImplicit())
6409 Loc = Destructor->getLocation();
6410 else
6411 Loc = RD->getLocation();
6412
6413 // If we have a virtual destructor, look up the deallocation function
Craig Topperc3ec1492014-05-26 06:22:03 +00006414 FunctionDecl *OperatorDelete = nullptr;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006415 DeclarationName Name =
6416 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006417 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00006418 return true;
Richard Smithf03bd302013-12-05 08:30:59 +00006419 // If there's no class-specific operator delete, look up the global
6420 // non-array delete.
6421 if (!OperatorDelete)
6422 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall1e5d75d2010-07-03 18:33:00 +00006423
Eli Friedmanfa0df832012-02-02 03:46:19 +00006424 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00006425
6426 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006427 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00006428
6429 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006430}
6431
Douglas Gregor831c93f2008-11-05 20:51:48 +00006432/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6433/// the well-formednes of the destructor declarator @p D with type @p
6434/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006435/// emit diagnostics and set the declarator to invalid. Even if this happens,
6436/// will be updated to reflect a well-formed type for the destructor and
6437/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00006438QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006439 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006440 // C++ [class.dtor]p1:
6441 // [...] A typedef-name that names a class is a class-name
6442 // (7.1.3); however, a typedef-name that names a class shall not
6443 // be used as the identifier in the declarator for a destructor
6444 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00006445 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00006446 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00006447 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00006448 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00006449 else if (const TemplateSpecializationType *TST =
6450 DeclaratorType->getAs<TemplateSpecializationType>())
6451 if (TST->isTypeAlias())
6452 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6453 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006454
6455 // C++ [class.dtor]p2:
6456 // A destructor is used to destroy objects of its class type. A
6457 // destructor takes no parameters, and no return type can be
6458 // specified for it (not even void). The address of a destructor
6459 // shall not be taken. A destructor shall not be static. A
6460 // destructor can be invoked for a const, volatile or const
6461 // volatile object. A destructor shall not be declared const,
6462 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00006463 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006464 if (!D.isInvalidType())
6465 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6466 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00006467 << SourceRange(D.getIdentifierLoc())
6468 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6469
John McCall8e7d6562010-08-26 03:08:43 +00006470 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006471 }
David Majnemer03f705f2014-07-08 18:18:04 +00006472 if (!D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006473 // Destructors don't have return types, but the parser will
6474 // happily parse something like:
6475 //
6476 // class X {
6477 // float ~X();
6478 // };
6479 //
6480 // The return type will be eliminated later.
David Majnemer03f705f2014-07-08 18:18:04 +00006481 if (D.getDeclSpec().hasTypeSpecifier())
6482 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6483 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6484 << SourceRange(D.getIdentifierLoc());
6485 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6486 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6487 SourceLocation(),
6488 D.getDeclSpec().getConstSpecLoc(),
6489 D.getDeclSpec().getVolatileSpecLoc(),
6490 D.getDeclSpec().getRestrictSpecLoc(),
6491 D.getDeclSpec().getAtomicSpecLoc());
6492 D.setInvalidType();
6493 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006494 }
Mike Stump11289f42009-09-09 15:08:12 +00006495
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006496 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006497 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006498 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006499 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6500 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006501 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006502 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6503 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006504 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006505 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6506 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00006507 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006508 }
6509
Douglas Gregordb9d6642011-01-26 05:01:58 +00006510 // C++0x [class.dtor]p2:
6511 // A destructor shall not be declared with a ref-qualifier.
6512 if (FTI.hasRefQualifier()) {
6513 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6514 << FTI.RefQualifierIsLValueRef
6515 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6516 D.setInvalidType();
6517 }
6518
Douglas Gregor831c93f2008-11-05 20:51:48 +00006519 // Make sure we don't have any parameters.
Alp Toker4284c6e2014-05-11 16:05:55 +00006520 if (FTIHasNonVoidParameters(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006521 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6522
6523 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006524 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00006525 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006526 }
6527
Mike Stump11289f42009-09-09 15:08:12 +00006528 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00006529 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006530 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00006531 D.setInvalidType();
6532 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006533
6534 // Rebuild the function type "R" without any type qualifiers or
6535 // parameters (in case any of the errors above fired) and with
6536 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00006537 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00006538 if (!D.isInvalidType())
6539 return R;
6540
Douglas Gregor95755162010-07-01 05:10:53 +00006541 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006542 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6543 EPI.Variadic = false;
6544 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006545 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006546 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006547}
6548
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006549/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6550/// well-formednes of the conversion function declarator @p D with
6551/// type @p R. If there are any errors in the declarator, this routine
6552/// will emit diagnostics and return true. Otherwise, it will return
6553/// false. Either way, the type @p R will be updated to reflect a
6554/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006555void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00006556 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006557 // C++ [class.conv.fct]p1:
6558 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00006559 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00006560 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00006561 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006562 if (!D.isInvalidType())
6563 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00006564 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6565 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006566 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006567 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006568 }
John McCall212fa2e2010-04-13 00:04:31 +00006569
6570 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6571
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006572 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006573 // Conversion functions don't have return types, but the parser will
6574 // happily parse something like:
6575 //
6576 // class X {
6577 // float operator bool();
6578 // };
6579 //
6580 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00006581 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6582 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6583 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00006584 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006585 }
6586
John McCall212fa2e2010-04-13 00:04:31 +00006587 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6588
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006589 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00006590 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006591 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6592
6593 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006594 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006595 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00006596 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006597 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006598 D.setInvalidType();
6599 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006600
John McCall212fa2e2010-04-13 00:04:31 +00006601 // Diagnose "&operator bool()" and other such nonsense. This
6602 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00006603 if (Proto->getReturnType() != ConvType) {
John McCall212fa2e2010-04-13 00:04:31 +00006604 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
Alp Toker314cc812014-01-25 16:55:45 +00006605 << Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006606 D.setInvalidType();
Alp Toker314cc812014-01-25 16:55:45 +00006607 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006608 }
6609
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006610 // C++ [class.conv.fct]p4:
6611 // The conversion-type-id shall not represent a function type nor
6612 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006613 if (ConvType->isArrayType()) {
6614 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6615 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006616 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006617 } else if (ConvType->isFunctionType()) {
6618 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6619 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006620 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006621 }
6622
6623 // Rebuild the function type "R" without any parameters (in case any
6624 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00006625 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00006626 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006627 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006628
Douglas Gregor5fb53972009-01-14 15:45:31 +00006629 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006630 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00006631 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006632 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006633 diag::warn_cxx98_compat_explicit_conversion_functions :
6634 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00006635 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006636}
6637
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006638/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6639/// the declaration of the given C++ conversion function. This routine
6640/// is responsible for recording the conversion function in the C++
6641/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00006642Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006643 assert(Conversion && "Expected to receive a conversion function declaration");
6644
Douglas Gregor4287b372008-12-12 08:25:50 +00006645 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006646
6647 // Make sure we aren't redeclaring the conversion function.
6648 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006649
6650 // C++ [class.conv.fct]p1:
6651 // [...] A conversion function is never used to convert a
6652 // (possibly cv-qualified) object to the (possibly cv-qualified)
6653 // same object type (or a reference to it), to a (possibly
6654 // cv-qualified) base class of that type (or a reference to it),
6655 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00006656 // FIXME: Suppress this warning if the conversion function ends up being a
6657 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00006658 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006659 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006660 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006661 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006662 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6663 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00006664 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006665 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006666 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6667 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006668 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006669 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006670 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006671 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006672 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006673 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006674 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006675 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006676 }
6677
Douglas Gregor457104e2010-09-29 04:25:11 +00006678 if (FunctionTemplateDecl *ConversionTemplate
6679 = Conversion->getDescribedFunctionTemplate())
6680 return ConversionTemplate;
6681
John McCall48871652010-08-21 09:40:31 +00006682 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006683}
6684
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006685//===----------------------------------------------------------------------===//
6686// Namespace Handling
6687//===----------------------------------------------------------------------===//
6688
Richard Smith45bb8852012-10-04 22:13:39 +00006689/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6690/// reopened.
6691static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6692 SourceLocation Loc,
6693 IdentifierInfo *II, bool *IsInline,
6694 NamespaceDecl *PrevNS) {
6695 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00006696
Richard Smithf501cc32012-10-05 01:46:25 +00006697 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6698 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6699 // inline namespaces, with the intention of bringing names into namespace std.
6700 //
6701 // We support this just well enough to get that case working; this is not
6702 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00006703 if (*IsInline && II && II->getName().startswith("__atomic") &&
6704 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00006705 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00006706 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6707 NS = NS->getPreviousDecl())
6708 NS->setInline(*IsInline);
6709 // Patch up the lookup table for the containing namespace. This isn't really
6710 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00006711 for (auto *I : PrevNS->decls())
6712 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00006713 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6714 return;
6715 }
6716
6717 if (PrevNS->isInline())
6718 // The user probably just forgot the 'inline', so suggest that it
6719 // be added back.
6720 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6721 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6722 else
Richard Smith5b5d21e2014-03-12 23:36:42 +00006723 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
Richard Smith45bb8852012-10-04 22:13:39 +00006724
6725 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6726 *IsInline = PrevNS->isInline();
6727}
John McCallb1be5232010-08-26 09:15:37 +00006728
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006729/// ActOnStartNamespaceDef - This is called at the start of a namespace
6730/// definition.
John McCall48871652010-08-21 09:40:31 +00006731Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00006732 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006733 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00006734 SourceLocation IdentLoc,
6735 IdentifierInfo *II,
6736 SourceLocation LBrace,
6737 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006738 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6739 // For anonymous namespace, take the location of the left brace.
6740 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00006741 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00006742 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00006743 bool IsStd = false;
6744 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006745 Scope *DeclRegionScope = NamespcScope->getParent();
6746
Craig Topperc3ec1492014-05-26 06:22:03 +00006747 NamespaceDecl *PrevNS = nullptr;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006748 if (II) {
6749 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00006750 // The identifier in an original-namespace-definition shall not
6751 // have been previously defined in the declarative region in
6752 // which the original-namespace-definition appears. The
6753 // identifier in an original-namespace-definition is the name of
6754 // the namespace. Subsequently in that declarative region, it is
6755 // treated as an original-namespace-name.
6756 //
6757 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006758 // look through using directives, just look for any ordinary names.
6759
6760 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00006761 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6762 Decl::IDNS_Namespace;
Craig Topperc3ec1492014-05-26 06:22:03 +00006763 NamedDecl *PrevDecl = nullptr;
David Blaikieff7d47a2012-12-19 00:45:41 +00006764 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6765 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6766 ++I) {
6767 if ((*I)->getIdentifierNamespace() & IDNS) {
6768 PrevDecl = *I;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00006769 break;
6770 }
6771 }
6772
Douglas Gregore57e7522012-01-07 09:11:48 +00006773 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6774
6775 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00006776 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00006777 if (IsInline != PrevNS->isInline())
6778 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6779 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00006780 } else if (PrevDecl) {
6781 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006782 Diag(Loc, diag::err_redefinition_different_kind)
6783 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00006784 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006785 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00006786 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00006787 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00006788 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00006789 // This is the first "real" definition of the namespace "std", so update
6790 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00006791 PrevNS = getStdNamespace();
6792 IsStd = true;
6793 AddToKnown = !IsInline;
6794 } else {
6795 // We've seen this namespace for the first time.
6796 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00006797 }
Douglas Gregor91f84212008-12-11 16:49:14 +00006798 } else {
John McCall4fa53422009-10-01 00:25:31 +00006799 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00006800
6801 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00006802 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00006803 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00006804 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006805 } else {
6806 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00006807 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00006808 }
6809
Richard Smith45bb8852012-10-04 22:13:39 +00006810 if (PrevNS && IsInline != PrevNS->isInline())
6811 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6812 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00006813 }
6814
6815 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6816 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00006817 if (IsInvalid)
6818 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00006819
6820 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00006821
Douglas Gregore57e7522012-01-07 09:11:48 +00006822 // FIXME: Should we be merging attributes?
6823 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006824 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00006825
6826 if (IsStd)
6827 StdNamespace = Namespc;
6828 if (AddToKnown)
6829 KnownNamespaces[Namespc] = false;
6830
6831 if (II) {
6832 PushOnScopeChains(Namespc, DeclRegionScope);
6833 } else {
6834 // Link the anonymous namespace into its parent.
6835 DeclContext *Parent = CurContext->getRedeclContext();
6836 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6837 TU->setAnonymousNamespace(Namespc);
6838 } else {
6839 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00006840 }
John McCall4fa53422009-10-01 00:25:31 +00006841
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00006842 CurContext->addDecl(Namespc);
6843
John McCall4fa53422009-10-01 00:25:31 +00006844 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6845 // behaves as if it were replaced by
6846 // namespace unique { /* empty body */ }
6847 // using namespace unique;
6848 // namespace unique { namespace-body }
6849 // where all occurrences of 'unique' in a translation unit are
6850 // replaced by the same identifier and this identifier differs
6851 // from all other identifiers in the entire program.
6852
6853 // We just create the namespace with an empty name and then add an
6854 // implicit using declaration, just like the standard suggests.
6855 //
6856 // CodeGen enforces the "universally unique" aspect by giving all
6857 // declarations semantically contained within an anonymous
6858 // namespace internal linkage.
6859
Douglas Gregore57e7522012-01-07 09:11:48 +00006860 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00006861 UsingDirectiveDecl* UD
Nick Lewycky38115822012-11-04 20:21:54 +00006862 = UsingDirectiveDecl::Create(Context, Parent,
John McCall0db42252009-12-16 02:06:49 +00006863 /* 'using' */ LBrace,
6864 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00006865 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00006866 /* identifier */ SourceLocation(),
6867 Namespc,
Nick Lewycky38115822012-11-04 20:21:54 +00006868 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00006869 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00006870 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00006871 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006872 }
6873
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00006874 ActOnDocumentableDecl(Namespc);
6875
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006876 // Although we could have an invalid decl (i.e. the namespace name is a
6877 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00006878 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6879 // for the namespace has the declarations that showed up in that particular
6880 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00006881 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00006882 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006883}
6884
Sebastian Redla6602e92009-11-23 15:34:23 +00006885/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6886/// is a namespace alias, returns the namespace it points to.
6887static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6888 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6889 return AD->getNamespace();
6890 return dyn_cast_or_null<NamespaceDecl>(D);
6891}
6892
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006893/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6894/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00006895void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006896 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6897 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006898 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006899 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00006900 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00006901 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006902}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006903
John McCall28a0cf72010-08-25 07:42:41 +00006904CXXRecordDecl *Sema::getStdBadAlloc() const {
6905 return cast_or_null<CXXRecordDecl>(
6906 StdBadAlloc.get(Context.getExternalSource()));
6907}
6908
6909NamespaceDecl *Sema::getStdNamespace() const {
6910 return cast_or_null<NamespaceDecl>(
6911 StdNamespace.get(Context.getExternalSource()));
6912}
6913
Douglas Gregorcdf87022010-06-29 17:53:46 +00006914/// \brief Retrieve the special "std" namespace, which may require us to
6915/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006916NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00006917 if (!StdNamespace) {
6918 // The "std" namespace has not yet been defined, so build one implicitly.
6919 StdNamespace = NamespaceDecl::Create(Context,
6920 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006921 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006922 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00006923 &PP.getIdentifierTable().get("std"),
Craig Topperc3ec1492014-05-26 06:22:03 +00006924 /*PrevDecl=*/nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006925 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006926 }
6927
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00006928 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006929}
6930
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006931bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006932 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006933 "Looking for std::initializer_list outside of C++.");
6934
6935 // We're looking for implicit instantiations of
6936 // template <typename E> class std::initializer_list.
6937
6938 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6939 return false;
6940
Craig Topperc3ec1492014-05-26 06:22:03 +00006941 ClassTemplateDecl *Template = nullptr;
6942 const TemplateArgument *Arguments = nullptr;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006943
Sebastian Redl43144e72012-01-17 22:49:58 +00006944 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006945
Sebastian Redl43144e72012-01-17 22:49:58 +00006946 ClassTemplateSpecializationDecl *Specialization =
6947 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6948 if (!Specialization)
6949 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006950
Sebastian Redl43144e72012-01-17 22:49:58 +00006951 Template = Specialization->getSpecializedTemplate();
6952 Arguments = Specialization->getTemplateArgs().data();
6953 } else if (const TemplateSpecializationType *TST =
6954 Ty->getAs<TemplateSpecializationType>()) {
6955 Template = dyn_cast_or_null<ClassTemplateDecl>(
6956 TST->getTemplateName().getAsTemplateDecl());
6957 Arguments = TST->getArgs();
6958 }
6959 if (!Template)
6960 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006961
6962 if (!StdInitializerList) {
6963 // Haven't recognized std::initializer_list yet, maybe this is it.
6964 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6965 if (TemplateClass->getIdentifier() !=
6966 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00006967 !getStdNamespace()->InEnclosingNamespaceSetOf(
6968 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006969 return false;
6970 // This is a template called std::initializer_list, but is it the right
6971 // template?
6972 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00006973 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006974 return false;
6975 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6976 return false;
6977
6978 // It's the right template.
6979 StdInitializerList = Template;
6980 }
6981
6982 if (Template != StdInitializerList)
6983 return false;
6984
6985 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00006986 if (Element)
6987 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00006988 return true;
6989}
6990
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006991static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6992 NamespaceDecl *Std = S.getStdNamespace();
6993 if (!Std) {
6994 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00006995 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00006996 }
6997
6998 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6999 Loc, Sema::LookupOrdinaryName);
7000 if (!S.LookupQualifiedName(Result, Std)) {
7001 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00007002 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007003 }
7004 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7005 if (!Template) {
7006 Result.suppressDiagnostics();
7007 // We found something weird. Complain about the first thing we found.
7008 NamedDecl *Found = *Result.begin();
7009 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00007010 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007011 }
7012
7013 // We found some template called std::initializer_list. Now verify that it's
7014 // correct.
7015 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00007016 if (Params->getMinRequiredArguments() != 1 ||
7017 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007018 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00007019 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007020 }
7021
7022 return Template;
7023}
7024
7025QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7026 if (!StdInitializerList) {
7027 StdInitializerList = LookupStdInitializerList(*this, Loc);
7028 if (!StdInitializerList)
7029 return QualType();
7030 }
7031
7032 TemplateArgumentListInfo Args(Loc, Loc);
7033 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7034 Context.getTrivialTypeSourceInfo(Element,
7035 Loc)));
7036 return Context.getCanonicalType(
7037 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7038}
7039
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007040bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7041 // C++ [dcl.init.list]p2:
7042 // A constructor is an initializer-list constructor if its first parameter
7043 // is of type std::initializer_list<E> or reference to possibly cv-qualified
7044 // std::initializer_list<E> for some type E, and either there are no other
7045 // parameters or else all other parameters have default arguments.
7046 if (Ctor->getNumParams() < 1 ||
7047 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7048 return false;
7049
7050 QualType ArgType = Ctor->getParamDecl(0)->getType();
7051 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7052 ArgType = RT->getPointeeType().getUnqualifiedType();
7053
Craig Topperc3ec1492014-05-26 06:22:03 +00007054 return isStdInitializerList(ArgType, nullptr);
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007055}
7056
Douglas Gregora172e082011-03-26 22:25:30 +00007057/// \brief Determine whether a using statement is in a context where it will be
7058/// apply in all contexts.
7059static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7060 switch (CurContext->getDeclKind()) {
7061 case Decl::TranslationUnit:
7062 return true;
7063 case Decl::LinkageSpec:
7064 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7065 default:
7066 return false;
7067 }
7068}
7069
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007070namespace {
7071
7072// Callback to only accept typo corrections that are namespaces.
7073class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007074public:
Craig Toppera798a9d2014-03-02 09:32:10 +00007075 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007076 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007077 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007078 return false;
7079 }
7080};
7081
7082}
7083
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007084static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7085 CXXScopeSpec &SS,
7086 SourceLocation IdentLoc,
7087 IdentifierInfo *Ident) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007088 NamespaceValidatorCCC Validator;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007089 R.clear();
7090 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007091 R.getLookupKind(), Sc, &SS,
John Thompson2255f2c2014-04-23 12:57:01 +00007092 Validator,
7093 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007094 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00007095 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7096 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007097 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00007098 S.diagnoseTypo(Corrected,
7099 S.PDiag(diag::err_using_directive_member_suggest)
7100 << Ident << DC << DroppedSpecifier << SS.getRange(),
7101 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007102 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007103 S.diagnoseTypo(Corrected,
7104 S.PDiag(diag::err_using_directive_suggest) << Ident,
7105 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007106 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007107 R.addDecl(Corrected.getCorrectionDecl());
7108 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007109 }
7110 return false;
7111}
7112
John McCall48871652010-08-21 09:40:31 +00007113Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00007114 SourceLocation UsingLoc,
7115 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007116 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00007117 SourceLocation IdentLoc,
7118 IdentifierInfo *NamespcName,
7119 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00007120 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7121 assert(NamespcName && "Invalid NamespcName.");
7122 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00007123
7124 // This can only happen along a recovery path.
7125 while (S->getFlags() & Scope::TemplateParamScope)
7126 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00007127 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00007128
Craig Topperc3ec1492014-05-26 06:22:03 +00007129 UsingDirectiveDecl *UDir = nullptr;
7130 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregorcdf87022010-06-29 17:53:46 +00007131 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00007132 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007133
Douglas Gregor34074322009-01-14 22:20:51 +00007134 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00007135 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7136 LookupParsedName(R, S, &SS);
7137 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00007138 return nullptr;
John McCall27b18f82009-11-17 02:14:36 +00007139
Douglas Gregorcdf87022010-06-29 17:53:46 +00007140 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007141 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007142 // Allow "using namespace std;" or "using namespace ::std;" even if
7143 // "std" hasn't been defined yet, for GCC compatibility.
7144 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7145 NamespcName->isStr("std")) {
7146 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007147 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00007148 R.resolveKind();
7149 }
7150 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007151 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007152 }
7153
John McCall9f3059a2009-10-09 21:13:30 +00007154 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00007155 NamedDecl *Named = R.getFoundDecl();
7156 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7157 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00007158 // C++ [namespace.udir]p1:
7159 // A using-directive specifies that the names in the nominated
7160 // namespace can be used in the scope in which the
7161 // using-directive appears after the using-directive. During
7162 // unqualified name lookup (3.4.1), the names appear as if they
7163 // were declared in the nearest enclosing namespace which
7164 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00007165 // namespace. [Note: in this context, "contains" means "contains
7166 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00007167
7168 // Find enclosing context containing both using-directive and
7169 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00007170 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007171 DeclContext *CommonAncestor = cast<DeclContext>(NS);
7172 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7173 CommonAncestor = CommonAncestor->getParent();
7174
Sebastian Redla6602e92009-11-23 15:34:23 +00007175 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00007176 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00007177 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007178
Douglas Gregora172e082011-03-26 22:25:30 +00007179 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00007180 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007181 Diag(IdentLoc, diag::warn_using_directive_in_header);
7182 }
7183
Douglas Gregor889ceb72009-02-03 19:21:40 +00007184 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007185 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00007186 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00007187 }
7188
Richard Smith54ecd982013-02-20 19:22:51 +00007189 if (UDir)
7190 ProcessDeclAttributeList(S, UDir, AttrList);
7191
John McCall48871652010-08-21 09:40:31 +00007192 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00007193}
7194
7195void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00007196 // If the scope has an associated entity and the using directive is at
7197 // namespace or translation unit scope, add the UsingDirectiveDecl into
7198 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007199 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00007200 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007201 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007202 else
Yaron Keren065da7c2014-05-20 18:23:05 +00007203 // Otherwise, it is at block scope. The using-directives will affect lookup
Richard Smith05afe5e2012-03-13 03:12:56 +00007204 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00007205 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007206}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007207
Douglas Gregorfec52632009-06-20 00:51:54 +00007208
John McCall48871652010-08-21 09:40:31 +00007209Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00007210 AccessSpecifier AS,
7211 bool HasUsingKeyword,
7212 SourceLocation UsingLoc,
7213 CXXScopeSpec &SS,
7214 UnqualifiedId &Name,
7215 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007216 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00007217 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00007218 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00007219
Douglas Gregor220f4272009-11-04 16:30:06 +00007220 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00007221 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00007222 case UnqualifiedId::IK_Identifier:
7223 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00007224 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00007225 case UnqualifiedId::IK_ConversionFunctionId:
7226 break;
7227
7228 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00007229 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00007230 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007231 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007232 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00007233 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00007234 diag::err_using_decl_constructor)
7235 << SS.getRange();
7236
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007237 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00007238
Craig Topperc3ec1492014-05-26 06:22:03 +00007239 return nullptr;
7240
Douglas Gregor220f4272009-11-04 16:30:06 +00007241 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007242 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00007243 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00007244 return nullptr;
7245
Douglas Gregor220f4272009-11-04 16:30:06 +00007246 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007247 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00007248 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007249 return nullptr;
Douglas Gregor220f4272009-11-04 16:30:06 +00007250 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007251
7252 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7253 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00007254 if (!TargetName)
Craig Topperc3ec1492014-05-26 06:22:03 +00007255 return nullptr;
John McCall3969e302009-12-08 07:46:18 +00007256
Richard Smithc2bc61b2013-03-18 21:12:30 +00007257 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00007258 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00007259 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00007260 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7261 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00007262 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00007263 }
7264
Douglas Gregorc4356532010-12-16 00:46:58 +00007265 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7266 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +00007267 return nullptr;
Douglas Gregorc4356532010-12-16 00:46:58 +00007268
John McCall3f746822009-11-17 05:59:44 +00007269 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007270 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007271 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007272 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00007273 if (UD)
7274 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00007275
John McCall48871652010-08-21 09:40:31 +00007276 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00007277}
7278
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007279/// \brief Determine whether a using declaration considers the given
7280/// declarations as "equivalent", e.g., if they are redeclarations of
7281/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00007282static bool
7283IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7284 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007285 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007286
Richard Smithdda56e42011-04-15 14:24:37 +00007287 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00007288 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007289 return Context.hasSameType(TD1->getUnderlyingType(),
7290 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007291
7292 return false;
7293}
7294
7295
John McCall84d87672009-12-10 09:41:52 +00007296/// Determines whether to create a using shadow decl for a particular
7297/// decl, given the set of decls existing prior to this using lookup.
7298bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00007299 const LookupResult &Previous,
7300 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00007301 // Diagnose finding a decl which is not from a base class of the
7302 // current class. We do this now because there are cases where this
7303 // function will silently decide not to build a shadow decl, which
7304 // will pre-empt further diagnostics.
7305 //
7306 // We don't need to do this in C++0x because we do the check once on
7307 // the qualifier.
7308 //
7309 // FIXME: diagnose the following if we care enough:
7310 // struct A { int foo; };
7311 // struct B : A { using A::foo; };
7312 // template <class T> struct C : A {};
7313 // template <class T> struct D : C<T> { using B::foo; } // <---
7314 // This is invalid (during instantiation) in C++03 because B::foo
7315 // resolves to the using decl in B, which is not a base class of D<T>.
7316 // We can't diagnose it immediately because C<T> is an unknown
7317 // specialization. The UsingShadowDecl in D<T> then points directly
7318 // to A::foo, which will look well-formed when we instantiate.
7319 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007320 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00007321 DeclContext *OrigDC = Orig->getDeclContext();
7322
7323 // Handle enums and anonymous structs.
7324 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7325 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7326 while (OrigRec->isAnonymousStructOrUnion())
7327 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7328
7329 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7330 if (OrigDC == CurContext) {
7331 Diag(Using->getLocation(),
7332 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007333 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007334 Diag(Orig->getLocation(), diag::note_using_decl_target);
7335 return true;
7336 }
7337
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007338 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00007339 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007340 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00007341 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007342 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007343 Diag(Orig->getLocation(), diag::note_using_decl_target);
7344 return true;
7345 }
7346 }
7347
7348 if (Previous.empty()) return false;
7349
7350 NamedDecl *Target = Orig;
7351 if (isa<UsingShadowDecl>(Target))
7352 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7353
John McCalla17e83e2009-12-11 02:33:26 +00007354 // If the target happens to be one of the previous declarations, we
7355 // don't have a conflict.
7356 //
7357 // FIXME: but we might be increasing its access, in which case we
7358 // should redeclare it.
Craig Topperc3ec1492014-05-26 06:22:03 +00007359 NamedDecl *NonTag = nullptr, *Tag = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00007360 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00007361 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7362 I != E; ++I) {
7363 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007364 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7365 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7366 PrevShadow = Shadow;
7367 FoundEquivalentDecl = true;
7368 }
John McCalla17e83e2009-12-11 02:33:26 +00007369
7370 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7371 }
7372
Richard Smithfd8634a2013-10-23 02:17:46 +00007373 if (FoundEquivalentDecl)
7374 return false;
7375
Alp Tokera2794f92014-01-22 07:29:52 +00007376 if (FunctionDecl *FD = Target->getAsFunction()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007377 NamedDecl *OldDecl = nullptr;
7378 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7379 /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00007380 case Ovl_Overload:
7381 return false;
7382
7383 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00007384 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007385 break;
Richard Smith18819302014-02-06 01:31:33 +00007386
John McCall84d87672009-12-10 09:41:52 +00007387 // We found a decl with the exact signature.
7388 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007389 // If we're in a record, we want to hide the target, so we
7390 // return true (without a diagnostic) to tell the caller not to
7391 // build a shadow decl.
7392 if (CurContext->isRecord())
7393 return true;
7394
7395 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00007396 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007397 break;
7398 }
7399
7400 Diag(Target->getLocation(), diag::note_using_decl_target);
7401 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7402 return true;
7403 }
7404
7405 // Target is not a function.
7406
John McCall84d87672009-12-10 09:41:52 +00007407 if (isa<TagDecl>(Target)) {
7408 // No conflict between a tag and a non-tag.
7409 if (!Tag) return false;
7410
John McCalle29c5cd2009-12-10 19:51:03 +00007411 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007412 Diag(Target->getLocation(), diag::note_using_decl_target);
7413 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7414 return true;
7415 }
7416
7417 // No conflict between a tag and a non-tag.
7418 if (!NonTag) return false;
7419
John McCalle29c5cd2009-12-10 19:51:03 +00007420 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007421 Diag(Target->getLocation(), diag::note_using_decl_target);
7422 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7423 return true;
7424}
7425
John McCall3f746822009-11-17 05:59:44 +00007426/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00007427UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00007428 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00007429 NamedDecl *Orig,
7430 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00007431
7432 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00007433 NamedDecl *Target = Orig;
7434 if (isa<UsingShadowDecl>(Target)) {
7435 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7436 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00007437 }
Richard Smithfd8634a2013-10-23 02:17:46 +00007438
John McCall3f746822009-11-17 05:59:44 +00007439 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00007440 = UsingShadowDecl::Create(Context, CurContext,
7441 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00007442 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00007443
Douglas Gregor457104e2010-09-29 04:25:11 +00007444 Shadow->setAccess(UD->getAccess());
7445 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7446 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007447
7448 Shadow->setPreviousDecl(PrevDecl);
7449
John McCall3f746822009-11-17 05:59:44 +00007450 if (S)
John McCall3969e302009-12-08 07:46:18 +00007451 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00007452 else
John McCall3969e302009-12-08 07:46:18 +00007453 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00007454
John McCall3969e302009-12-08 07:46:18 +00007455
John McCall84d87672009-12-10 09:41:52 +00007456 return Shadow;
7457}
John McCall3969e302009-12-08 07:46:18 +00007458
John McCall84d87672009-12-10 09:41:52 +00007459/// Hides a using shadow declaration. This is required by the current
7460/// using-decl implementation when a resolvable using declaration in a
7461/// class is followed by a declaration which would hide or override
7462/// one or more of the using decl's targets; for example:
7463///
7464/// struct Base { void foo(int); };
7465/// struct Derived : Base {
7466/// using Base::foo;
7467/// void foo(int);
7468/// };
7469///
7470/// The governing language is C++03 [namespace.udecl]p12:
7471///
7472/// When a using-declaration brings names from a base class into a
7473/// derived class scope, member functions in the derived class
7474/// override and/or hide member functions with the same name and
7475/// parameter types in a base class (rather than conflicting).
7476///
7477/// There are two ways to implement this:
7478/// (1) optimistically create shadow decls when they're not hidden
7479/// by existing declarations, or
7480/// (2) don't create any shadow decls (or at least don't make them
7481/// visible) until we've fully parsed/instantiated the class.
7482/// The problem with (1) is that we might have to retroactively remove
7483/// a shadow decl, which requires several O(n) operations because the
7484/// decl structures are (very reasonably) not designed for removal.
7485/// (2) avoids this but is very fiddly and phase-dependent.
7486void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00007487 if (Shadow->getDeclName().getNameKind() ==
7488 DeclarationName::CXXConversionFunctionName)
7489 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7490
John McCall84d87672009-12-10 09:41:52 +00007491 // Remove it from the DeclContext...
7492 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007493
John McCall84d87672009-12-10 09:41:52 +00007494 // ...and the scope, if applicable...
7495 if (S) {
John McCall48871652010-08-21 09:40:31 +00007496 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00007497 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007498 }
7499
John McCall84d87672009-12-10 09:41:52 +00007500 // ...and the using decl.
7501 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7502
7503 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00007504 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00007505}
7506
Richard Smith09d5b3a2014-05-01 00:35:04 +00007507/// Find the base specifier for a base class with the given type.
7508static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7509 QualType DesiredBase,
7510 bool &AnyDependentBases) {
7511 // Check whether the named type is a direct base class.
7512 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7513 for (auto &Base : Derived->bases()) {
7514 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7515 if (CanonicalDesiredBase == BaseType)
7516 return &Base;
7517 if (BaseType->isDependentType())
7518 AnyDependentBases = true;
7519 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007520 return nullptr;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007521}
7522
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007523namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007524class UsingValidatorCCC : public CorrectionCandidateCallback {
7525public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007526 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007527 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007528 : HasTypenameKeyword(HasTypenameKeyword),
Richard Smith09d5b3a2014-05-01 00:35:04 +00007529 IsInstantiation(IsInstantiation), OldNNS(NNS),
7530 RequireMemberOf(RequireMemberOf) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007531
Craig Toppera798a9d2014-03-02 09:32:10 +00007532 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007533 NamedDecl *ND = Candidate.getCorrectionDecl();
7534
7535 // Keywords are not valid here.
7536 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007537 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007538
7539 // Completely unqualified names are invalid for a 'using' declaration.
7540 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7541 return false;
7542
Richard Smith09d5b3a2014-05-01 00:35:04 +00007543 if (RequireMemberOf) {
7544 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7545 if (FoundRecord && FoundRecord->isInjectedClassName()) {
7546 // No-one ever wants a using-declaration to name an injected-class-name
7547 // of a base class, unless they're declaring an inheriting constructor.
7548 ASTContext &Ctx = ND->getASTContext();
7549 if (!Ctx.getLangOpts().CPlusPlus11)
7550 return false;
7551 QualType FoundType = Ctx.getRecordType(FoundRecord);
7552
7553 // Check that the injected-class-name is named as a member of its own
7554 // type; we don't want to suggest 'using Derived::Base;', since that
7555 // means something else.
7556 NestedNameSpecifier *Specifier =
7557 Candidate.WillReplaceSpecifier()
7558 ? Candidate.getCorrectionSpecifier()
7559 : OldNNS;
7560 if (!Specifier->getAsType() ||
7561 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
7562 return false;
7563
7564 // Check that this inheriting constructor declaration actually names a
7565 // direct base class of the current class.
7566 bool AnyDependentBases = false;
7567 if (!findDirectBaseWithType(RequireMemberOf,
7568 Ctx.getRecordType(FoundRecord),
7569 AnyDependentBases) &&
7570 !AnyDependentBases)
7571 return false;
7572 } else {
7573 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
7574 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
7575 return false;
7576
7577 // FIXME: Check that the base class member is accessible?
7578 }
7579 }
7580
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007581 if (isa<TypeDecl>(ND))
7582 return HasTypenameKeyword || !IsInstantiation;
7583
7584 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007585 }
7586
7587private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007588 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007589 bool IsInstantiation;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007590 NestedNameSpecifier *OldNNS;
Richard Smith21866c32014-04-30 18:03:21 +00007591 CXXRecordDecl *RequireMemberOf;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007592};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007593} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007594
John McCalle61f2ba2009-11-18 02:36:19 +00007595/// Builds a using declaration.
7596///
7597/// \param IsInstantiation - Whether this call arises from an
7598/// instantiation of an unresolved using declaration. We treat
7599/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00007600NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7601 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007602 CXXScopeSpec &SS,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007603 DeclarationNameInfo NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00007604 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007605 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007606 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00007607 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00007608 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007609 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00007610 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00007611
Anders Carlssonf038fc22009-08-28 05:49:21 +00007612 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00007613
Anders Carlsson59140b32009-08-28 03:16:11 +00007614 if (SS.isEmpty()) {
7615 Diag(IdentLoc, diag::err_using_requires_qualname);
Craig Topperc3ec1492014-05-26 06:22:03 +00007616 return nullptr;
Anders Carlsson59140b32009-08-28 03:16:11 +00007617 }
Mike Stump11289f42009-09-09 15:08:12 +00007618
John McCall84d87672009-12-10 09:41:52 +00007619 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007620 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00007621 ForRedeclaration);
7622 Previous.setHideTags(false);
7623 if (S) {
7624 LookupName(Previous, S);
7625
7626 // It is really dumb that we have to do this.
7627 LookupResult::Filter F = Previous.makeFilter();
7628 while (F.hasNext()) {
7629 NamedDecl *D = F.next();
7630 if (!isDeclInScope(D, CurContext, S))
7631 F.erase();
Richard Smith83e78f52014-04-11 01:03:38 +00007632 // If we found a local extern declaration that's not ordinarily visible,
7633 // and this declaration is being added to a non-block scope, ignore it.
7634 // We're only checking for scope conflicts here, not also for violations
7635 // of the linkage rules.
7636 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
7637 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
7638 F.erase();
John McCall84d87672009-12-10 09:41:52 +00007639 }
7640 F.done();
7641 } else {
7642 assert(IsInstantiation && "no scope in non-instantiation");
7643 assert(CurContext->isRecord() && "scope not record in instantiation");
7644 LookupQualifiedName(Previous, CurContext);
7645 }
7646
John McCall84d87672009-12-10 09:41:52 +00007647 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007648 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7649 SS, IdentLoc, Previous))
Craig Topperc3ec1492014-05-26 06:22:03 +00007650 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00007651
7652 // Check for bad qualifiers.
Richard Smith7ad0b882014-04-02 21:44:35 +00007653 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00007654 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00007655
John McCall84c16cf2009-11-12 03:15:40 +00007656 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007657 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007658 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00007659 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007660 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00007661 // FIXME: not all declaration name kinds are legal here
7662 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7663 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007664 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007665 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00007666 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007667 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7668 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00007669 }
Richard Smith09d5b3a2014-05-01 00:35:04 +00007670 D->setAccess(AS);
7671 CurContext->addDecl(D);
7672 return D;
Anders Carlssonf038fc22009-08-28 05:49:21 +00007673 }
John McCallb96ec562009-12-04 22:46:56 +00007674
Richard Smith09d5b3a2014-05-01 00:35:04 +00007675 auto Build = [&](bool Invalid) {
7676 UsingDecl *UD =
7677 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
7678 HasTypenameKeyword);
7679 UD->setAccess(AS);
7680 CurContext->addDecl(UD);
7681 UD->setInvalidDecl(Invalid);
John McCall3969e302009-12-08 07:46:18 +00007682 return UD;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007683 };
7684 auto BuildInvalid = [&]{ return Build(true); };
7685 auto BuildValid = [&]{ return Build(false); };
7686
7687 if (RequireCompleteDeclContext(SS, LookupContext))
7688 return BuildInvalid();
Anders Carlsson59140b32009-08-28 03:16:11 +00007689
Richard Smith23d55872012-04-02 01:30:27 +00007690 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redl08905022011-02-05 19:23:19 +00007691 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smith09d5b3a2014-05-01 00:35:04 +00007692 UsingDecl *UD = BuildValid();
7693 CheckInheritingConstructorUsingDecl(UD);
Sebastian Redl08905022011-02-05 19:23:19 +00007694 return UD;
7695 }
7696
7697 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00007698
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007699 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00007700
John McCall3969e302009-12-08 07:46:18 +00007701 // Unlike most lookups, we don't always want to hide tag
7702 // declarations: tag names are visible through the using declaration
7703 // even if hidden by ordinary names, *except* in a dependent context
7704 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00007705 if (!IsInstantiation)
7706 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00007707
John McCall5dadb652012-04-07 03:04:20 +00007708 // For the purposes of this lookup, we have a base object type
7709 // equal to that of the current context.
7710 if (CurContext->isRecord()) {
7711 R.setBaseObjectType(
7712 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7713 }
7714
John McCall27b18f82009-11-17 02:14:36 +00007715 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00007716
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007717 // Try to correct typos if possible.
John McCall9f3059a2009-10-09 21:13:30 +00007718 if (R.empty()) {
Richard Smith09d5b3a2014-05-01 00:35:04 +00007719 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
Richard Smith21866c32014-04-30 18:03:21 +00007720 dyn_cast<CXXRecordDecl>(CurContext));
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007721 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
John Thompson2255f2c2014-04-23 12:57:01 +00007722 R.getLookupKind(), S, &SS, CCC,
7723 CTK_ErrorRecovery)){
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007724 // We reject any correction for which ND would be NULL.
7725 NamedDecl *ND = Corrected.getCorrectionDecl();
Richard Smith09d5b3a2014-05-01 00:35:04 +00007726
Richard Smithf9b15102013-08-17 00:46:16 +00007727 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007728 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00007729 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7730 << NameInfo.getName() << LookupContext << 0
7731 << SS.getRange());
Richard Smith09d5b3a2014-05-01 00:35:04 +00007732
7733 // If we corrected to an inheriting constructor, handle it as one.
7734 auto *RD = dyn_cast<CXXRecordDecl>(ND);
7735 if (RD && RD->isInjectedClassName()) {
7736 // Fix up the information we'll use to build the using declaration.
7737 if (Corrected.WillReplaceSpecifier()) {
7738 NestedNameSpecifierLocBuilder Builder;
7739 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
7740 QualifierLoc.getSourceRange());
7741 QualifierLoc = Builder.getWithLocInContext(Context);
7742 }
7743
7744 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
7745 Context.getCanonicalType(Context.getRecordType(RD))));
Craig Topperc3ec1492014-05-26 06:22:03 +00007746 NameInfo.setNamedTypeInfo(nullptr);
Richard Smith09d5b3a2014-05-01 00:35:04 +00007747
7748 // Build it and process it as an inheriting constructor.
7749 UsingDecl *UD = BuildValid();
7750 CheckInheritingConstructorUsingDecl(UD);
7751 return UD;
7752 }
7753
7754 // FIXME: Pick up all the declarations if we found an overloaded function.
7755 R.setLookupName(Corrected.getCorrection());
7756 R.addDecl(ND);
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007757 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007758 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007759 << NameInfo.getName() << LookupContext << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00007760 return BuildInvalid();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007761 }
Douglas Gregorfec52632009-06-20 00:51:54 +00007762 }
7763
Richard Smith09d5b3a2014-05-01 00:35:04 +00007764 if (R.isAmbiguous())
7765 return BuildInvalid();
Mike Stump11289f42009-09-09 15:08:12 +00007766
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007767 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00007768 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00007769 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007770 Diag(IdentLoc, diag::err_using_typename_non_type);
7771 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7772 Diag((*I)->getUnderlyingDecl()->getLocation(),
7773 diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00007774 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00007775 }
7776 } else {
7777 // If we asked for a non-typename and we got a type, error out,
7778 // but only if this is an instantiation of an unresolved using
7779 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00007780 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00007781 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7782 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00007783 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00007784 }
Anders Carlsson59140b32009-08-28 03:16:11 +00007785 }
7786
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007787 // C++0x N2914 [namespace.udecl]p6:
7788 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00007789 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007790 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7791 << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00007792 return BuildInvalid();
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00007793 }
Mike Stump11289f42009-09-09 15:08:12 +00007794
Richard Smith09d5b3a2014-05-01 00:35:04 +00007795 UsingDecl *UD = BuildValid();
John McCall84d87672009-12-10 09:41:52 +00007796 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007797 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00007798 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7799 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00007800 }
John McCall3f746822009-11-17 05:59:44 +00007801
7802 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00007803}
7804
Sebastian Redl08905022011-02-05 19:23:19 +00007805/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00007806bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007807 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00007808
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007809 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00007810 assert(SourceType &&
7811 "Using decl naming constructor doesn't have type in scope spec.");
7812 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7813
7814 // Check whether the named type is a direct base class.
Richard Smith09d5b3a2014-05-01 00:35:04 +00007815 bool AnyDependentBases = false;
7816 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
7817 AnyDependentBases);
7818 if (!Base && !AnyDependentBases) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007819 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00007820 diag::err_using_decl_constructor_not_in_direct_base)
7821 << UD->getNameInfo().getSourceRange()
7822 << QualType(SourceType, 0) << TargetClass;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007823 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00007824 return true;
7825 }
7826
Richard Smith09d5b3a2014-05-01 00:35:04 +00007827 if (Base)
7828 Base->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00007829
7830 return false;
7831}
7832
John McCall84d87672009-12-10 09:41:52 +00007833/// Checks that the given using declaration is not an invalid
7834/// redeclaration. Note that this is checking only for the using decl
7835/// itself, not for any ill-formedness among the UsingShadowDecls.
7836bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007837 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00007838 const CXXScopeSpec &SS,
7839 SourceLocation NameLoc,
7840 const LookupResult &Prev) {
7841 // C++03 [namespace.udecl]p8:
7842 // C++0x [namespace.udecl]p10:
7843 // A using-declaration is a declaration and can therefore be used
7844 // repeatedly where (and only where) multiple declarations are
7845 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00007846 //
John McCall032092f2010-11-29 18:01:58 +00007847 // That's in non-member contexts.
7848 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00007849 return false;
7850
Aaron Ballman4a979672014-01-03 13:56:08 +00007851 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall84d87672009-12-10 09:41:52 +00007852
7853 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7854 NamedDecl *D = *I;
7855
7856 bool DTypename;
7857 NestedNameSpecifier *DQual;
7858 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007859 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007860 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007861 } else if (UnresolvedUsingValueDecl *UD
7862 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7863 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007864 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007865 } else if (UnresolvedUsingTypenameDecl *UD
7866 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7867 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007868 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00007869 } else continue;
7870
7871 // using decls differ if one says 'typename' and the other doesn't.
7872 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007873 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00007874
7875 // using decls differ if they name different scopes (but note that
7876 // template instantiation can cause this check to trigger when it
7877 // didn't before instantiation).
7878 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7879 Context.getCanonicalNestedNameSpecifier(DQual))
7880 continue;
7881
7882 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00007883 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00007884 return true;
7885 }
7886
7887 return false;
7888}
7889
John McCall3969e302009-12-08 07:46:18 +00007890
John McCallb96ec562009-12-04 22:46:56 +00007891/// Checks that the given nested-name qualifier used in a using decl
7892/// in the current context is appropriately related to the current
7893/// scope. If an error is found, diagnoses it and returns true.
7894bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7895 const CXXScopeSpec &SS,
Richard Smith7ad0b882014-04-02 21:44:35 +00007896 const DeclarationNameInfo &NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00007897 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00007898 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007899
John McCall3969e302009-12-08 07:46:18 +00007900 if (!CurContext->isRecord()) {
7901 // C++03 [namespace.udecl]p3:
7902 // C++0x [namespace.udecl]p8:
7903 // A using-declaration for a class member shall be a member-declaration.
7904
7905 // If we weren't able to compute a valid scope, it must be a
7906 // dependent class scope.
7907 if (!NamedContext || NamedContext->isRecord()) {
Richard Smith7ad0b882014-04-02 21:44:35 +00007908 auto *RD = dyn_cast<CXXRecordDecl>(NamedContext);
7909 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
Craig Topperc3ec1492014-05-26 06:22:03 +00007910 RD = nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00007911
John McCall3969e302009-12-08 07:46:18 +00007912 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7913 << SS.getRange();
Richard Smith7ad0b882014-04-02 21:44:35 +00007914
7915 // If we have a complete, non-dependent source type, try to suggest a
7916 // way to get the same effect.
7917 if (!RD)
7918 return true;
7919
7920 // Find what this using-declaration was referring to.
7921 LookupResult R(*this, NameInfo, LookupOrdinaryName);
7922 R.setHideTags(false);
7923 R.suppressDiagnostics();
7924 LookupQualifiedName(R, RD);
7925
7926 if (R.getAsSingle<TypeDecl>()) {
7927 if (getLangOpts().CPlusPlus11) {
7928 // Convert 'using X::Y;' to 'using Y = X::Y;'.
7929 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
7930 << 0 // alias declaration
7931 << FixItHint::CreateInsertion(SS.getBeginLoc(),
7932 NameInfo.getName().getAsString() +
7933 " = ");
7934 } else {
7935 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
7936 SourceLocation InsertLoc =
7937 PP.getLocForEndOfToken(NameInfo.getLocEnd());
7938 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
7939 << 1 // typedef declaration
7940 << FixItHint::CreateReplacement(UsingLoc, "typedef")
7941 << FixItHint::CreateInsertion(
7942 InsertLoc, " " + NameInfo.getName().getAsString());
7943 }
7944 } else if (R.getAsSingle<VarDecl>()) {
7945 // Don't provide a fixit outside C++11 mode; we don't want to suggest
7946 // repeating the type of the static data member here.
7947 FixItHint FixIt;
7948 if (getLangOpts().CPlusPlus11) {
7949 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
7950 FixIt = FixItHint::CreateReplacement(
7951 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
7952 }
7953
7954 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
7955 << 2 // reference declaration
7956 << FixIt;
7957 }
John McCall3969e302009-12-08 07:46:18 +00007958 return true;
7959 }
7960
7961 // Otherwise, everything is known to be fine.
7962 return false;
7963 }
7964
7965 // The current scope is a record.
7966
7967 // If the named context is dependent, we can't decide much.
7968 if (!NamedContext) {
7969 // FIXME: in C++0x, we can diagnose if we can prove that the
7970 // nested-name-specifier does not refer to a base class, which is
7971 // still possible in some cases.
7972
7973 // Otherwise we have to conservatively report that things might be
7974 // okay.
7975 return false;
7976 }
7977
7978 if (!NamedContext->isRecord()) {
7979 // Ideally this would point at the last name in the specifier,
7980 // but we don't have that level of source info.
7981 Diag(SS.getRange().getBegin(),
7982 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00007983 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00007984 return true;
7985 }
7986
Douglas Gregor7c842292010-12-21 07:41:49 +00007987 if (!NamedContext->isDependentContext() &&
7988 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7989 return true;
7990
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007991 if (getLangOpts().CPlusPlus11) {
John McCall3969e302009-12-08 07:46:18 +00007992 // C++0x [namespace.udecl]p3:
7993 // In a using-declaration used as a member-declaration, the
7994 // nested-name-specifier shall name a base class of the class
7995 // being defined.
7996
7997 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7998 cast<CXXRecordDecl>(NamedContext))) {
7999 if (CurContext == NamedContext) {
8000 Diag(NameLoc,
8001 diag::err_using_decl_nested_name_specifier_is_current_class)
8002 << SS.getRange();
8003 return true;
8004 }
8005
8006 Diag(SS.getRange().getBegin(),
8007 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00008008 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00008009 << cast<CXXRecordDecl>(CurContext)
8010 << SS.getRange();
8011 return true;
8012 }
8013
8014 return false;
8015 }
8016
8017 // C++03 [namespace.udecl]p4:
8018 // A using-declaration used as a member-declaration shall refer
8019 // to a member of a base class of the class being defined [etc.].
8020
8021 // Salient point: SS doesn't have to name a base class as long as
8022 // lookup only finds members from base classes. Therefore we can
8023 // diagnose here only if we can prove that that can't happen,
8024 // i.e. if the class hierarchies provably don't intersect.
8025
8026 // TODO: it would be nice if "definitely valid" results were cached
8027 // in the UsingDecl and UsingShadowDecl so that these checks didn't
8028 // need to be repeated.
8029
8030 struct UserData {
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00008031 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall3969e302009-12-08 07:46:18 +00008032
8033 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
8034 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8035 Data->Bases.insert(Base);
8036 return true;
8037 }
8038
8039 bool hasDependentBases(const CXXRecordDecl *Class) {
8040 return !Class->forallBases(collect, this);
8041 }
8042
8043 /// Returns true if the base is dependent or is one of the
8044 /// accumulated base classes.
8045 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
8046 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8047 return !Data->Bases.count(Base);
8048 }
8049
8050 bool mightShareBases(const CXXRecordDecl *Class) {
8051 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
8052 }
8053 };
8054
8055 UserData Data;
8056
8057 // Returns false if we find a dependent base.
8058 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
8059 return false;
8060
8061 // Returns false if the class has a dependent base or if it or one
8062 // of its bases is present in the base set of the current context.
8063 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
8064 return false;
8065
8066 Diag(SS.getRange().getBegin(),
8067 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00008068 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00008069 << cast<CXXRecordDecl>(CurContext)
8070 << SS.getRange();
8071
8072 return true;
John McCallb96ec562009-12-04 22:46:56 +00008073}
8074
Richard Smithdda56e42011-04-15 14:24:37 +00008075Decl *Sema::ActOnAliasDeclaration(Scope *S,
8076 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008077 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00008078 SourceLocation UsingLoc,
8079 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00008080 AttributeList *AttrList,
Richard Smithdda56e42011-04-15 14:24:37 +00008081 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00008082 // Skip up to the relevant declaration scope.
8083 while (S->getFlags() & Scope::TemplateParamScope)
8084 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00008085 assert((S->getFlags() & Scope::DeclScope) &&
8086 "got alias-declaration outside of declaration scope");
8087
8088 if (Type.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00008089 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008090
8091 bool Invalid = false;
8092 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
Craig Topperc3ec1492014-05-26 06:22:03 +00008093 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky82e47802011-05-02 01:07:19 +00008094 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00008095
8096 if (DiagnoseClassNameShadow(CurContext, NameInfo))
Craig Topperc3ec1492014-05-26 06:22:03 +00008097 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008098
8099 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008100 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00008101 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008102 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8103 TInfo->getTypeLoc().getBeginLoc());
8104 }
Richard Smithdda56e42011-04-15 14:24:37 +00008105
8106 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8107 LookupName(Previous, S);
8108
8109 // Warn about shadowing the name of a template parameter.
8110 if (Previous.isSingleResult() &&
8111 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00008112 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00008113 Previous.clear();
8114 }
8115
8116 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8117 "name in alias declaration must be an identifier");
8118 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8119 Name.StartLocation,
8120 Name.Identifier, TInfo);
8121
8122 NewTD->setAccess(AS);
8123
8124 if (Invalid)
8125 NewTD->setInvalidDecl();
8126
Richard Smith54ecd982013-02-20 19:22:51 +00008127 ProcessDeclAttributeList(S, NewTD, AttrList);
8128
Richard Smith3f1b5d02011-05-05 21:57:07 +00008129 CheckTypedefForVariablyModifiedType(S, NewTD);
8130 Invalid |= NewTD->isInvalidDecl();
8131
Richard Smithdda56e42011-04-15 14:24:37 +00008132 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008133
8134 NamedDecl *NewND;
8135 if (TemplateParamLists.size()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008136 TypeAliasTemplateDecl *OldDecl = nullptr;
8137 TemplateParameterList *OldTemplateParams = nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008138
8139 if (TemplateParamLists.size() != 1) {
8140 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008141 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8142 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00008143 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008144 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00008145
8146 // Only consider previous declarations in the same scope.
8147 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8148 /*ExplicitInstantiationOrSpecialization*/false);
8149 if (!Previous.empty()) {
8150 Redeclaration = true;
8151
8152 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8153 if (!OldDecl && !Invalid) {
8154 Diag(UsingLoc, diag::err_redefinition_different_kind)
8155 << Name.Identifier;
8156
8157 NamedDecl *OldD = Previous.getRepresentativeDecl();
8158 if (OldD->getLocation().isValid())
8159 Diag(OldD->getLocation(), diag::note_previous_definition);
8160
8161 Invalid = true;
8162 }
8163
8164 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8165 if (TemplateParameterListsAreEqual(TemplateParams,
8166 OldDecl->getTemplateParameters(),
8167 /*Complain=*/true,
8168 TPL_TemplateMatch))
8169 OldTemplateParams = OldDecl->getTemplateParameters();
8170 else
8171 Invalid = true;
8172
8173 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8174 if (!Invalid &&
8175 !Context.hasSameType(OldTD->getUnderlyingType(),
8176 NewTD->getUnderlyingType())) {
8177 // FIXME: The C++0x standard does not clearly say this is ill-formed,
8178 // but we can't reasonably accept it.
8179 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8180 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8181 if (OldTD->getLocation().isValid())
8182 Diag(OldTD->getLocation(), diag::note_previous_definition);
8183 Invalid = true;
8184 }
8185 }
8186 }
8187
8188 // Merge any previous default template arguments into our parameters,
8189 // and check the parameter list.
8190 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8191 TPC_TypeAliasTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +00008192 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008193
8194 TypeAliasTemplateDecl *NewDecl =
8195 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8196 Name.Identifier, TemplateParams,
8197 NewTD);
8198
8199 NewDecl->setAccess(AS);
8200
8201 if (Invalid)
8202 NewDecl->setInvalidDecl();
8203 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00008204 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008205
8206 NewND = NewDecl;
8207 } else {
8208 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8209 NewND = NewTD;
8210 }
Richard Smithdda56e42011-04-15 14:24:37 +00008211
8212 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00008213 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00008214
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00008215 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008216 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00008217}
8218
John McCall48871652010-08-21 09:40:31 +00008219Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00008220 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00008221 SourceLocation AliasLoc,
8222 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00008223 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00008224 SourceLocation IdentLoc,
8225 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00008226
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008227 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00008228 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8229 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008230
Anders Carlssondca83c42009-03-28 06:23:46 +00008231 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00008232 NamedDecl *PrevDecl
8233 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8234 ForRedeclaration);
8235 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
Craig Topperc3ec1492014-05-26 06:22:03 +00008236 PrevDecl = nullptr;
Douglas Gregor5cf8d672010-05-03 15:37:31 +00008237
8238 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008239 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00008240 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008241 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00008242 // FIXME: At some point, we'll want to create the (redundant)
8243 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00008244 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00008245 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
Craig Topperc3ec1492014-05-26 06:22:03 +00008246 return nullptr;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008247 }
Mike Stump11289f42009-09-09 15:08:12 +00008248
Anders Carlssondca83c42009-03-28 06:23:46 +00008249 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
8250 diag::err_redefinition_different_kind;
8251 Diag(AliasLoc, DiagID) << Alias;
8252 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Craig Topperc3ec1492014-05-26 06:22:03 +00008253 return nullptr;
Anders Carlssondca83c42009-03-28 06:23:46 +00008254 }
8255
John McCall27b18f82009-11-17 02:14:36 +00008256 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00008257 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008258
John McCall9f3059a2009-10-09 21:13:30 +00008259 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008260 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00008261 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00008262 return nullptr;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00008263 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00008264 }
Mike Stump11289f42009-09-09 15:08:12 +00008265
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008266 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00008267 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00008268 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00008269 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00008270
John McCalld8d0d432010-02-16 06:53:13 +00008271 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00008272 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00008273}
8274
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008275Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008276Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8277 CXXMethodDecl *MD) {
8278 CXXRecordDecl *ClassDecl = MD->getParent();
8279
Douglas Gregor6d880b12010-07-01 22:31:05 +00008280 // C++ [except.spec]p14:
8281 // An implicitly declared special member function (Clause 12) shall have an
8282 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00008283 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008284 if (ClassDecl->isInvalidDecl())
8285 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00008286
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008287 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008288 for (const auto &B : ClassDecl->bases()) {
8289 if (B.isVirtual()) // Handled below.
Douglas Gregor6d880b12010-07-01 22:31:05 +00008290 continue;
8291
Aaron Ballman574705e2014-03-13 15:41:46 +00008292 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008293 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008294 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8295 // If this is a deleted function, add it anyway. This might be conformant
8296 // with the standard. This might not. I'm not sure. It might not matter.
8297 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008298 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008299 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008300 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008301
8302 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008303 for (const auto &B : ClassDecl->vbases()) {
8304 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008305 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008306 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8307 // If this is a deleted function, add it anyway. This might be conformant
8308 // with the standard. This might not. I'm not sure. It might not matter.
8309 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008310 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008311 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008312 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008313
8314 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008315 for (const auto *F : ClassDecl->fields()) {
Richard Smith938f40b2011-06-11 17:19:42 +00008316 if (F->hasInClassInitializer()) {
8317 if (Expr *E = F->getInClassInitializer())
8318 ExceptSpec.CalledExpr(E);
8319 else if (!F->isInvalidDecl())
Richard Smithd3b5c9082012-07-27 04:22:15 +00008320 // DR1351:
8321 // If the brace-or-equal-initializer of a non-static data member
8322 // invokes a defaulted default constructor of its class or of an
8323 // enclosing class in a potentially evaluated subexpression, the
8324 // program is ill-formed.
8325 //
8326 // This resolution is unworkable: the exception specification of the
8327 // default constructor can be needed in an unevaluated context, in
8328 // particular, in the operand of a noexcept-expression, and we can be
8329 // unable to compute an exception specification for an enclosed class.
8330 //
8331 // We do not allow an in-class initializer to require the evaluation
8332 // of the exception specification for any in-class initializer whose
8333 // definition is not lexically complete.
8334 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith938f40b2011-06-11 17:19:42 +00008335 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00008336 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00008337 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8338 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8339 // If this is a deleted function, add it anyway. This might be conformant
8340 // with the standard. This might not. I'm not sure. It might not matter.
8341 // In particular, the problem is that this function never gets called. It
8342 // might just be ill-formed because this function attempts to refer to
8343 // a deleted function here.
8344 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008345 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008346 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008347 }
John McCalldb40c7f2010-12-14 08:05:40 +00008348
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008349 return ExceptSpec;
8350}
8351
Richard Smithc2bc61b2013-03-18 21:12:30 +00008352Sema::ImplicitExceptionSpecification
Richard Smithb7151b92013-04-10 06:11:48 +00008353Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8354 CXXRecordDecl *ClassDecl = CD->getParent();
8355
8356 // C++ [except.spec]p14:
8357 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00008358 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00008359 if (ClassDecl->isInvalidDecl())
8360 return ExceptSpec;
8361
8362 // Inherited constructor.
8363 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8364 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8365 // FIXME: Copying or moving the parameters could add extra exceptions to the
8366 // set, as could the default arguments for the inherited constructor. This
8367 // will be addressed when we implement the resolution of core issue 1351.
8368 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8369
8370 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008371 for (const auto &B : ClassDecl->bases()) {
8372 if (B.isVirtual()) // Handled below.
Richard Smithb7151b92013-04-10 06:11:48 +00008373 continue;
8374
Aaron Ballman574705e2014-03-13 15:41:46 +00008375 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008376 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8377 if (BaseClassDecl == InheritedDecl)
8378 continue;
8379 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8380 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008381 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008382 }
8383 }
8384
8385 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008386 for (const auto &B : ClassDecl->vbases()) {
8387 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008388 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8389 if (BaseClassDecl == InheritedDecl)
8390 continue;
8391 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8392 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008393 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008394 }
8395 }
8396
8397 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008398 for (const auto *F : ClassDecl->fields()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008399 if (F->hasInClassInitializer()) {
8400 if (Expr *E = F->getInClassInitializer())
8401 ExceptSpec.CalledExpr(E);
8402 else if (!F->isInvalidDecl())
8403 Diag(CD->getLocation(),
8404 diag::err_in_class_initializer_references_def_ctor) << CD;
8405 } else if (const RecordType *RecordTy
8406 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8407 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8408 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8409 if (Constructor)
8410 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8411 }
8412 }
8413
Richard Smithc2bc61b2013-03-18 21:12:30 +00008414 return ExceptSpec;
8415}
8416
Richard Smith8bf22e52012-11-29 01:34:07 +00008417namespace {
8418/// RAII object to register a special member as being currently declared.
8419struct DeclaringSpecialMember {
8420 Sema &S;
8421 Sema::SpecialMemberDecl D;
8422 bool WasAlreadyBeingDeclared;
8423
8424 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8425 : S(S), D(RD, CSM) {
8426 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8427 if (WasAlreadyBeingDeclared)
8428 // This almost never happens, but if it does, ensure that our cache
8429 // doesn't contain a stale result.
8430 S.SpecialMemberCache.clear();
8431
8432 // FIXME: Register a note to be produced if we encounter an error while
8433 // declaring the special member.
8434 }
8435 ~DeclaringSpecialMember() {
8436 if (!WasAlreadyBeingDeclared)
8437 S.SpecialMembersBeingDeclared.erase(D);
8438 }
8439
8440 /// \brief Are we already trying to declare this special member?
8441 bool isAlreadyBeingDeclared() const {
8442 return WasAlreadyBeingDeclared;
8443 }
8444};
8445}
8446
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008447CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8448 CXXRecordDecl *ClassDecl) {
8449 // C++ [class.ctor]p5:
8450 // A default constructor for a class X is a constructor of class X
8451 // that can be called without an argument. If there is no
8452 // user-declared constructor for class X, a default constructor is
8453 // implicitly declared. An implicitly-declared default constructor
8454 // is an inline public member of its class.
Richard Smith7d125a12012-11-27 21:20:31 +00008455 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008456 "Should not build implicit default constructor!");
8457
Richard Smith8bf22e52012-11-29 01:34:07 +00008458 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8459 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00008460 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00008461
Richard Smithb5800092012-06-10 05:43:50 +00008462 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8463 CXXDefaultConstructor,
8464 false);
8465
Douglas Gregor6d880b12010-07-01 22:31:05 +00008466 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008467 CanQualType ClassType
8468 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008469 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008470 DeclarationName Name
8471 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008472 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00008473 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00008474 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8475 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8476 /*isImplicitlyDeclared=*/true, Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008477 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00008478 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008479 DefaultCon->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008480
8481 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008482 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008483 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008484
Richard Smith6b02d462012-12-08 08:32:28 +00008485 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8486 // constructors is easy to compute.
8487 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8488
8489 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008490 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008491
Douglas Gregor9672f922010-07-03 00:47:00 +00008492 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00008493 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00008494
Douglas Gregor0be31a22010-07-02 17:43:08 +00008495 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00008496 PushOnScopeChains(DefaultCon, S, false);
8497 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008498
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008499 return DefaultCon;
8500}
8501
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008502void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8503 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008504 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008505 !Constructor->doesThisDeclarationHaveABody() &&
8506 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008507 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008508
Anders Carlsson423f5d82010-04-23 16:04:08 +00008509 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00008510 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00008511
Eli Friedmaneaf34142012-10-18 20:14:08 +00008512 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008513 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00008514 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008515 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008516 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008517 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00008518 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00008519 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00008520 }
Douglas Gregor73193272010-09-20 16:48:21 +00008521
Daniel Jasperb3b0b802014-06-20 08:44:22 +00008522 SourceLocation Loc = Constructor->getLocEnd().isValid()
8523 ? Constructor->getLocEnd()
8524 : Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008525 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +00008526
Eli Friedman276dd182013-09-05 00:02:25 +00008527 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +00008528 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008529
8530 if (ASTMutationListener *L = getASTMutationListener()) {
8531 L->CompletedImplicitDefinition(Constructor);
8532 }
Richard Trieuef64e942013-10-25 00:56:00 +00008533
8534 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008535}
8536
Richard Smith938f40b2011-06-11 17:19:42 +00008537void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008538 // Perform any delayed checks on exception specifications.
8539 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +00008540}
8541
Richard Smith185be182013-04-10 05:48:59 +00008542namespace {
8543/// Information on inheriting constructors to declare.
8544class InheritingConstructorInfo {
8545public:
8546 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8547 : SemaRef(SemaRef), Derived(Derived) {
8548 // Mark the constructors that we already have in the derived class.
8549 //
8550 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8551 // unless there is a user-declared constructor with the same signature in
8552 // the class where the using-declaration appears.
8553 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8554 }
8555
8556 void inheritAll(CXXRecordDecl *RD) {
8557 visitAll(RD, &InheritingConstructorInfo::inherit);
8558 }
8559
8560private:
8561 /// Information about an inheriting constructor.
8562 struct InheritingConstructor {
8563 InheritingConstructor()
Craig Topperc3ec1492014-05-26 06:22:03 +00008564 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
Richard Smith185be182013-04-10 05:48:59 +00008565
8566 /// If \c true, a constructor with this signature is already declared
8567 /// in the derived class.
8568 bool DeclaredInDerived;
8569
8570 /// The constructor which is inherited.
8571 const CXXConstructorDecl *BaseCtor;
8572
8573 /// The derived constructor we declared.
8574 CXXConstructorDecl *DerivedCtor;
8575 };
8576
8577 /// Inheriting constructors with a given canonical type. There can be at
8578 /// most one such non-template constructor, and any number of templated
8579 /// constructors.
8580 struct InheritingConstructorsForType {
8581 InheritingConstructor NonTemplate;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008582 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8583 Templates;
Richard Smith185be182013-04-10 05:48:59 +00008584
8585 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8586 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8587 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8588 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8589 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8590 false, S.TPL_TemplateMatch))
8591 return Templates[I].second;
8592 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8593 return Templates.back().second;
Sebastian Redl08905022011-02-05 19:23:19 +00008594 }
Richard Smith185be182013-04-10 05:48:59 +00008595
8596 return NonTemplate;
8597 }
8598 };
8599
8600 /// Get or create the inheriting constructor record for a constructor.
8601 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8602 QualType CtorType) {
8603 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8604 .getEntry(SemaRef, Ctor);
8605 }
8606
8607 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8608
8609 /// Process all constructors for a class.
8610 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00008611 for (const auto *Ctor : RD->ctors())
8612 (this->*Callback)(Ctor);
Richard Smith185be182013-04-10 05:48:59 +00008613 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8614 I(RD->decls_begin()), E(RD->decls_end());
8615 I != E; ++I) {
8616 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8617 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8618 (this->*Callback)(CD);
Sebastian Redl08905022011-02-05 19:23:19 +00008619 }
8620 }
Richard Smith185be182013-04-10 05:48:59 +00008621
8622 /// Note that a constructor (or constructor template) was declared in Derived.
8623 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8624 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8625 }
8626
8627 /// Inherit a single constructor.
8628 void inherit(const CXXConstructorDecl *Ctor) {
8629 const FunctionProtoType *CtorType =
8630 Ctor->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00008631 ArrayRef<QualType> ArgTypes(CtorType->getParamTypes());
Richard Smith185be182013-04-10 05:48:59 +00008632 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8633
8634 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8635
8636 // Core issue (no number yet): the ellipsis is always discarded.
8637 if (EPI.Variadic) {
8638 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8639 SemaRef.Diag(Ctor->getLocation(),
8640 diag::note_using_decl_constructor_ellipsis);
8641 EPI.Variadic = false;
8642 }
8643
8644 // Declare a constructor for each number of parameters.
8645 //
8646 // C++11 [class.inhctor]p1:
8647 // The candidate set of inherited constructors from the class X named in
8648 // the using-declaration consists of [... modulo defects ...] for each
8649 // constructor or constructor template of X, the set of constructors or
8650 // constructor templates that results from omitting any ellipsis parameter
8651 // specification and successively omitting parameters with a default
8652 // argument from the end of the parameter-type-list
Richard Smith3c626ed2013-04-17 19:00:52 +00008653 unsigned MinParams = minParamsToInherit(Ctor);
8654 unsigned Params = Ctor->getNumParams();
8655 if (Params >= MinParams) {
8656 do
8657 declareCtor(UsingLoc, Ctor,
8658 SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00008659 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
Richard Smith3c626ed2013-04-17 19:00:52 +00008660 while (Params > MinParams &&
8661 Ctor->getParamDecl(--Params)->hasDefaultArg());
8662 }
Richard Smith185be182013-04-10 05:48:59 +00008663 }
8664
8665 /// Find the using-declaration which specified that we should inherit the
8666 /// constructors of \p Base.
8667 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8668 // No fancy lookup required; just look for the base constructor name
8669 // directly within the derived class.
8670 ASTContext &Context = SemaRef.Context;
8671 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8672 Context.getCanonicalType(Context.getRecordType(Base)));
8673 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8674 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8675 }
8676
8677 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8678 // C++11 [class.inhctor]p3:
8679 // [F]or each constructor template in the candidate set of inherited
8680 // constructors, a constructor template is implicitly declared
8681 if (Ctor->getDescribedFunctionTemplate())
8682 return 0;
8683
8684 // For each non-template constructor in the candidate set of inherited
8685 // constructors other than a constructor having no parameters or a
8686 // copy/move constructor having a single parameter, a constructor is
8687 // implicitly declared [...]
8688 if (Ctor->getNumParams() == 0)
8689 return 1;
8690 if (Ctor->isCopyOrMoveConstructor())
8691 return 2;
8692
8693 // Per discussion on core reflector, never inherit a constructor which
8694 // would become a default, copy, or move constructor of Derived either.
8695 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8696 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8697 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8698 }
8699
8700 /// Declare a single inheriting constructor, inheriting the specified
8701 /// constructor, with the given type.
8702 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8703 QualType DerivedType) {
8704 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8705
8706 // C++11 [class.inhctor]p3:
8707 // ... a constructor is implicitly declared with the same constructor
8708 // characteristics unless there is a user-declared constructor with
8709 // the same signature in the class where the using-declaration appears
8710 if (Entry.DeclaredInDerived)
8711 return;
8712
8713 // C++11 [class.inhctor]p7:
8714 // If two using-declarations declare inheriting constructors with the
8715 // same signature, the program is ill-formed
8716 if (Entry.DerivedCtor) {
8717 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8718 // Only diagnose this once per constructor.
8719 if (Entry.DerivedCtor->isInvalidDecl())
8720 return;
8721 Entry.DerivedCtor->setInvalidDecl();
8722
8723 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8724 SemaRef.Diag(BaseCtor->getLocation(),
8725 diag::note_using_decl_constructor_conflict_current_ctor);
8726 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8727 diag::note_using_decl_constructor_conflict_previous_ctor);
8728 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8729 diag::note_using_decl_constructor_conflict_previous_using);
8730 } else {
8731 // Core issue (no number): if the same inheriting constructor is
8732 // produced by multiple base class constructors from the same base
8733 // class, the inheriting constructor is defined as deleted.
8734 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8735 }
8736
8737 return;
8738 }
8739
8740 ASTContext &Context = SemaRef.Context;
8741 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8742 Context.getCanonicalType(Context.getRecordType(Derived)));
8743 DeclarationNameInfo NameInfo(Name, UsingLoc);
8744
Craig Topperc3ec1492014-05-26 06:22:03 +00008745 TemplateParameterList *TemplateParams = nullptr;
Richard Smith185be182013-04-10 05:48:59 +00008746 if (const FunctionTemplateDecl *FTD =
8747 BaseCtor->getDescribedFunctionTemplate()) {
8748 TemplateParams = FTD->getTemplateParameters();
8749 // We're reusing template parameters from a different DeclContext. This
8750 // is questionable at best, but works out because the template depth in
8751 // both places is guaranteed to be 0.
8752 // FIXME: Rebuild the template parameters in the new context, and
8753 // transform the function type to refer to them.
8754 }
8755
8756 // Build type source info pointing at the using-declaration. This is
8757 // required by template instantiation.
8758 TypeSourceInfo *TInfo =
8759 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8760 FunctionProtoTypeLoc ProtoLoc =
8761 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8762
8763 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8764 Context, Derived, UsingLoc, NameInfo, DerivedType,
8765 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8766 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8767
8768 // Build an unevaluated exception specification for this constructor.
8769 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8770 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00008771 EPI.ExceptionSpec.Type = EST_Unevaluated;
8772 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
Alp Toker314cc812014-01-25 16:55:45 +00008773 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00008774 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +00008775
8776 // Build the parameter declarations.
8777 SmallVector<ParmVarDecl *, 16> ParamDecls;
Alp Toker9cacbab2014-01-20 20:26:09 +00008778 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +00008779 TypeSourceInfo *TInfo =
Alp Toker9cacbab2014-01-20 20:26:09 +00008780 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
Richard Smith185be182013-04-10 05:48:59 +00008781 ParmVarDecl *PD = ParmVarDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00008782 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
8783 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
Richard Smith185be182013-04-10 05:48:59 +00008784 PD->setScopeInfo(0, I);
8785 PD->setImplicit();
8786 ParamDecls.push_back(PD);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00008787 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +00008788 }
8789
8790 // Set up the new constructor.
8791 DerivedCtor->setAccess(BaseCtor->getAccess());
8792 DerivedCtor->setParams(ParamDecls);
8793 DerivedCtor->setInheritedConstructor(BaseCtor);
8794 if (BaseCtor->isDeleted())
8795 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8796
8797 // If this is a constructor template, build the template declaration.
8798 if (TemplateParams) {
8799 FunctionTemplateDecl *DerivedTemplate =
8800 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8801 TemplateParams, DerivedCtor);
8802 DerivedTemplate->setAccess(BaseCtor->getAccess());
8803 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8804 Derived->addDecl(DerivedTemplate);
8805 } else {
8806 Derived->addDecl(DerivedCtor);
8807 }
8808
8809 Entry.BaseCtor = BaseCtor;
8810 Entry.DerivedCtor = DerivedCtor;
8811 }
8812
8813 Sema &SemaRef;
8814 CXXRecordDecl *Derived;
8815 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8816 MapType Map;
8817};
8818}
8819
8820void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8821 // Defer declaring the inheriting constructors until the class is
8822 // instantiated.
8823 if (ClassDecl->isDependentContext())
Sebastian Redl08905022011-02-05 19:23:19 +00008824 return;
8825
Richard Smith185be182013-04-10 05:48:59 +00008826 // Find base classes from which we might inherit constructors.
8827 SmallVector<CXXRecordDecl*, 4> InheritedBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00008828 for (const auto &BaseIt : ClassDecl->bases())
8829 if (BaseIt.getInheritConstructors())
8830 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
Richard Smithc2bc61b2013-03-18 21:12:30 +00008831
Richard Smith185be182013-04-10 05:48:59 +00008832 // Go no further if we're not inheriting any constructors.
8833 if (InheritedBases.empty())
8834 return;
Sebastian Redl08905022011-02-05 19:23:19 +00008835
Richard Smith185be182013-04-10 05:48:59 +00008836 // Declare the inherited constructors.
8837 InheritingConstructorInfo ICI(*this, ClassDecl);
8838 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8839 ICI.inheritAll(InheritedBases[I]);
Sebastian Redl08905022011-02-05 19:23:19 +00008840}
8841
Richard Smithc2bc61b2013-03-18 21:12:30 +00008842void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8843 CXXConstructorDecl *Constructor) {
8844 CXXRecordDecl *ClassDecl = Constructor->getParent();
8845 assert(Constructor->getInheritedConstructor() &&
8846 !Constructor->doesThisDeclarationHaveABody() &&
8847 !Constructor->isDeleted());
8848
8849 SynthesizedFunctionScope Scope(*this, Constructor);
8850 DiagnosticErrorTrap Trap(Diags);
8851 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8852 Trap.hasErrorOccurred()) {
8853 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8854 << Context.getTagDeclType(ClassDecl);
8855 Constructor->setInvalidDecl();
8856 return;
8857 }
8858
8859 SourceLocation Loc = Constructor->getLocation();
8860 Constructor->setBody(new (Context) CompoundStmt(Loc));
8861
Eli Friedman276dd182013-09-05 00:02:25 +00008862 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +00008863 MarkVTableUsed(CurrentLocation, ClassDecl);
8864
8865 if (ASTMutationListener *L = getASTMutationListener()) {
8866 L->CompletedImplicitDefinition(Constructor);
8867 }
8868}
8869
8870
Alexis Huntf91729462011-05-12 22:46:25 +00008871Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008872Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8873 CXXRecordDecl *ClassDecl = MD->getParent();
8874
Douglas Gregorf1203042010-07-01 19:09:28 +00008875 // C++ [except.spec]p14:
8876 // An implicitly declared special member function (Clause 12) shall have
8877 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +00008878 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008879 if (ClassDecl->isInvalidDecl())
8880 return ExceptSpec;
8881
Douglas Gregorf1203042010-07-01 19:09:28 +00008882 // Direct base-class destructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008883 for (const auto &B : ClassDecl->bases()) {
8884 if (B.isVirtual()) // Handled below.
Douglas Gregorf1203042010-07-01 19:09:28 +00008885 continue;
8886
Aaron Ballman574705e2014-03-13 15:41:46 +00008887 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8888 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008889 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008890 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008891
Douglas Gregorf1203042010-07-01 19:09:28 +00008892 // Virtual base-class destructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008893 for (const auto &B : ClassDecl->vbases()) {
8894 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
8895 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008896 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008897 }
Sebastian Redl623ea822011-05-19 05:13:44 +00008898
Douglas Gregorf1203042010-07-01 19:09:28 +00008899 // Field destructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008900 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorf1203042010-07-01 19:09:28 +00008901 if (const RecordType *RecordTy
8902 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00008903 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +00008904 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00008905 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008906
Alexis Huntf91729462011-05-12 22:46:25 +00008907 return ExceptSpec;
8908}
8909
8910CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8911 // C++ [class.dtor]p2:
8912 // If a class has no user-declared destructor, a destructor is
8913 // declared implicitly. An implicitly-declared destructor is an
8914 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +00008915 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +00008916
Richard Smith8bf22e52012-11-29 01:34:07 +00008917 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8918 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00008919 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00008920
Douglas Gregor7454c562010-07-02 20:37:36 +00008921 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00008922 CanQualType ClassType
8923 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008924 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00008925 DeclarationName Name
8926 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008927 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00008928 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +00008929 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +00008930 QualType(), nullptr, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008931 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00008932 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00008933 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00008934 Destructor->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00008935
8936 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008937 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008938 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008939
Richard Smith6b02d462012-12-08 08:32:28 +00008940 AddOverriddenMethods(ClassDecl, Destructor);
8941
8942 // We don't need to use SpecialMemberIsTrivial here; triviality for
8943 // destructors is easy to compute.
8944 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8945
8946 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008947 SetDeclDeleted(Destructor, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008948
Douglas Gregor7454c562010-07-02 20:37:36 +00008949 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00008950 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +00008951
Douglas Gregor7454c562010-07-02 20:37:36 +00008952 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00008953 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00008954 PushOnScopeChains(Destructor, S, false);
8955 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +00008956
Douglas Gregorf1203042010-07-01 19:09:28 +00008957 return Destructor;
8958}
8959
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008960void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00008961 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008962 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +00008963 !Destructor->doesThisDeclarationHaveABody() &&
8964 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008965 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00008966 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008967 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008968
Douglas Gregor54818f02010-05-12 16:39:35 +00008969 if (Destructor->isInvalidDecl())
8970 return;
8971
Eli Friedmaneaf34142012-10-18 20:14:08 +00008972 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008973
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008974 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00008975 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8976 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00008977
Douglas Gregor54818f02010-05-12 16:39:35 +00008978 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008979 Diag(CurrentLocation, diag::note_member_synthesized_at)
8980 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8981
8982 Destructor->setInvalidDecl();
8983 return;
8984 }
8985
Daniel Jasperb3b0b802014-06-20 08:44:22 +00008986 SourceLocation Loc = Destructor->getLocEnd().isValid()
8987 ? Destructor->getLocEnd()
8988 : Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008989 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +00008990 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +00008991 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008992
8993 if (ASTMutationListener *L = getASTMutationListener()) {
8994 L->CompletedImplicitDefinition(Destructor);
8995 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00008996}
8997
Richard Smith84973e52012-04-21 18:42:51 +00008998/// \brief Perform any semantic analysis which needs to be delayed until all
8999/// pending class member declarations have been parsed.
9000void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00009001 // If the context is an invalid C++ class, just suppress these checks.
9002 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9003 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +00009004 DelayedDefaultedMemberExceptionSpecs.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00009005 DelayedDestructorExceptionSpecChecks.clear();
9006 return;
9007 }
9008 }
Richard Smith84973e52012-04-21 18:42:51 +00009009}
9010
Richard Smithd3b5c9082012-07-27 04:22:15 +00009011void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9012 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009013 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00009014 "adjusting dtor exception specs was introduced in c++11");
9015
Sebastian Redl623ea822011-05-19 05:13:44 +00009016 // C++11 [class.dtor]p3:
9017 // A declaration of a destructor that does not have an exception-
9018 // specification is implicitly considered to have the same exception-
9019 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009020 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +00009021 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009022 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +00009023 return;
9024
Chandler Carruth9a797572011-09-20 04:55:26 +00009025 // Replace the destructor's type, building off the existing one. Fortunately,
9026 // the only thing of interest in the destructor type is its extended info.
9027 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009028 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00009029 EPI.ExceptionSpec.Type = EST_Unevaluated;
9030 EPI.ExceptionSpec.SourceDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009031 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +00009032
Sebastian Redl623ea822011-05-19 05:13:44 +00009033 // FIXME: If the destructor has a body that could throw, and the newly created
9034 // spec doesn't allow exceptions, we should emit a warning, because this
9035 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009036 // However, we don't have a body or an exception specification yet, so it
9037 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +00009038}
9039
Pavel Labath58934982013-08-30 08:52:28 +00009040namespace {
9041/// \brief An abstract base class for all helper classes used in building the
9042// copy/move operators. These classes serve as factory functions and help us
9043// avoid using the same Expr* in the AST twice.
9044class ExprBuilder {
9045 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9046 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9047
9048protected:
9049 static Expr *assertNotNull(Expr *E) {
9050 assert(E && "Expression construction must not fail.");
9051 return E;
9052 }
9053
9054public:
9055 ExprBuilder() {}
9056 virtual ~ExprBuilder() {}
9057
9058 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9059};
9060
9061class RefBuilder: public ExprBuilder {
9062 VarDecl *Var;
9063 QualType VarType;
9064
9065public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009066 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009067 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009068 }
9069
9070 RefBuilder(VarDecl *Var, QualType VarType)
9071 : Var(Var), VarType(VarType) {}
9072};
9073
9074class ThisBuilder: public ExprBuilder {
9075public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009076 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009077 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
Pavel Labath58934982013-08-30 08:52:28 +00009078 }
9079};
9080
9081class CastBuilder: public ExprBuilder {
9082 const ExprBuilder &Builder;
9083 QualType Type;
9084 ExprValueKind Kind;
9085 const CXXCastPath &Path;
9086
9087public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009088 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009089 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9090 CK_UncheckedDerivedToBase, Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009091 &Path).get());
Pavel Labath58934982013-08-30 08:52:28 +00009092 }
9093
9094 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9095 const CXXCastPath &Path)
9096 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9097};
9098
9099class DerefBuilder: public ExprBuilder {
9100 const ExprBuilder &Builder;
9101
9102public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009103 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009104 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009105 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009106 }
9107
9108 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9109};
9110
9111class MemberBuilder: public ExprBuilder {
9112 const ExprBuilder &Builder;
9113 QualType Type;
9114 CXXScopeSpec SS;
9115 bool IsArrow;
9116 LookupResult &MemberLookup;
9117
9118public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009119 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009120 return assertNotNull(S.BuildMemberReferenceExpr(
Craig Topperc3ec1492014-05-26 06:22:03 +00009121 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009122 nullptr, MemberLookup, nullptr).get());
Pavel Labath58934982013-08-30 08:52:28 +00009123 }
9124
9125 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9126 LookupResult &MemberLookup)
9127 : Builder(Builder), Type(Type), IsArrow(IsArrow),
9128 MemberLookup(MemberLookup) {}
9129};
9130
9131class MoveCastBuilder: public ExprBuilder {
9132 const ExprBuilder &Builder;
9133
9134public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009135 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009136 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9137 }
9138
9139 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9140};
9141
9142class LvalueConvBuilder: public ExprBuilder {
9143 const ExprBuilder &Builder;
9144
9145public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009146 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009147 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009148 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009149 }
9150
9151 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9152};
9153
9154class SubscriptBuilder: public ExprBuilder {
9155 const ExprBuilder &Base;
9156 const ExprBuilder &Index;
9157
9158public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009159 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009160 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009161 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009162 }
9163
9164 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9165 : Base(Base), Index(Index) {}
9166};
9167
9168} // end anonymous namespace
9169
Richard Smith41ae3282012-11-14 00:50:40 +00009170/// When generating a defaulted copy or move assignment operator, if a field
9171/// should be copied with __builtin_memcpy rather than via explicit assignments,
9172/// do so. This optimization only applies for arrays of scalars, and for arrays
9173/// of class type where the selected copy/move-assignment operator is trivial.
9174static StmtResult
9175buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009176 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +00009177 // Compute the size of the memory buffer to be copied.
9178 QualType SizeType = S.Context.getSizeType();
9179 llvm::APInt Size(S.Context.getTypeSize(SizeType),
9180 S.Context.getTypeSizeInChars(T).getQuantity());
9181
9182 // Take the address of the field references for "from" and "to". We
9183 // directly construct UnaryOperators here because semantic analysis
9184 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009185 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009186 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9187 S.Context.getPointerType(From->getType()),
9188 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +00009189 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009190 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9191 S.Context.getPointerType(To->getType()),
9192 VK_RValue, OK_Ordinary, Loc);
9193
9194 const Type *E = T->getBaseElementTypeUnsafe();
9195 bool NeedsCollectableMemCpy =
9196 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9197
9198 // Create a reference to the __builtin_objc_memmove_collectable function
9199 StringRef MemCpyName = NeedsCollectableMemCpy ?
9200 "__builtin_objc_memmove_collectable" :
9201 "__builtin_memcpy";
9202 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9203 Sema::LookupOrdinaryName);
9204 S.LookupName(R, S.TUScope, true);
9205
9206 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9207 if (!MemCpy)
9208 // Something went horribly wrong earlier, and we will have complained
9209 // about it.
9210 return StmtError();
9211
9212 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
Craig Topperc3ec1492014-05-26 06:22:03 +00009213 VK_RValue, Loc, nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009214 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9215
9216 Expr *CallArgs[] = {
9217 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9218 };
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009219 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
Richard Smith41ae3282012-11-14 00:50:40 +00009220 Loc, CallArgs, Loc);
9221
9222 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009223 return Call.getAs<Stmt>();
Richard Smith41ae3282012-11-14 00:50:40 +00009224}
9225
Sebastian Redl22653ba2011-08-30 19:58:05 +00009226/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00009227/// \c To.
9228///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009229/// This routine is used to copy/move the members of a class with an
9230/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00009231/// copied are arrays, this routine builds for loops to copy them.
9232///
9233/// \param S The Sema object used for type-checking.
9234///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009235/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009236///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009237/// \param T The type of the expressions being copied/moved. Both expressions
9238/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009239///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009240/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009241///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009242/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009243///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009244/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009245/// Otherwise, it's a non-static member subobject.
9246///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009247/// \param Copying Whether we're copying or moving.
9248///
Douglas Gregorb139cd52010-05-01 20:49:11 +00009249/// \param Depth Internal parameter recording the depth of the recursion.
9250///
Richard Smith41ae3282012-11-14 00:50:40 +00009251/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9252/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +00009253static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +00009254buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009255 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009256 bool CopyingBaseSubobject, bool Copying,
9257 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +00009258 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00009259 // Each subobject is assigned in the manner appropriate to its type:
9260 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00009261 // - if the subobject is of class type, as if by a call to operator= with
9262 // the subobject as the object expression and the corresponding
9263 // subobject of x as a single function argument (as if by explicit
9264 // qualification; that is, ignoring any possible virtual overriding
9265 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +00009266 //
9267 // C++03 [class.copy]p13:
9268 // - if the subobject is of class type, the copy assignment operator for
9269 // the class is used (as if by explicit qualification; that is,
9270 // ignoring any possible virtual overriding functions in more derived
9271 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009272 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9273 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +00009274
Douglas Gregorb139cd52010-05-01 20:49:11 +00009275 // Look for operator=.
9276 DeclarationName Name
9277 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9278 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9279 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009280
Richard Smith52c0b582012-11-13 00:54:12 +00009281 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9282 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009283 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +00009284 LookupResult::Filter F = OpLookup.makeFilter();
9285 while (F.hasNext()) {
9286 NamedDecl *D = F.next();
9287 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9288 if (Method->isCopyAssignmentOperator() ||
9289 (!Copying && Method->isMoveAssignmentOperator()))
9290 continue;
9291
9292 F.erase();
9293 }
9294 F.done();
John McCallab8c2732010-03-16 06:11:48 +00009295 }
Richard Smith52c0b582012-11-13 00:54:12 +00009296
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009297 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +00009298 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009299 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +00009300 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009301 // ambiguities), we need to cast "this" to that subobject type; to
9302 // ensure that we don't go through the virtual call mechanism, we need
9303 // to qualify the operator= name with the base class (see below). However,
9304 // this means that if the base class has a protected copy assignment
9305 // operator, the protected member access check will fail. So, we
9306 // rewrite "protected" access to "public" access in this case, since we
9307 // know by construction that we're calling from a derived class.
9308 if (CopyingBaseSubobject) {
9309 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9310 L != LEnd; ++L) {
9311 if (L.getAccess() == AS_protected)
9312 L.setAccess(AS_public);
9313 }
9314 }
Richard Smith52c0b582012-11-13 00:54:12 +00009315
Douglas Gregorb139cd52010-05-01 20:49:11 +00009316 // Create the nested-name-specifier that will be used to qualify the
9317 // reference to operator=; this is required to suppress the virtual
9318 // call mechanism.
9319 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00009320 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +00009321 SS.MakeTrivial(S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +00009322 NestedNameSpecifier::Create(S.Context, nullptr, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00009323 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00009324 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009325
Douglas Gregorb139cd52010-05-01 20:49:11 +00009326 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00009327 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +00009328 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9329 SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009330 /*FirstQualifierInScope=*/nullptr,
Abramo Bagnara7945c982012-01-27 09:46:47 +00009331 OpLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00009332 /*TemplateArgs=*/nullptr,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009333 /*SuppressQualifierCheck=*/true);
9334 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009335 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009336
Douglas Gregorb139cd52010-05-01 20:49:11 +00009337 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00009338
Pavel Labath58934982013-08-30 08:52:28 +00009339 Expr *FromInst = From.build(S, Loc);
Craig Topperc3ec1492014-05-26 06:22:03 +00009340 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009341 OpEqualRef.getAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +00009342 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009343 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009344 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009345
Richard Smith41ae3282012-11-14 00:50:40 +00009346 // If we built a call to a trivial 'operator=' while copying an array,
9347 // bail out. We'll replace the whole shebang with a memcpy.
9348 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9349 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
Craig Topperc3ec1492014-05-26 06:22:03 +00009350 return StmtResult((Stmt*)nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009351
Richard Smith52c0b582012-11-13 00:54:12 +00009352 // Convert to an expression-statement, and clean up any produced
9353 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +00009354 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009355 }
John McCallab8c2732010-03-16 06:11:48 +00009356
Richard Smith52c0b582012-11-13 00:54:12 +00009357 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +00009358 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +00009359 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009360 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +00009361 ExprResult Assignment = S.CreateBuiltinBinOp(
9362 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009363 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009364 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +00009365 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009366 }
Richard Smith52c0b582012-11-13 00:54:12 +00009367
9368 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +00009369 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +00009370
Douglas Gregorb139cd52010-05-01 20:49:11 +00009371 // Construct a loop over the array bounds, e.g.,
9372 //
9373 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9374 //
9375 // that will copy each of the array elements.
9376 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +00009377
Douglas Gregorb139cd52010-05-01 20:49:11 +00009378 // Create the iteration variable.
Craig Topperc3ec1492014-05-26 06:22:03 +00009379 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009380 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009381 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009382 llvm::raw_svector_ostream OS(Str);
9383 OS << "__i" << Depth;
9384 IterationVarName = &S.Context.Idents.get(OS.str());
9385 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00009386 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009387 IterationVarName, SizeType,
9388 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009389 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +00009390
Douglas Gregorb139cd52010-05-01 20:49:11 +00009391 // Initialize the iteration variable to zero.
9392 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009393 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009394
Pavel Labath58934982013-08-30 08:52:28 +00009395 // Creates a reference to the iteration variable.
9396 RefBuilder IterationVarRef(IterationVar, SizeType);
9397 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +00009398
Douglas Gregorb139cd52010-05-01 20:49:11 +00009399 // Create the DeclStmt that holds the iteration variable.
9400 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009401
Douglas Gregorb139cd52010-05-01 20:49:11 +00009402 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +00009403 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9404 MoveCastBuilder FromIndexMove(FromIndexCopy);
9405 const ExprBuilder *FromIndex;
9406 if (Copying)
9407 FromIndex = &FromIndexCopy;
9408 else
9409 FromIndex = &FromIndexMove;
9410
9411 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009412
9413 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +00009414 StmtResult Copy =
9415 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +00009416 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +00009417 Copying, Depth + 1);
9418 // Bail out if copying fails or if we determined that we should use memcpy.
9419 if (Copy.isInvalid() || !Copy.get())
9420 return Copy;
9421
9422 // Create the comparison against the array bound.
9423 llvm::APInt Upper
9424 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9425 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +00009426 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +00009427 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9428 BO_NE, S.Context.BoolTy,
9429 VK_RValue, OK_Ordinary, Loc, false);
9430
9431 // Create the pre-increment of the iteration variable.
9432 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +00009433 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9434 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009435
Douglas Gregorb139cd52010-05-01 20:49:11 +00009436 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00009437 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009438 S.MakeFullExpr(Comparison),
Craig Topperc3ec1492014-05-26 06:22:03 +00009439 nullptr, S.MakeFullDiscardedValueExpr(Increment),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009440 Loc, Copy.get());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009441}
9442
Richard Smith41ae3282012-11-14 00:50:40 +00009443static StmtResult
9444buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009445 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009446 bool CopyingBaseSubobject, bool Copying) {
9447 // Maybe we should use a memcpy?
9448 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9449 T.isTriviallyCopyableType(S.Context))
9450 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9451
9452 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9453 CopyingBaseSubobject,
9454 Copying, 0));
9455
9456 // If we ended up picking a trivial assignment operator for an array of a
9457 // non-trivially-copyable class type, just emit a memcpy.
9458 if (!Result.isInvalid() && !Result.get())
9459 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9460
9461 return Result;
9462}
9463
Richard Smithd3b5c9082012-07-27 04:22:15 +00009464Sema::ImplicitExceptionSpecification
9465Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9466 CXXRecordDecl *ClassDecl = MD->getParent();
9467
9468 ImplicitExceptionSpecification ExceptSpec(*this);
9469 if (ClassDecl->isInvalidDecl())
9470 return ExceptSpec;
9471
9472 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00009473 assert(T->getNumParams() == 1 && "not a copy assignment op");
9474 unsigned ArgQuals =
9475 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009476
Douglas Gregor68e11362010-07-01 17:48:08 +00009477 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +00009478 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +00009479 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00009480
9481 // It is unspecified whether or not an implicit copy assignment operator
9482 // attempts to deduplicate calls to assignment operators of virtual bases are
9483 // made. As such, this exception specification is effectively unspecified.
9484 // Based on a similar decision made for constness in C++0x, we're erring on
9485 // the side of assuming such calls to be made regardless of whether they
9486 // actually happen.
Aaron Ballman574705e2014-03-13 15:41:46 +00009487 for (const auto &Base : ClassDecl->bases()) {
9488 if (Base.isVirtual())
Alexis Hunt491ec602011-06-21 23:42:56 +00009489 continue;
9490
Douglas Gregor330b9cf2010-07-02 21:50:04 +00009491 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009492 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009493 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9494 ArgQuals, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009495 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00009496 }
Alexis Hunt491ec602011-06-21 23:42:56 +00009497
Aaron Ballman445a9392014-03-13 16:15:17 +00009498 for (const auto &Base : ClassDecl->vbases()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00009499 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009500 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009501 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9502 ArgQuals, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009503 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +00009504 }
9505
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009506 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009507 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00009508 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9509 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +00009510 LookupCopyingAssignment(FieldClassDecl,
9511 ArgQuals | FieldType.getCVRQualifiers(),
9512 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009513 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009514 }
Douglas Gregor68e11362010-07-01 17:48:08 +00009515 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009516
Richard Smithd3b5c9082012-07-27 04:22:15 +00009517 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +00009518}
9519
9520CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9521 // Note: The following rules are largely analoguous to the copy
9522 // constructor rules. Note that virtual bases are not taken into account
9523 // for determining the argument type of the operator. Note also that
9524 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +00009525 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +00009526
Richard Smith8bf22e52012-11-29 01:34:07 +00009527 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9528 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009529 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009530
Alexis Hunt119f3652011-05-14 05:23:20 +00009531 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9532 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +00009533 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9534 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +00009535 ArgType = ArgType.withConst();
9536 ArgType = Context.getLValueReferenceType(ArgType);
9537
Richard Smith99005e62013-05-07 03:19:20 +00009538 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9539 CXXCopyAssignment,
9540 Const);
9541
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009542 // An implicitly-declared copy assignment operator is an inline public
9543 // member of its class.
9544 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009545 SourceLocation ClassLoc = ClassDecl->getLocation();
9546 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009547 CXXMethodDecl *CopyAssignment =
9548 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009549 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
9550 /*isInline=*/true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009551 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00009552 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009553 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009554
9555 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009556 FunctionProtoType::ExtProtoInfo EPI =
9557 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009558 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009559
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009560 // Add the parameter to the operator.
9561 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +00009562 ClassLoc, ClassLoc,
9563 /*Id=*/nullptr, ArgType,
9564 /*TInfo=*/nullptr, SC_None,
9565 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +00009566 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +00009567
Richard Smith6b02d462012-12-08 08:32:28 +00009568 AddOverriddenMethods(ClassDecl, CopyAssignment);
9569
9570 CopyAssignment->setTrivial(
9571 ClassDecl->needsOverloadResolutionForCopyAssignment()
9572 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9573 : ClassDecl->hasTrivialCopyAssignment());
9574
Richard Smith852265f2012-03-30 20:53:28 +00009575 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smithb4d2a152013-04-02 19:38:47 +00009576 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +00009577
Richard Smith6b02d462012-12-08 08:32:28 +00009578 // Note that we have added this copy-assignment operator.
9579 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9580
9581 if (Scope *S = getScopeForContext(ClassDecl))
9582 PushOnScopeChains(CopyAssignment, S, false);
9583 ClassDecl->addDecl(CopyAssignment);
9584
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009585 return CopyAssignment;
9586}
9587
Richard Smithd577fbb2013-06-13 03:23:42 +00009588/// Diagnose an implicit copy operation for a class which is odr-used, but
9589/// which is deprecated because the class has a user-declared copy constructor,
9590/// copy assignment operator, or destructor.
9591static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9592 SourceLocation UseLoc) {
9593 assert(CopyOp->isImplicit());
9594
9595 CXXRecordDecl *RD = CopyOp->getParent();
Craig Topperc3ec1492014-05-26 06:22:03 +00009596 CXXMethodDecl *UserDeclaredOperation = nullptr;
Richard Smithd577fbb2013-06-13 03:23:42 +00009597
9598 // In Microsoft mode, assignment operations don't affect constructors and
9599 // vice versa.
9600 if (RD->hasUserDeclaredDestructor()) {
9601 UserDeclaredOperation = RD->getDestructor();
9602 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9603 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009604 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009605 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009606 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009607 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009608 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009609 break;
9610 }
9611 }
9612 assert(UserDeclaredOperation);
9613 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9614 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009615 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009616 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00009617 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009618 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00009619 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009620 break;
9621 }
9622 }
9623 assert(UserDeclaredOperation);
9624 }
9625
9626 if (UserDeclaredOperation) {
9627 S.Diag(UserDeclaredOperation->getLocation(),
9628 diag::warn_deprecated_copy_operation)
9629 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9630 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9631 S.Diag(UseLoc, diag::note_member_synthesized_at)
9632 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9633 : Sema::CXXCopyAssignment)
9634 << RD;
9635 }
9636}
9637
Douglas Gregorb139cd52010-05-01 20:49:11 +00009638void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9639 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00009640 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009641 CopyAssignOperator->isOverloadedOperator() &&
9642 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009643 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9644 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009645 "DefineImplicitCopyAssignment called for wrong function");
9646
9647 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9648
9649 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9650 CopyAssignOperator->setInvalidDecl();
9651 return;
9652 }
Richard Smithd577fbb2013-06-13 03:23:42 +00009653
9654 // C++11 [class.copy]p18:
9655 // The [definition of an implicitly declared copy assignment operator] is
9656 // deprecated if the class has a user-declared copy constructor or a
9657 // user-declared destructor.
9658 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9659 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9660
Eli Friedman276dd182013-09-05 00:02:25 +00009661 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009662
Eli Friedmaneaf34142012-10-18 20:14:08 +00009663 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009664 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009665
9666 // C++0x [class.copy]p30:
9667 // The implicitly-defined or explicitly-defaulted copy assignment operator
9668 // for a non-union class X performs memberwise copy assignment of its
9669 // subobjects. The direct base classes of X are assigned first, in the
9670 // order of their declaration in the base-specifier-list, and then the
9671 // immediate non-static data members of X are assigned, in the order in
9672 // which they were declared in the class definition.
9673
9674 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009675 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009676
9677 // The parameter for the "other" object, which we are copying from.
9678 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9679 Qualifiers OtherQuals = Other->getType().getQualifiers();
9680 QualType OtherRefType = Other->getType();
9681 if (const LValueReferenceType *OtherRef
9682 = OtherRefType->getAs<LValueReferenceType>()) {
9683 OtherRefType = OtherRef->getPointeeType();
9684 OtherQuals = OtherRefType.getQualifiers();
9685 }
9686
9687 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +00009688 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
9689 ? CopyAssignOperator->getLocEnd()
9690 : CopyAssignOperator->getLocation();
9691
Pavel Labath58934982013-08-30 08:52:28 +00009692 // Builds a DeclRefExpr for the "other" object.
9693 RefBuilder OtherRef(Other, OtherRefType);
9694
9695 // Builds the "this" pointer.
9696 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009697
9698 // Assign base classes.
9699 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +00009700 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009701 // Form the assignment:
9702 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +00009703 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009704 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009705 Invalid = true;
9706 continue;
9707 }
9708
John McCallcf142162010-08-07 06:22:56 +00009709 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +00009710 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +00009711
Douglas Gregorb139cd52010-05-01 20:49:11 +00009712 // Construct the "from" expression, which is an implicit cast to the
9713 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009714 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9715 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009716
9717 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009718 DerefBuilder DerefThis(This);
9719 CastBuilder To(DerefThis,
9720 Context.getCVRQualifiedType(
9721 BaseType, CopyAssignOperator->getTypeQualifiers()),
9722 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009723
9724 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +00009725 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +00009726 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009727 /*CopyingBaseSubobject=*/true,
9728 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009729 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009730 Diag(CurrentLocation, diag::note_member_synthesized_at)
9731 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9732 CopyAssignOperator->setInvalidDecl();
9733 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009734 }
9735
9736 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009737 Statements.push_back(Copy.getAs<Expr>());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009738 }
9739
Douglas Gregorb139cd52010-05-01 20:49:11 +00009740 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009741 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00009742 if (Field->isUnnamedBitfield())
9743 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +00009744
9745 if (Field->isInvalidDecl()) {
9746 Invalid = true;
9747 continue;
9748 }
9749
Douglas Gregorb139cd52010-05-01 20:49:11 +00009750 // Check for members of reference type; we can't copy those.
9751 if (Field->getType()->isReferenceType()) {
9752 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9753 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9754 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009755 Diag(CurrentLocation, diag::note_member_synthesized_at)
9756 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009757 Invalid = true;
9758 continue;
9759 }
9760
9761 // Check for members of const-qualified, non-class type.
9762 QualType BaseType = Context.getBaseElementType(Field->getType());
9763 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9764 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9765 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9766 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009767 Diag(CurrentLocation, diag::note_member_synthesized_at)
9768 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009769 Invalid = true;
9770 continue;
9771 }
John McCall1b1a1db2011-06-17 00:18:42 +00009772
9773 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00009774 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9775 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009776
9777 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00009778 if (FieldType->isIncompleteArrayType()) {
9779 assert(ClassDecl->hasFlexibleArrayMember() &&
9780 "Incomplete array type is not valid");
9781 continue;
9782 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009783
9784 // Build references to the field in the object we're copying from and to.
9785 CXXScopeSpec SS; // Intentionally empty
9786 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9787 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009788 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009789 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +00009790
9791 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9792
9793 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009794
Douglas Gregorb139cd52010-05-01 20:49:11 +00009795 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +00009796 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +00009797 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00009798 /*CopyingBaseSubobject=*/false,
9799 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009800 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00009801 Diag(CurrentLocation, diag::note_member_synthesized_at)
9802 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9803 CopyAssignOperator->setInvalidDecl();
9804 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009805 }
9806
9807 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009808 Statements.push_back(Copy.getAs<Stmt>());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009809 }
9810
9811 if (!Invalid) {
9812 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +00009813 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009814
Nick Lewyckyd78f92f2014-05-03 00:41:18 +00009815 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00009816 if (Return.isInvalid())
9817 Invalid = true;
9818 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009819 Statements.push_back(Return.getAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00009820
9821 if (Trap.hasErrorOccurred()) {
9822 Diag(CurrentLocation, diag::note_member_synthesized_at)
9823 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9824 Invalid = true;
9825 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00009826 }
9827 }
9828
9829 if (Invalid) {
9830 CopyAssignOperator->setInvalidDecl();
9831 return;
9832 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009833
9834 StmtResult Body;
9835 {
9836 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009837 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009838 /*isStmtExpr=*/false);
9839 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9840 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009841 CopyAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00009842
9843 if (ASTMutationListener *L = getASTMutationListener()) {
9844 L->CompletedImplicitDefinition(CopyAssignOperator);
9845 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009846}
9847
Sebastian Redl22653ba2011-08-30 19:58:05 +00009848Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009849Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9850 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009851
Richard Smithd3b5c9082012-07-27 04:22:15 +00009852 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009853 if (ClassDecl->isInvalidDecl())
9854 return ExceptSpec;
9855
9856 // C++0x [except.spec]p14:
9857 // An implicitly declared special member function (Clause 12) shall have an
9858 // exception-specification. [...]
9859
9860 // It is unspecified whether or not an implicit move assignment operator
9861 // attempts to deduplicate calls to assignment operators of virtual bases are
9862 // made. As such, this exception specification is effectively unspecified.
9863 // Based on a similar decision made for constness in C++0x, we're erring on
9864 // the side of assuming such calls to be made regardless of whether they
9865 // actually happen.
9866 // Note that a move constructor is not implicitly declared when there are
9867 // virtual bases, but it can still be user-declared and explicitly defaulted.
Aaron Ballman574705e2014-03-13 15:41:46 +00009868 for (const auto &Base : ClassDecl->bases()) {
9869 if (Base.isVirtual())
Sebastian Redl22653ba2011-08-30 19:58:05 +00009870 continue;
9871
9872 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009873 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009874 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009875 0, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009876 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009877 }
9878
Aaron Ballman445a9392014-03-13 16:15:17 +00009879 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009880 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009881 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009882 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +00009883 0, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009884 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009885 }
9886
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009887 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009888 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009889 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +00009890 if (CXXMethodDecl *MoveAssign =
9891 LookupMovingAssignment(FieldClassDecl,
9892 FieldType.getCVRQualifiers(),
9893 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009894 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009895 }
9896 }
9897
9898 return ExceptSpec;
9899}
9900
9901CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00009902 assert(ClassDecl->needsImplicitMoveAssignment());
9903
Richard Smith8bf22e52012-11-29 01:34:07 +00009904 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9905 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009906 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009907
Sebastian Redl22653ba2011-08-30 19:58:05 +00009908 // Note: The following rules are largely analoguous to the move
9909 // constructor rules.
9910
Sebastian Redl22653ba2011-08-30 19:58:05 +00009911 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9912 QualType RetType = Context.getLValueReferenceType(ArgType);
9913 ArgType = Context.getRValueReferenceType(ArgType);
9914
Richard Smith99005e62013-05-07 03:19:20 +00009915 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9916 CXXMoveAssignment,
9917 false);
9918
Sebastian Redl22653ba2011-08-30 19:58:05 +00009919 // An implicitly-declared move assignment operator is an inline public
9920 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +00009921 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9922 SourceLocation ClassLoc = ClassDecl->getLocation();
9923 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009924 CXXMethodDecl *MoveAssignment =
9925 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009926 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
Richard Smith99005e62013-05-07 03:19:20 +00009927 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009928 MoveAssignment->setAccess(AS_public);
9929 MoveAssignment->setDefaulted();
9930 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +00009931
Richard Smithd3b5c9082012-07-27 04:22:15 +00009932 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009933 FunctionProtoType::ExtProtoInfo EPI =
9934 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009935 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009936
Sebastian Redl22653ba2011-08-30 19:58:05 +00009937 // Add the parameter to the operator.
9938 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +00009939 ClassLoc, ClassLoc,
9940 /*Id=*/nullptr, ArgType,
9941 /*TInfo=*/nullptr, SC_None,
9942 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +00009943 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009944
Richard Smith6b02d462012-12-08 08:32:28 +00009945 AddOverriddenMethods(ClassDecl, MoveAssignment);
9946
9947 MoveAssignment->setTrivial(
9948 ClassDecl->needsOverloadResolutionForMoveAssignment()
9949 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9950 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +00009951
Richard Smithd951a1d2012-02-18 02:02:13 +00009952 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +00009953 ClassDecl->setImplicitMoveAssignmentIsDeleted();
9954 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009955 }
9956
Richard Smith6b02d462012-12-08 08:32:28 +00009957 // Note that we have added this copy-assignment operator.
9958 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9959
Sebastian Redl22653ba2011-08-30 19:58:05 +00009960 if (Scope *S = getScopeForContext(ClassDecl))
9961 PushOnScopeChains(MoveAssignment, S, false);
9962 ClassDecl->addDecl(MoveAssignment);
9963
Sebastian Redl22653ba2011-08-30 19:58:05 +00009964 return MoveAssignment;
9965}
9966
Richard Smithb2504bd2013-11-04 04:26:14 +00009967/// Check if we're implicitly defining a move assignment operator for a class
9968/// with virtual bases. Such a move assignment might move-assign the virtual
9969/// base multiple times.
9970static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
9971 SourceLocation CurrentLocation) {
9972 assert(!Class->isDependentContext() && "should not define dependent move");
9973
9974 // Only a virtual base could get implicitly move-assigned multiple times.
9975 // Only a non-trivial move assignment can observe this. We only want to
9976 // diagnose if we implicitly define an assignment operator that assigns
9977 // two base classes, both of which move-assign the same virtual base.
9978 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
9979 Class->getNumBases() < 2)
9980 return;
9981
9982 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
9983 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
9984 VBaseMap VBases;
9985
Aaron Ballman574705e2014-03-13 15:41:46 +00009986 for (auto &BI : Class->bases()) {
9987 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +00009988 while (!Worklist.empty()) {
9989 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
9990 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
9991
9992 // If the base has no non-trivial move assignment operators,
9993 // we don't care about moves from it.
9994 if (!Base->hasNonTrivialMoveAssignment())
9995 continue;
9996
9997 // If there's nothing virtual here, skip it.
9998 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
9999 continue;
10000
10001 // If we're not actually going to call a move assignment for this base,
10002 // or the selected move assignment is trivial, skip it.
10003 Sema::SpecialMemberOverloadResult *SMOR =
10004 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10005 /*ConstArg*/false, /*VolatileArg*/false,
10006 /*RValueThis*/true, /*ConstThis*/false,
10007 /*VolatileThis*/false);
10008 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10009 !SMOR->getMethod()->isMoveAssignmentOperator())
10010 continue;
10011
10012 if (BaseSpec->isVirtual()) {
10013 // We're going to move-assign this virtual base, and its move
10014 // assignment operator is not trivial. If this can happen for
10015 // multiple distinct direct bases of Class, diagnose it. (If it
10016 // only happens in one base, we'll diagnose it when synthesizing
10017 // that base class's move assignment operator.)
10018 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +000010019 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +000010020 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +000010021 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010022 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10023 << Class << Base;
10024 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10025 << (Base->getCanonicalDecl() ==
10026 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10027 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +000010028 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +000010029 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +000010030 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10031 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +000010032
10033 // Only diagnose each vbase once.
Craig Topperc3ec1492014-05-26 06:22:03 +000010034 Existing = nullptr;
Richard Smithb2504bd2013-11-04 04:26:14 +000010035 }
10036 } else {
10037 // Only walk over bases that have defaulted move assignment operators.
10038 // We assume that any user-provided move assignment operator handles
10039 // the multiple-moves-of-vbase case itself somehow.
10040 if (!SMOR->getMethod()->isDefaulted())
10041 continue;
10042
10043 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +000010044 for (auto &BI : Base->bases())
10045 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000010046 }
10047 }
10048 }
10049}
10050
Sebastian Redl22653ba2011-08-30 19:58:05 +000010051void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10052 CXXMethodDecl *MoveAssignOperator) {
10053 assert((MoveAssignOperator->isDefaulted() &&
10054 MoveAssignOperator->isOverloadedOperator() &&
10055 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000010056 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10057 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010058 "DefineImplicitMoveAssignment called for wrong function");
10059
10060 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10061
10062 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10063 MoveAssignOperator->setInvalidDecl();
10064 return;
10065 }
10066
Eli Friedman276dd182013-09-05 00:02:25 +000010067 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010068
Eli Friedmaneaf34142012-10-18 20:14:08 +000010069 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010070 DiagnosticErrorTrap Trap(Diags);
10071
10072 // C++0x [class.copy]p28:
10073 // The implicitly-defined or move assignment operator for a non-union class
10074 // X performs memberwise move assignment of its subobjects. The direct base
10075 // classes of X are assigned first, in the order of their declaration in the
10076 // base-specifier-list, and then the immediate non-static data members of X
10077 // are assigned, in the order in which they were declared in the class
10078 // definition.
10079
Richard Smithb2504bd2013-11-04 04:26:14 +000010080 // Issue a warning if our implicit move assignment operator will move
10081 // from a virtual base more than once.
10082 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +000010083
Sebastian Redl22653ba2011-08-30 19:58:05 +000010084 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000010085 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010086
10087 // The parameter for the "other" object, which we are move from.
10088 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10089 QualType OtherRefType = Other->getType()->
10090 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +000010091 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010092 "Bad argument type of defaulted move assignment");
10093
10094 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010095 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10096 ? MoveAssignOperator->getLocEnd()
10097 : MoveAssignOperator->getLocation();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010098
Pavel Labath58934982013-08-30 08:52:28 +000010099 // Builds a reference to the "other" object.
10100 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010101 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +000010102 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010103
Pavel Labath58934982013-08-30 08:52:28 +000010104 // Builds the "this" pointer.
10105 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010106
Sebastian Redl22653ba2011-08-30 19:58:05 +000010107 // Assign base classes.
10108 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000010109 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010110 // C++11 [class.copy]p28:
10111 // It is unspecified whether subobjects representing virtual base classes
10112 // are assigned more than once by the implicitly-defined copy assignment
10113 // operator.
10114 // FIXME: Do not assign to a vbase that will be assigned by some other base
10115 // class. For a move-assignment, this can result in the vbase being moved
10116 // multiple times.
10117
Sebastian Redl22653ba2011-08-30 19:58:05 +000010118 // Form the assignment:
10119 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000010120 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010121 if (!BaseType->isRecordType()) {
10122 Invalid = true;
10123 continue;
10124 }
10125
10126 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000010127 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010128
10129 // Construct the "from" expression, which is an implicit cast to the
10130 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010131 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010132
10133 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000010134 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010135
10136 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010137 CastBuilder To(DerefThis,
10138 Context.getCVRQualifiedType(
10139 BaseType, MoveAssignOperator->getTypeQualifiers()),
10140 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010141
10142 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +000010143 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000010144 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010145 /*CopyingBaseSubobject=*/true,
10146 /*Copying=*/false);
10147 if (Move.isInvalid()) {
10148 Diag(CurrentLocation, diag::note_member_synthesized_at)
10149 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10150 MoveAssignOperator->setInvalidDecl();
10151 return;
10152 }
10153
10154 // Success! Record the move.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010155 Statements.push_back(Move.getAs<Expr>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010156 }
10157
Sebastian Redl22653ba2011-08-30 19:58:05 +000010158 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010159 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +000010160 if (Field->isUnnamedBitfield())
10161 continue;
10162
Eli Friedmanc9817fd2013-06-07 01:48:56 +000010163 if (Field->isInvalidDecl()) {
10164 Invalid = true;
10165 continue;
10166 }
10167
Sebastian Redl22653ba2011-08-30 19:58:05 +000010168 // Check for members of reference type; we can't move those.
10169 if (Field->getType()->isReferenceType()) {
10170 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10171 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10172 Diag(Field->getLocation(), diag::note_declared_at);
10173 Diag(CurrentLocation, diag::note_member_synthesized_at)
10174 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10175 Invalid = true;
10176 continue;
10177 }
10178
10179 // Check for members of const-qualified, non-class type.
10180 QualType BaseType = Context.getBaseElementType(Field->getType());
10181 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10182 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10183 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10184 Diag(Field->getLocation(), diag::note_declared_at);
10185 Diag(CurrentLocation, diag::note_member_synthesized_at)
10186 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10187 Invalid = true;
10188 continue;
10189 }
10190
10191 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000010192 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10193 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010194
10195 QualType FieldType = Field->getType().getNonReferenceType();
10196 if (FieldType->isIncompleteArrayType()) {
10197 assert(ClassDecl->hasFlexibleArrayMember() &&
10198 "Incomplete array type is not valid");
10199 continue;
10200 }
10201
10202 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010203 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10204 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010205 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010206 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000010207 MemberBuilder From(MoveOther, OtherRefType,
10208 /*IsArrow=*/false, MemberLookup);
10209 MemberBuilder To(This, getCurrentThisType(),
10210 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010211
Pavel Labath58934982013-08-30 08:52:28 +000010212 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +000010213 "Member reference with rvalue base must be rvalue except for reference "
10214 "members, which aren't allowed for move assignment.");
10215
Sebastian Redl22653ba2011-08-30 19:58:05 +000010216 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000010217 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010218 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010219 /*CopyingBaseSubobject=*/false,
10220 /*Copying=*/false);
10221 if (Move.isInvalid()) {
10222 Diag(CurrentLocation, diag::note_member_synthesized_at)
10223 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10224 MoveAssignOperator->setInvalidDecl();
10225 return;
10226 }
Richard Smith11d19592012-11-12 23:33:00 +000010227
Sebastian Redl22653ba2011-08-30 19:58:05 +000010228 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010229 Statements.push_back(Move.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010230 }
10231
10232 if (!Invalid) {
10233 // Add a "return *this;"
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010234 ExprResult ThisObj =
10235 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10236
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010237 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010238 if (Return.isInvalid())
10239 Invalid = true;
10240 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010241 Statements.push_back(Return.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010242
10243 if (Trap.hasErrorOccurred()) {
10244 Diag(CurrentLocation, diag::note_member_synthesized_at)
10245 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10246 Invalid = true;
10247 }
10248 }
10249 }
10250
10251 if (Invalid) {
10252 MoveAssignOperator->setInvalidDecl();
10253 return;
10254 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010255
10256 StmtResult Body;
10257 {
10258 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010259 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010260 /*isStmtExpr=*/false);
10261 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10262 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010263 MoveAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010264
10265 if (ASTMutationListener *L = getASTMutationListener()) {
10266 L->CompletedImplicitDefinition(MoveAssignOperator);
10267 }
10268}
10269
Richard Smithd3b5c9082012-07-27 04:22:15 +000010270Sema::ImplicitExceptionSpecification
10271Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10272 CXXRecordDecl *ClassDecl = MD->getParent();
10273
10274 ImplicitExceptionSpecification ExceptSpec(*this);
10275 if (ClassDecl->isInvalidDecl())
10276 return ExceptSpec;
10277
10278 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000010279 assert(T->getNumParams() >= 1 && "not a copy ctor");
10280 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010281
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010282 // C++ [except.spec]p14:
10283 // An implicitly declared special member function (Clause 12) shall have an
10284 // exception-specification. [...]
Aaron Ballman574705e2014-03-13 15:41:46 +000010285 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010286 // Virtual bases are handled below.
Aaron Ballman574705e2014-03-13 15:41:46 +000010287 if (Base.isVirtual())
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010288 continue;
10289
Douglas Gregora6d69502010-07-02 23:41:54 +000010290 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010291 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010292 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010293 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman574705e2014-03-13 15:41:46 +000010294 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010295 }
Aaron Ballman445a9392014-03-13 16:15:17 +000010296 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregora6d69502010-07-02 23:41:54 +000010297 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010298 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010299 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010300 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman445a9392014-03-13 16:15:17 +000010301 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010302 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010303 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010304 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000010305 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10306 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000010307 LookupCopyingConstructor(FieldClassDecl,
10308 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000010309 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010310 }
10311 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010312
Richard Smithd3b5c9082012-07-27 04:22:15 +000010313 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000010314}
10315
10316CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10317 CXXRecordDecl *ClassDecl) {
10318 // C++ [class.copy]p4:
10319 // If the class definition does not explicitly declare a copy
10320 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000010321 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000010322
Richard Smith8bf22e52012-11-29 01:34:07 +000010323 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10324 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010325 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010326
Alexis Hunt913820d2011-05-13 06:10:58 +000010327 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10328 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000010329 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000010330 if (Const)
10331 ArgType = ArgType.withConst();
10332 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000010333
Richard Smithb5800092012-06-10 05:43:50 +000010334 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10335 CXXCopyConstructor,
10336 Const);
10337
Douglas Gregor54be3392010-07-01 17:57:27 +000010338 DeclarationName Name
10339 = Context.DeclarationNames.getCXXConstructorName(
10340 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010341 SourceLocation ClassLoc = ClassDecl->getLocation();
10342 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000010343
10344 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010345 // member of its class.
10346 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010347 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000010348 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010349 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000010350 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000010351 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010352
Richard Smithd3b5c9082012-07-27 04:22:15 +000010353 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010354 FunctionProtoType::ExtProtoInfo EPI =
10355 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010356 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010357 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010358
Douglas Gregor54be3392010-07-01 17:57:27 +000010359 // Add the parameter to the constructor.
10360 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000010361 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010362 /*IdentifierInfo=*/nullptr,
10363 ArgType, /*TInfo=*/nullptr,
10364 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010365 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000010366
Richard Smith6b02d462012-12-08 08:32:28 +000010367 CopyConstructor->setTrivial(
10368 ClassDecl->needsOverloadResolutionForCopyConstructor()
10369 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10370 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000010371
Richard Smith852265f2012-03-30 20:53:28 +000010372 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +000010373 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010374
Richard Smith6b02d462012-12-08 08:32:28 +000010375 // Note that we have declared this constructor.
10376 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10377
10378 if (Scope *S = getScopeForContext(ClassDecl))
10379 PushOnScopeChains(CopyConstructor, S, false);
10380 ClassDecl->addDecl(CopyConstructor);
10381
Douglas Gregor54be3392010-07-01 17:57:27 +000010382 return CopyConstructor;
10383}
10384
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010385void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000010386 CXXConstructorDecl *CopyConstructor) {
10387 assert((CopyConstructor->isDefaulted() &&
10388 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010389 !CopyConstructor->doesThisDeclarationHaveABody() &&
10390 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010391 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010392
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000010393 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010394 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010395
Richard Smithd577fbb2013-06-13 03:23:42 +000010396 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000010397 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000010398 // deprecated if the class has a user-declared copy assignment operator
10399 // or a user-declared destructor.
10400 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10401 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10402
Eli Friedmaneaf34142012-10-18 20:14:08 +000010403 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010404 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010405
David Blaikie3fc2f912013-01-17 05:26:25 +000010406 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010407 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000010408 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000010409 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000010410 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000010411 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010412 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10413 ? CopyConstructor->getLocEnd()
10414 : CopyConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010415 Sema::CompoundScopeRAII CompoundScope(*this);
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010416 CopyConstructor->setBody(
10417 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000010418 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010419
Eli Friedman276dd182013-09-05 00:02:25 +000010420 CopyConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000010421 MarkVTableUsed(CurrentLocation, ClassDecl);
10422
Sebastian Redlab238a72011-04-24 16:28:06 +000010423 if (ASTMutationListener *L = getASTMutationListener()) {
10424 L->CompletedImplicitDefinition(CopyConstructor);
10425 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010426}
10427
Sebastian Redl22653ba2011-08-30 19:58:05 +000010428Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010429Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10430 CXXRecordDecl *ClassDecl = MD->getParent();
10431
Sebastian Redl22653ba2011-08-30 19:58:05 +000010432 // C++ [except.spec]p14:
10433 // An implicitly declared special member function (Clause 12) shall have an
10434 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000010435 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010436 if (ClassDecl->isInvalidDecl())
10437 return ExceptSpec;
10438
10439 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000010440 for (const auto &B : ClassDecl->bases()) {
10441 if (B.isVirtual()) // Handled below.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010442 continue;
10443
Aaron Ballman574705e2014-03-13 15:41:46 +000010444 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010445 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010446 CXXConstructorDecl *Constructor =
10447 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010448 // If this is a deleted function, add it anyway. This might be conformant
10449 // with the standard. This might not. I'm not sure. It might not matter.
10450 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +000010451 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010452 }
10453 }
10454
10455 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000010456 for (const auto &B : ClassDecl->vbases()) {
10457 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010458 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010459 CXXConstructorDecl *Constructor =
10460 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010461 // If this is a deleted function, add it anyway. This might be conformant
10462 // with the standard. This might not. I'm not sure. It might not matter.
10463 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000010464 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010465 }
10466 }
10467
10468 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010469 for (const auto *F : ClassDecl->fields()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010470 QualType FieldType = Context.getBaseElementType(F->getType());
10471 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10472 CXXConstructorDecl *Constructor =
10473 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010474 // If this is a deleted function, add it anyway. This might be conformant
10475 // with the standard. This might not. I'm not sure. It might not matter.
10476 // In particular, the problem is that this function never gets called. It
10477 // might just be ill-formed because this function attempts to refer to
10478 // a deleted function here.
10479 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010480 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010481 }
10482 }
10483
10484 return ExceptSpec;
10485}
10486
10487CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10488 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010489 assert(ClassDecl->needsImplicitMoveConstructor());
10490
Richard Smith8bf22e52012-11-29 01:34:07 +000010491 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10492 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010493 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010494
Sebastian Redl22653ba2011-08-30 19:58:05 +000010495 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10496 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010497
Richard Smithb5800092012-06-10 05:43:50 +000010498 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10499 CXXMoveConstructor,
10500 false);
10501
Sebastian Redl22653ba2011-08-30 19:58:05 +000010502 DeclarationName Name
10503 = Context.DeclarationNames.getCXXConstructorName(
10504 Context.getCanonicalType(ClassType));
10505 SourceLocation ClassLoc = ClassDecl->getLocation();
10506 DeclarationNameInfo NameInfo(Name, ClassLoc);
10507
Richard Smith99005e62013-05-07 03:19:20 +000010508 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000010509 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010510 // member of its class.
10511 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010512 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000010513 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010514 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010515 MoveConstructor->setAccess(AS_public);
10516 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010517
Richard Smithd3b5c9082012-07-27 04:22:15 +000010518 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010519 FunctionProtoType::ExtProtoInfo EPI =
10520 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010521 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010522 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010523
Sebastian Redl22653ba2011-08-30 19:58:05 +000010524 // Add the parameter to the constructor.
10525 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10526 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010527 /*IdentifierInfo=*/nullptr,
10528 ArgType, /*TInfo=*/nullptr,
10529 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010530 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010531
Richard Smith6b02d462012-12-08 08:32:28 +000010532 MoveConstructor->setTrivial(
10533 ClassDecl->needsOverloadResolutionForMoveConstructor()
10534 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10535 : ClassDecl->hasTrivialMoveConstructor());
10536
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000010537 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010538 ClassDecl->setImplicitMoveConstructorIsDeleted();
10539 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010540 }
10541
10542 // Note that we have declared this constructor.
10543 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10544
10545 if (Scope *S = getScopeForContext(ClassDecl))
10546 PushOnScopeChains(MoveConstructor, S, false);
10547 ClassDecl->addDecl(MoveConstructor);
10548
10549 return MoveConstructor;
10550}
10551
10552void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10553 CXXConstructorDecl *MoveConstructor) {
10554 assert((MoveConstructor->isDefaulted() &&
10555 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010556 !MoveConstructor->doesThisDeclarationHaveABody() &&
10557 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010558 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10559
10560 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10561 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10562
Eli Friedmaneaf34142012-10-18 20:14:08 +000010563 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010564 DiagnosticErrorTrap Trap(Diags);
10565
David Blaikie3fc2f912013-01-17 05:26:25 +000010566 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000010567 Trap.hasErrorOccurred()) {
10568 Diag(CurrentLocation, diag::note_member_synthesized_at)
10569 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10570 MoveConstructor->setInvalidDecl();
10571 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010572 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
10573 ? MoveConstructor->getLocEnd()
10574 : MoveConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010575 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010576 MoveConstructor->setBody(ActOnCompoundStmt(
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010577 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010578 }
10579
Eli Friedman276dd182013-09-05 00:02:25 +000010580 MoveConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000010581 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010582
10583 if (ASTMutationListener *L = getASTMutationListener()) {
10584 L->CompletedImplicitDefinition(MoveConstructor);
10585 }
10586}
10587
Douglas Gregor74f7d502012-02-15 19:33:52 +000010588bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000010589 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000010590}
Douglas Gregord3b672c2012-02-16 01:06:16 +000010591
10592void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000010593 SourceLocation CurrentLocation,
10594 CXXConversionDecl *Conv) {
10595 CXXRecordDecl *Lambda = Conv->getParent();
10596 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10597 // If we are defining a specialization of a conversion to function-ptr
10598 // cache the deduced template arguments for this specialization
10599 // so that we can use them to retrieve the corresponding call-operator
10600 // and static-invoker.
Craig Topperc3ec1492014-05-26 06:22:03 +000010601 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
10602
Faisal Vali571df122013-09-29 08:45:24 +000010603 // Retrieve the corresponding call-operator specialization.
10604 if (Lambda->isGenericLambda()) {
10605 assert(Conv->isFunctionTemplateSpecialization());
10606 FunctionTemplateDecl *CallOpTemplate =
10607 CallOp->getDescribedFunctionTemplate();
10608 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
Craig Topperc3ec1492014-05-26 06:22:03 +000010609 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000010610 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000010611 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000010612 InsertPos);
10613 assert(CallOpSpec &&
10614 "Conversion operator must have a corresponding call operator");
10615 CallOp = cast<CXXMethodDecl>(CallOpSpec);
10616 }
10617 // Mark the call operator referenced (and add to pending instantiations
10618 // if necessary).
10619 // For both the conversion and static-invoker template specializations
10620 // we construct their body's in this function, so no need to add them
10621 // to the PendingInstantiations.
10622 MarkFunctionReferenced(CurrentLocation, CallOp);
10623
Eli Friedmaneaf34142012-10-18 20:14:08 +000010624 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010625 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000010626
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010627 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000010628 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10629 // ... and get the corresponding specialization for a generic lambda.
10630 if (Lambda->isGenericLambda()) {
10631 assert(DeducedTemplateArgs &&
10632 "Must have deduced template arguments from Conversion Operator");
10633 FunctionTemplateDecl *InvokeTemplate =
10634 Invoker->getDescribedFunctionTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +000010635 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000010636 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000010637 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000010638 InsertPos);
10639 assert(InvokeSpec &&
10640 "Must have a corresponding static invoker specialization");
10641 Invoker = cast<CXXMethodDecl>(InvokeSpec);
10642 }
10643 // Construct the body of the conversion function { return __invoke; }.
10644 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010645 VK_LValue, Conv->getLocation()).get();
Faisal Vali571df122013-09-29 08:45:24 +000010646 assert(FunctionRef && "Can't refer to __invoke function?");
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010647 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
Faisal Vali571df122013-09-29 08:45:24 +000010648 Conv->setBody(new (Context) CompoundStmt(Context, Return,
10649 Conv->getLocation(),
10650 Conv->getLocation()));
10651
10652 Conv->markUsed(Context);
10653 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010654
Faisal Vali571df122013-09-29 08:45:24 +000010655 // Fill in the __invoke function with a dummy implementation. IR generation
10656 // will fill in the actual details.
10657 Invoker->markUsed(Context);
10658 Invoker->setReferenced();
10659 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10660
Douglas Gregord3b672c2012-02-16 01:06:16 +000010661 if (ASTMutationListener *L = getASTMutationListener()) {
10662 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000010663 L->CompletedImplicitDefinition(Invoker);
10664 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000010665}
10666
Faisal Vali571df122013-09-29 08:45:24 +000010667
10668
Douglas Gregord3b672c2012-02-16 01:06:16 +000010669void Sema::DefineImplicitLambdaToBlockPointerConversion(
10670 SourceLocation CurrentLocation,
10671 CXXConversionDecl *Conv)
10672{
Faisal Vali850da1a2013-09-29 17:08:32 +000010673 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000010674
Eli Friedman276dd182013-09-05 00:02:25 +000010675 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010676
Eli Friedmaneaf34142012-10-18 20:14:08 +000010677 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010678 DiagnosticErrorTrap Trap(Diags);
10679
Douglas Gregored90df32012-02-22 05:02:47 +000010680 // Copy-initialize the lambda object as needed to capture it.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010681 Expr *This = ActOnCXXThis(CurrentLocation).get();
10682 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010683
Eli Friedman98b01ed2012-03-01 04:01:32 +000010684 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10685 Conv->getLocation(),
10686 Conv, DerefThis);
10687
10688 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10689 // behavior. Note that only the general conversion function does this
10690 // (since it's unusable otherwise); in the case where we inline the
10691 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010692 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000010693 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10694 CK_CopyAndAutoreleaseBlockObject,
Craig Topperc3ec1492014-05-26 06:22:03 +000010695 BuildBlock.get(), nullptr, VK_RValue);
Eli Friedman98b01ed2012-03-01 04:01:32 +000010696
10697 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000010698 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000010699 Conv->setInvalidDecl();
10700 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000010701 }
Douglas Gregored90df32012-02-22 05:02:47 +000010702
Douglas Gregored90df32012-02-22 05:02:47 +000010703 // Create the return statement that returns the block from the conversion
10704 // function.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010705 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000010706 if (Return.isInvalid()) {
10707 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10708 Conv->setInvalidDecl();
10709 return;
10710 }
10711
10712 // Set the body of the conversion function.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010713 Stmt *ReturnS = Return.get();
Nico Webera2a0eb92012-12-29 20:03:39 +000010714 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000010715 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000010716 Conv->getLocation()));
10717
Douglas Gregored90df32012-02-22 05:02:47 +000010718 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000010719 if (ASTMutationListener *L = getASTMutationListener()) {
10720 L->CompletedImplicitDefinition(Conv);
10721 }
10722}
10723
Douglas Gregord2f70072012-03-10 06:53:13 +000010724/// \brief Determine whether the given list arguments contains exactly one
10725/// "real" (non-default) argument.
10726static bool hasOneRealArgument(MultiExprArg Args) {
10727 switch (Args.size()) {
10728 case 0:
10729 return false;
10730
10731 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010732 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000010733 return false;
10734
10735 // fall through
10736 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010737 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000010738 }
10739
10740 return false;
10741}
10742
John McCalldadc5752010-08-24 06:29:42 +000010743ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010744Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +000010745 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010746 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010747 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010748 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000010749 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010750 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010751 unsigned ConstructKind,
10752 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000010753 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000010754
Douglas Gregor45cf7e32010-04-02 18:24:57 +000010755 // C++0x [class.copy]p34:
10756 // When certain criteria are met, an implementation is allowed to
10757 // omit the copy/move construction of a class object, even if the
10758 // copy/move constructor and/or destructor for the object have
10759 // side effects. [...]
10760 // - when a temporary class object that has not been bound to a
10761 // reference (12.2) would be copied/moved to a class object
10762 // with the same cv-unqualified type, the copy/move operation
10763 // can be omitted by constructing the temporary object
10764 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +000010765 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregord2f70072012-03-10 06:53:13 +000010766 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010767 Expr *SubExpr = ExprArgs[0];
John McCall7a626f62010-09-15 10:14:12 +000010768 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +000010769 }
Mike Stump11289f42009-09-09 15:08:12 +000010770
10771 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010772 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithf8adcdc2014-07-17 05:12:35 +000010773 IsListInitialization,
10774 IsStdInitListInitialization, RequiresZeroInit,
Richard Smithd59b8322012-12-19 01:39:02 +000010775 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000010776}
10777
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010778/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10779/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +000010780ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000010781Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10782 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000010783 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010784 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000010785 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000010786 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010787 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000010788 unsigned ConstructKind,
10789 SourceRange ParenRange) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010790 MarkFunctionReferenced(ConstructLoc, Constructor);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010791 return CXXConstructExpr::Create(
10792 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
Richard Smithf8adcdc2014-07-17 05:12:35 +000010793 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
10794 RequiresZeroInit,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010795 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10796 ParenRange);
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000010797}
10798
John McCall03c48482010-02-02 09:10:11 +000010799void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000010800 if (VD->isInvalidDecl()) return;
10801
John McCall03c48482010-02-02 09:10:11 +000010802 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000010803 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000010804 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000010805 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000010806
Chandler Carruth86d17d32011-03-27 21:26:48 +000010807 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010808 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000010809 CheckDestructorAccess(VD->getLocation(), Destructor,
10810 PDiag(diag::err_access_dtor_var)
10811 << VD->getDeclName()
10812 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000010813 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000010814
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000010815 if (Destructor->isTrivial()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000010816 if (!VD->hasGlobalStorage()) return;
10817
10818 // Emit warning for non-trivial dtor in global scope (a real global,
10819 // class-static, function-static).
10820 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10821
10822 // TODO: this should be re-enabled for static locals by !CXAAtExit
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000010823 if (!VD->isStaticLocal())
Chandler Carruth86d17d32011-03-27 21:26:48 +000010824 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010825}
10826
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010827/// \brief Given a constructor and the set of arguments provided for the
10828/// constructor, convert the arguments and add any required default arguments
10829/// to form a proper call to this constructor.
10830///
10831/// \returns true if an error occurred, false otherwise.
10832bool
10833Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10834 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000010835 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000010836 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010837 bool AllowExplicit,
10838 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010839 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10840 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000010841 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010842
10843 const FunctionProtoType *Proto
10844 = Constructor->getType()->getAs<FunctionProtoType>();
10845 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010846 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000010847
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010848 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000010849 if (NumArgs < NumParams)
10850 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010851 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000010852 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010853
10854 VariadicCallType CallType =
10855 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010856 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010857 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010858 Proto, 0,
10859 llvm::makeArrayRef(Args, NumArgs),
10860 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000010861 CallType, AllowExplicit,
10862 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000010863 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000010864
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010865 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010866
Dmitri Gribenko765396f2013-01-13 20:46:02 +000010867 CheckConstructorCall(Constructor,
10868 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10869 AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000010870 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000010871
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000010872 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000010873}
10874
Anders Carlssone363c8e2009-12-12 00:32:00 +000010875static inline bool
10876CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10877 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000010878 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000010879 if (isa<NamespaceDecl>(DC)) {
10880 return SemaRef.Diag(FnDecl->getLocation(),
10881 diag::err_operator_new_delete_declared_in_namespace)
10882 << FnDecl->getDeclName();
10883 }
10884
10885 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000010886 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010887 return SemaRef.Diag(FnDecl->getLocation(),
10888 diag::err_operator_new_delete_declared_static)
10889 << FnDecl->getDeclName();
10890 }
10891
Anders Carlsson60659a82009-12-12 02:43:16 +000010892 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000010893}
10894
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010895static inline bool
10896CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10897 CanQualType ExpectedResultType,
10898 CanQualType ExpectedFirstParamType,
10899 unsigned DependentParamTypeDiag,
10900 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000010901 QualType ResultType =
10902 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010903
10904 // Check that the result type is not dependent.
10905 if (ResultType->isDependentType())
10906 return SemaRef.Diag(FnDecl->getLocation(),
10907 diag::err_operator_new_delete_dependent_result_type)
10908 << FnDecl->getDeclName() << ExpectedResultType;
10909
10910 // Check that the result type is what we expect.
10911 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10912 return SemaRef.Diag(FnDecl->getLocation(),
10913 diag::err_operator_new_delete_invalid_result_type)
10914 << FnDecl->getDeclName() << ExpectedResultType;
10915
10916 // A function template must have at least 2 parameters.
10917 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10918 return SemaRef.Diag(FnDecl->getLocation(),
10919 diag::err_operator_new_delete_template_too_few_parameters)
10920 << FnDecl->getDeclName();
10921
10922 // The function decl must have at least 1 parameter.
10923 if (FnDecl->getNumParams() == 0)
10924 return SemaRef.Diag(FnDecl->getLocation(),
10925 diag::err_operator_new_delete_too_few_parameters)
10926 << FnDecl->getDeclName();
10927
Sylvestre Ledru830885c2012-07-23 08:59:39 +000010928 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010929 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10930 if (FirstParamType->isDependentType())
10931 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10932 << FnDecl->getDeclName() << ExpectedFirstParamType;
10933
10934 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000010935 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010936 ExpectedFirstParamType)
10937 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10938 << FnDecl->getDeclName() << ExpectedFirstParamType;
10939
10940 return false;
10941}
10942
Anders Carlsson12308f42009-12-11 23:23:22 +000010943static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010944CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000010945 // C++ [basic.stc.dynamic.allocation]p1:
10946 // A program is ill-formed if an allocation function is declared in a
10947 // namespace scope other than global scope or declared static in global
10948 // scope.
10949 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10950 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010951
10952 CanQualType SizeTy =
10953 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10954
10955 // C++ [basic.stc.dynamic.allocation]p1:
10956 // The return type shall be void*. The first parameter shall have type
10957 // std::size_t.
10958 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10959 SizeTy,
10960 diag::err_operator_new_dependent_param_type,
10961 diag::err_operator_new_param_type))
10962 return true;
10963
10964 // C++ [basic.stc.dynamic.allocation]p1:
10965 // The first parameter shall not have an associated default argument.
10966 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000010967 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010968 diag::err_operator_new_default_arg)
10969 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10970
10971 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000010972}
10973
10974static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000010975CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000010976 // C++ [basic.stc.dynamic.deallocation]p1:
10977 // A program is ill-formed if deallocation functions are declared in a
10978 // namespace scope other than global scope or declared static in global
10979 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000010980 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10981 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010982
10983 // C++ [basic.stc.dynamic.deallocation]p2:
10984 // Each deallocation function shall return void and its first parameter
10985 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000010986 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10987 SemaRef.Context.VoidPtrTy,
10988 diag::err_operator_delete_dependent_param_type,
10989 diag::err_operator_delete_param_type))
10990 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000010991
Anders Carlsson12308f42009-12-11 23:23:22 +000010992 return false;
10993}
10994
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000010995/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10996/// of this overloaded operator is well-formed. If so, returns false;
10997/// otherwise, emits appropriate diagnostics and returns true.
10998bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000010999 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011000 "Expected an overloaded operator declaration");
11001
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011002 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11003
Mike Stump11289f42009-09-09 15:08:12 +000011004 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011005 // The allocation and deallocation functions, operator new,
11006 // operator new[], operator delete and operator delete[], are
11007 // described completely in 3.7.3. The attributes and restrictions
11008 // found in the rest of this subclause do not apply to them unless
11009 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000011010 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000011011 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000011012
Anders Carlsson22f443f2009-12-12 00:26:23 +000011013 if (Op == OO_New || Op == OO_Array_New)
11014 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011015
11016 // C++ [over.oper]p6:
11017 // An operator function shall either be a non-static member
11018 // function or be a non-member function and have at least one
11019 // parameter whose type is a class, a reference to a class, an
11020 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000011021 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11022 if (MethodDecl->isStatic())
11023 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011024 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011025 } else {
11026 bool ClassOrEnumParam = false;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011027 for (auto Param : FnDecl->params()) {
11028 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000011029 if (ParamType->isDependentType() || ParamType->isRecordType() ||
11030 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011031 ClassOrEnumParam = true;
11032 break;
11033 }
11034 }
11035
Douglas Gregord69246b2008-11-17 16:14:12 +000011036 if (!ClassOrEnumParam)
11037 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011038 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011039 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011040 }
11041
11042 // C++ [over.oper]p8:
11043 // An operator function cannot have default arguments (8.3.6),
11044 // except where explicitly stated below.
11045 //
Mike Stump11289f42009-09-09 15:08:12 +000011046 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011047 // (C++ [over.call]p1).
11048 if (Op != OO_Call) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011049 for (auto Param : FnDecl->params()) {
11050 if (Param->hasDefaultArg())
11051 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000011052 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011053 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011054 }
11055 }
11056
Douglas Gregor6cf08062008-11-10 13:38:07 +000011057 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11058 { false, false, false }
11059#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11060 , { Unary, Binary, MemberOnly }
11061#include "clang/Basic/OperatorKinds.def"
11062 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011063
Douglas Gregor6cf08062008-11-10 13:38:07 +000011064 bool CanBeUnaryOperator = OperatorUses[Op][0];
11065 bool CanBeBinaryOperator = OperatorUses[Op][1];
11066 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011067
11068 // C++ [over.oper]p8:
11069 // [...] Operator functions cannot have more or fewer parameters
11070 // than the number required for the corresponding operator, as
11071 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000011072 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000011073 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011074 if (Op != OO_Call &&
11075 ((NumParams == 1 && !CanBeUnaryOperator) ||
11076 (NumParams == 2 && !CanBeBinaryOperator) ||
11077 (NumParams < 1) || (NumParams > 2))) {
11078 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011079 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000011080 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011081 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000011082 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011083 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011084 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000011085 assert(CanBeBinaryOperator &&
11086 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011087 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011088 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011089
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011090 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011091 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011092 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000011093
Douglas Gregord69246b2008-11-17 16:14:12 +000011094 // Overloaded operators other than operator() cannot be variadic.
11095 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000011096 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000011097 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011098 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011099 }
11100
11101 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000011102 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11103 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011104 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011105 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011106 }
11107
11108 // C++ [over.inc]p1:
11109 // The user-defined function called operator++ implements the
11110 // prefix and postfix ++ operator. If this function is a member
11111 // function with no parameters, or a non-member function with one
11112 // parameter of class or enumeration type, it defines the prefix
11113 // increment operator ++ for objects of that type. If the function
11114 // is a member function with one parameter (which shall be of type
11115 // int) or a non-member function with two parameters (the second
11116 // of which shall be of type int), it defines the postfix
11117 // increment operator ++ for objects of that type.
11118 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11119 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000011120 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011121
Richard Smith538b52a2014-01-30 22:24:05 +000011122 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11123 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000011124 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000011125 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000011126 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011127 }
11128
Douglas Gregord69246b2008-11-17 16:14:12 +000011129 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011130}
Chris Lattner3b024a32008-12-17 07:09:26 +000011131
Alexis Huntc88db062010-01-13 09:01:02 +000011132/// CheckLiteralOperatorDeclaration - Check whether the declaration
11133/// of this literal operator function is well-formed. If so, returns
11134/// false; otherwise, emits appropriate diagnostics and returns true.
11135bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000011136 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000011137 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11138 << FnDecl->getDeclName();
11139 return true;
11140 }
11141
Richard Smith72eebee2012-03-04 09:41:16 +000011142 if (FnDecl->isExternC()) {
11143 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11144 return true;
11145 }
11146
Alexis Huntc88db062010-01-13 09:01:02 +000011147 bool Valid = false;
11148
Richard Smithbcc22fc2012-03-09 08:00:36 +000011149 // This might be the definition of a literal operator template.
11150 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11151 // This might be a specialization of a literal operator template.
11152 if (!TpDecl)
11153 TpDecl = FnDecl->getPrimaryTemplate();
11154
Richard Smithb8b41d32013-10-07 19:57:58 +000011155 // template <char...> type operator "" name() and
11156 // template <class T, T...> type operator "" name() are the only valid
11157 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000011158 if (TpDecl) {
Richard Smith72eebee2012-03-04 09:41:16 +000011159 if (FnDecl->param_size() == 0) {
Richard Smithb8b41d32013-10-07 19:57:58 +000011160 // Must have one or two template parameters
Alexis Hunt7dd26172010-04-07 23:11:06 +000011161 TemplateParameterList *Params = TpDecl->getTemplateParameters();
11162 if (Params->size() == 1) {
11163 NonTypeTemplateParmDecl *PmDecl =
Richard Smithed943022012-08-03 21:14:57 +000011164 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +000011165
Alexis Hunt7dd26172010-04-07 23:11:06 +000011166 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +000011167 if (PmDecl && PmDecl->isTemplateParameterPack() &&
11168 Context.hasSameType(PmDecl->getType(), Context.CharTy))
11169 Valid = true;
Richard Smithb8b41d32013-10-07 19:57:58 +000011170 } else if (Params->size() == 2) {
11171 TemplateTypeParmDecl *PmType =
11172 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11173 NonTypeTemplateParmDecl *PmArgs =
11174 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11175
11176 // The second template parameter must be a parameter pack with the
11177 // first template parameter as its type.
11178 if (PmType && PmArgs &&
11179 !PmType->isTemplateParameterPack() &&
11180 PmArgs->isTemplateParameterPack()) {
11181 const TemplateTypeParmType *TArgs =
11182 PmArgs->getType()->getAs<TemplateTypeParmType>();
11183 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11184 TArgs->getIndex() == PmType->getIndex()) {
11185 Valid = true;
11186 if (ActiveTemplateInstantiations.empty())
11187 Diag(FnDecl->getLocation(),
11188 diag::ext_string_literal_operator_template);
11189 }
11190 }
Alexis Hunt7dd26172010-04-07 23:11:06 +000011191 }
11192 }
Richard Smith72eebee2012-03-04 09:41:16 +000011193 } else if (FnDecl->param_size()) {
Alexis Huntc88db062010-01-13 09:01:02 +000011194 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +000011195 FunctionDecl::param_iterator Param = FnDecl->param_begin();
11196
Richard Smith72eebee2012-03-04 09:41:16 +000011197 QualType T = (*Param)->getType().getUnqualifiedType();
Alexis Huntc88db062010-01-13 09:01:02 +000011198
Alexis Hunt079a6f72010-04-07 22:57:35 +000011199 // unsigned long long int, long double, and any character type are allowed
11200 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +000011201 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11202 Context.hasSameType(T, Context.LongDoubleTy) ||
11203 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011204 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011205 Context.hasSameType(T, Context.Char16Ty) ||
11206 Context.hasSameType(T, Context.Char32Ty)) {
11207 if (++Param == FnDecl->param_end())
11208 Valid = true;
11209 goto FinishedParams;
11210 }
11211
Alexis Hunt079a6f72010-04-07 22:57:35 +000011212 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +000011213 const PointerType *PT = T->getAs<PointerType>();
11214 if (!PT)
11215 goto FinishedParams;
11216 T = PT->getPointeeType();
Richard Smith72eebee2012-03-04 09:41:16 +000011217 if (!T.isConstQualified() || T.isVolatileQualified())
Alexis Huntc88db062010-01-13 09:01:02 +000011218 goto FinishedParams;
11219 T = T.getUnqualifiedType();
11220
11221 // Move on to the second parameter;
11222 ++Param;
11223
11224 // If there is no second parameter, the first must be a const char *
11225 if (Param == FnDecl->param_end()) {
11226 if (Context.hasSameType(T, Context.CharTy))
11227 Valid = true;
11228 goto FinishedParams;
11229 }
11230
11231 // const char *, const wchar_t*, const char16_t*, and const char32_t*
11232 // are allowed as the first parameter to a two-parameter function
11233 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011234 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011235 Context.hasSameType(T, Context.Char16Ty) ||
11236 Context.hasSameType(T, Context.Char32Ty)))
11237 goto FinishedParams;
11238
11239 // The second and final parameter must be an std::size_t
11240 T = (*Param)->getType().getUnqualifiedType();
11241 if (Context.hasSameType(T, Context.getSizeType()) &&
11242 ++Param == FnDecl->param_end())
11243 Valid = true;
11244 }
11245
11246 // FIXME: This diagnostic is absolutely terrible.
11247FinishedParams:
11248 if (!Valid) {
11249 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11250 << FnDecl->getDeclName();
11251 return true;
11252 }
11253
Richard Smith768cecc2012-03-09 08:16:22 +000011254 // A parameter-declaration-clause containing a default argument is not
11255 // equivalent to any of the permitted forms.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011256 for (auto Param : FnDecl->params()) {
11257 if (Param->hasDefaultArg()) {
11258 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000011259 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011260 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000011261 break;
11262 }
11263 }
11264
Richard Smith0df56f42012-03-08 02:39:21 +000011265 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000011266 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11267 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000011268 // C++11 [usrlit.suffix]p1:
11269 // Literal suffix identifiers that do not start with an underscore
11270 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000011271 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11272 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000011273 }
Richard Smith0df56f42012-03-08 02:39:21 +000011274
Alexis Huntc88db062010-01-13 09:01:02 +000011275 return false;
11276}
11277
Douglas Gregor07665a62009-01-05 19:45:36 +000011278/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11279/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000011280/// the '{'. ExternLoc is the location of the 'extern', Lang is the
11281/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000011282/// the '{' brace. Otherwise, this linkage specification does not
11283/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000011284Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000011285 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000011286 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011287 StringLiteral *Lit = cast<StringLiteral>(LangStr);
11288 if (!Lit->isAscii()) {
11289 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11290 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011291 return nullptr;
Richard Smith4ee696d2014-02-17 23:25:27 +000011292 }
11293
11294 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000011295 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000011296 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000011297 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000011298 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000011299 Language = LinkageSpecDecl::lang_cxx;
11300 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000011301 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11302 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011303 return nullptr;
Chris Lattner438e5012008-12-17 07:13:27 +000011304 }
Mike Stump11289f42009-09-09 15:08:12 +000011305
Chris Lattner438e5012008-12-17 07:13:27 +000011306 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000011307
Richard Smith4ee696d2014-02-17 23:25:27 +000011308 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11309 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000011310 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011311 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000011312 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000011313 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000011314}
11315
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000011316/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000011317/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11318/// valid, it's the position of the closing '}' brace in a linkage
11319/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000011320Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011321 Decl *LinkageSpec,
11322 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011323 if (RBraceLoc.isValid()) {
11324 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11325 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011326 }
Richard Smith4ee696d2014-02-17 23:25:27 +000011327 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000011328 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000011329}
11330
Michael Han84324352013-02-22 17:15:32 +000011331Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11332 AttributeList *AttrList,
11333 SourceLocation SemiLoc) {
11334 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11335 // Attribute declarations appertain to empty declaration so we handle
11336 // them here.
11337 if (AttrList)
11338 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000011339
Michael Han84324352013-02-22 17:15:32 +000011340 CurContext->addDecl(ED);
11341 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000011342}
11343
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011344/// \brief Perform semantic analysis for the variable declaration that
11345/// occurs within a C++ catch clause, returning the newly-created
11346/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011347VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000011348 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011349 SourceLocation StartLoc,
11350 SourceLocation Loc,
11351 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011352 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011353 QualType ExDeclType = TInfo->getType();
11354
Sebastian Redl54c04d42008-12-22 19:15:10 +000011355 // Arrays and functions decay.
11356 if (ExDeclType->isArrayType())
11357 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11358 else if (ExDeclType->isFunctionType())
11359 ExDeclType = Context.getPointerType(ExDeclType);
11360
11361 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11362 // The exception-declaration shall not denote a pointer or reference to an
11363 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000011364 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000011365 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011366 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000011367 Invalid = true;
11368 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011369
Sebastian Redl54c04d42008-12-22 19:15:10 +000011370 QualType BaseType = ExDeclType;
11371 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000011372 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011373 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011374 BaseType = Ptr->getPointeeType();
11375 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011376 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000011377 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000011378 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011379 BaseType = Ref->getPointeeType();
11380 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011381 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011382 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000011383 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011384 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000011385 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011386
Mike Stump11289f42009-09-09 15:08:12 +000011387 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011388 RequireNonAbstractType(Loc, ExDeclType,
11389 diag::err_abstract_type_in_decl,
11390 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000011391 Invalid = true;
11392
John McCall2ca705e2010-07-24 00:37:23 +000011393 // Only the non-fragile NeXT runtime currently supports C++ catches
11394 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011395 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000011396 QualType T = ExDeclType;
11397 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11398 T = RT->getPointeeType();
11399
11400 if (T->isObjCObjectType()) {
11401 Diag(Loc, diag::err_objc_object_catch);
11402 Invalid = true;
11403 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000011404 // FIXME: should this be a test for macosx-fragile specifically?
11405 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000011406 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000011407 }
11408 }
11409
Abramo Bagnaradff19302011-03-08 08:55:46 +000011410 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000011411 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000011412 ExDecl->setExceptionVariable(true);
11413
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011414 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011415 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011416 Invalid = true;
11417
Douglas Gregor750734c2011-07-06 18:14:43 +000011418 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000011419 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000011420 // Insulate this from anything else we might currently be parsing.
11421 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11422
Douglas Gregor6de584c2010-03-05 23:38:39 +000011423 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000011424 // The object declared in an exception-declaration or, if the
11425 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000011426 // copy-initialized (8.5) from the exception object. [...]
11427 // The object is destroyed when the handler exits, after the destruction
11428 // of any automatic objects initialized within the handler.
11429 //
Nick Lewycky0f292892013-09-22 10:06:57 +000011430 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000011431 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +000011432 QualType initType = ExDeclType;
11433
11434 InitializedEntity entity =
11435 InitializedEntity::InitializeVariable(ExDecl);
11436 InitializationKind initKind =
11437 InitializationKind::CreateCopy(Loc, SourceLocation());
11438
11439 Expr *opaqueValue =
11440 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000011441 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11442 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000011443 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000011444 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000011445 else {
11446 // If the constructor used was non-trivial, set this as the
11447 // "initializer".
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011448 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000011449 if (!construct->getConstructor()->isTrivial()) {
11450 Expr *init = MaybeCreateExprWithCleanups(construct);
11451 ExDecl->setInit(init);
11452 }
11453
11454 // And make sure it's destructable.
11455 FinalizeVarWithDestructor(ExDecl, recordType);
11456 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000011457 }
11458 }
11459
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011460 if (Invalid)
11461 ExDecl->setInvalidDecl();
11462
11463 return ExDecl;
11464}
11465
11466/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11467/// handler.
John McCall48871652010-08-21 09:40:31 +000011468Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000011469 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000011470 bool Invalid = D.isInvalidType();
11471
11472 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000011473 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11474 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000011475 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11476 D.getIdentifierLoc());
11477 Invalid = true;
11478 }
11479
Sebastian Redl54c04d42008-12-22 19:15:10 +000011480 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011481 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000011482 LookupOrdinaryName,
11483 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011484 // The scope should be freshly made just for us. There is just no way
Aaron Ballman9ef622e2014-06-02 13:10:07 +000011485 // it contains any previous declaration, except for function parameters in
11486 // a function-try-block's catch statement.
John McCall48871652010-08-21 09:40:31 +000011487 assert(!S->isDeclScope(PrevDecl));
Aaron Ballman9ef622e2014-06-02 13:10:07 +000011488 if (isDeclInScope(PrevDecl, CurContext, S)) {
11489 Diag(D.getIdentifierLoc(), diag::err_redefinition)
11490 << D.getIdentifier();
11491 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11492 Invalid = true;
11493 } else if (PrevDecl->isTemplateParameter())
Sebastian Redl54c04d42008-12-22 19:15:10 +000011494 // Maybe we will complain about the shadowed template parameter.
11495 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011496 }
11497
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011498 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011499 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11500 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011501 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011502 }
11503
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011504 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011505 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011506 D.getIdentifierLoc(),
11507 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011508 if (Invalid)
11509 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000011510
Sebastian Redl54c04d42008-12-22 19:15:10 +000011511 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011512 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011513 PushOnScopeChains(ExDecl, S);
11514 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011515 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011516
Douglas Gregor758a8692009-06-17 21:51:59 +000011517 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000011518 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011519}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011520
Abramo Bagnaraea947882011-03-08 16:41:52 +000011521Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000011522 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000011523 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000011524 SourceLocation RParenLoc) {
Richard Smith085a64f2014-06-20 19:57:12 +000011525 StringLiteral *AssertMessage =
11526 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011527
Richard Smithded9c2e2012-07-11 22:37:56 +000011528 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
Craig Topperc3ec1492014-05-26 06:22:03 +000011529 return nullptr;
Richard Smithded9c2e2012-07-11 22:37:56 +000011530
11531 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11532 AssertMessage, RParenLoc, false);
11533}
11534
11535Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11536 Expr *AssertExpr,
11537 StringLiteral *AssertMessage,
11538 SourceLocation RParenLoc,
11539 bool Failed) {
Richard Smith085a64f2014-06-20 19:57:12 +000011540 assert(AssertExpr != nullptr && "Expected non-null condition");
Richard Smithded9c2e2012-07-11 22:37:56 +000011541 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11542 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000011543 // In a static_assert-declaration, the constant-expression shall be a
11544 // constant expression that can be contextually converted to bool.
11545 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11546 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011547 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000011548
Richard Smith902ca212011-12-14 23:32:26 +000011549 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000011550 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000011551 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000011552 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011553 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011554
Richard Smithded9c2e2012-07-11 22:37:56 +000011555 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011556 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000011557 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith085a64f2014-06-20 19:57:12 +000011558 if (AssertMessage)
11559 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000011560 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith085a64f2014-06-20 19:57:12 +000011561 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000011562 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000011563 }
Anders Carlsson54b26982009-03-14 00:33:21 +000011564 }
Mike Stump11289f42009-09-09 15:08:12 +000011565
Abramo Bagnaraea947882011-03-08 16:41:52 +000011566 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000011567 AssertExpr, AssertMessage, RParenLoc,
11568 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000011569
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011570 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000011571 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011572}
Sebastian Redlf769df52009-03-24 22:27:57 +000011573
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011574/// \brief Perform semantic analysis of the given friend type declaration.
11575///
11576/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000011577FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000011578 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011579 TypeSourceInfo *TSInfo) {
11580 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11581
11582 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000011583 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011584
Richard Smithc8239732011-10-18 21:39:00 +000011585 // C++03 [class.friend]p2:
11586 // An elaborated-type-specifier shall be used in a friend declaration
11587 // for a class.*
11588 //
11589 // * The class-key of the elaborated-type-specifier is required.
11590 if (!ActiveTemplateInstantiations.empty()) {
11591 // Do not complain about the form of friend template types during
11592 // template instantiation; we will already have complained when the
11593 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000011594 } else {
11595 if (!T->isElaboratedTypeSpecifier()) {
11596 // If we evaluated the type to a record type, suggest putting
11597 // a tag in front.
11598 if (const RecordType *RT = T->getAs<RecordType>()) {
11599 RecordDecl *RD = RT->getDecl();
Alp Tokera030cd02014-05-05 12:38:48 +000011600
11601 SmallString<16> InsertionText(" ");
11602 InsertionText += RD->getKindName();
11603
Nick Lewycky36722d22013-02-06 05:59:33 +000011604 Diag(TypeRange.getBegin(),
11605 getLangOpts().CPlusPlus11 ?
11606 diag::warn_cxx98_compat_unelaborated_friend_type :
11607 diag::ext_unelaborated_friend_type)
11608 << (unsigned) RD->getTagKind()
11609 << T
11610 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11611 InsertionText);
11612 } else {
11613 Diag(FriendLoc,
11614 getLangOpts().CPlusPlus11 ?
11615 diag::warn_cxx98_compat_nonclass_type_friend :
11616 diag::ext_nonclass_type_friend)
11617 << T
11618 << TypeRange;
11619 }
11620 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000011621 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011622 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000011623 diag::warn_cxx98_compat_enum_friend :
11624 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011625 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000011626 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011627 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011628
Nick Lewycky36722d22013-02-06 05:59:33 +000011629 // C++11 [class.friend]p3:
11630 // A friend declaration that does not declare a function shall have one
11631 // of the following forms:
11632 // friend elaborated-type-specifier ;
11633 // friend simple-type-specifier ;
11634 // friend typename-specifier ;
11635 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11636 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11637 }
Richard Smitha31a89a2012-09-20 01:31:00 +000011638
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011639 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000011640 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011641 // the friend declaration is ignored.
Nikola Smiljanic3a01af02014-05-23 12:48:27 +000011642 return FriendDecl::Create(Context, CurContext,
11643 TSInfo->getTypeLoc().getLocStart(), TSInfo,
11644 FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011645}
11646
John McCallace48cd2010-10-19 01:40:49 +000011647/// Handle a friend tag declaration where the scope specifier was
11648/// templated.
11649Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11650 unsigned TagSpec, SourceLocation TagLoc,
11651 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011652 IdentifierInfo *Name,
11653 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000011654 AttributeList *Attr,
11655 MultiTemplateParamsArg TempParamLists) {
11656 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11657
11658 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000011659 bool Invalid = false;
11660
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011661 if (TemplateParameterList *TemplateParams =
11662 MatchTemplateParametersToScopeSpecifier(
Craig Topperc3ec1492014-05-26 06:22:03 +000011663 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011664 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000011665 if (TemplateParams->size() > 0) {
11666 // This is a declaration of a class template.
11667 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +000011668 return nullptr;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000011669
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000011670 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
11671 NameLoc, Attr, TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000011672 /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000011673 FriendLoc, TempParamLists.size() - 1,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011674 TempParamLists.data()).get();
John McCallace48cd2010-10-19 01:40:49 +000011675 } else {
11676 // The "template<>" header is extraneous.
11677 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11678 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11679 isExplicitSpecialization = true;
11680 }
11681 }
11682
Craig Topperc3ec1492014-05-26 06:22:03 +000011683 if (Invalid) return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000011684
John McCallace48cd2010-10-19 01:40:49 +000011685 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000011686 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011687 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000011688 isAllExplicitSpecializations = false;
11689 break;
11690 }
11691 }
11692
11693 // FIXME: don't ignore attributes.
11694
11695 // If it's explicit specializations all the way down, just forget
11696 // about the template header and build an appropriate non-templated
11697 // friend. TODO: for source fidelity, remember the headers.
11698 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011699 if (SS.isEmpty()) {
11700 bool Owned = false;
11701 bool IsDependent = false;
11702 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000011703 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011704 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000011705 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000011706 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011707 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000011708 /*UnderlyingType=*/TypeResult(),
11709 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011710 }
Richard Smith649c7b062014-01-08 00:56:48 +000011711
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011712 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000011713 ElaboratedTypeKeyword Keyword
11714 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011715 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000011716 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011717 if (T.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +000011718 return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000011719
11720 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11721 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000011722 DependentNameTypeLoc TL =
11723 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011724 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011725 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000011726 TL.setNameLoc(NameLoc);
11727 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000011728 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011729 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000011730 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000011731 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000011732 }
11733
11734 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011735 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011736 Friend->setAccess(AS_public);
11737 CurContext->addDecl(Friend);
11738 return Friend;
11739 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000011740
11741 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11742
11743
John McCallace48cd2010-10-19 01:40:49 +000011744
11745 // Handle the case of a templated-scope friend class. e.g.
11746 // template <class T> class A<T>::B;
11747 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000011748 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
11749 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000011750 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11751 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11752 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000011753 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000011754 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000011755 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000011756 TL.setNameLoc(NameLoc);
11757
11758 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011759 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000011760 Friend->setAccess(AS_public);
11761 Friend->setUnsupportedFriend(true);
11762 CurContext->addDecl(Friend);
11763 return Friend;
11764}
11765
11766
John McCall11083da2009-09-16 22:47:08 +000011767/// Handle a friend type declaration. This works in tandem with
11768/// ActOnTag.
11769///
11770/// Notes on friend class templates:
11771///
11772/// We generally treat friend class declarations as if they were
11773/// declaring a class. So, for example, the elaborated type specifier
11774/// in a friend declaration is required to obey the restrictions of a
11775/// class-head (i.e. no typedefs in the scope chain), template
11776/// parameters are required to match up with simple template-ids, &c.
11777/// However, unlike when declaring a template specialization, it's
11778/// okay to refer to a template specialization without an empty
11779/// template parameter declaration, e.g.
11780/// friend class A<T>::B<unsigned>;
11781/// We permit this as a special case; if there are any template
11782/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000011783/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000011784Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000011785 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011786 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000011787
11788 assert(DS.isFriendSpecified());
11789 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11790
John McCall11083da2009-09-16 22:47:08 +000011791 // Try to convert the decl specifier to a type. This works for
11792 // friend templates because ActOnTag never produces a ClassTemplateDecl
11793 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000011794 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000011795 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11796 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000011797 if (TheDeclarator.isInvalidType())
Craig Topperc3ec1492014-05-26 06:22:03 +000011798 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000011799
Douglas Gregor6c110f32010-12-16 01:14:37 +000011800 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000011801 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000011802
John McCall11083da2009-09-16 22:47:08 +000011803 // This is definitely an error in C++98. It's probably meant to
11804 // be forbidden in C++0x, too, but the specification is just
11805 // poorly written.
11806 //
11807 // The problem is with declarations like the following:
11808 // template <T> friend A<T>::foo;
11809 // where deciding whether a class C is a friend or not now hinges
11810 // on whether there exists an instantiation of A that causes
11811 // 'foo' to equal C. There are restrictions on class-heads
11812 // (which we declare (by fiat) elaborated friend declarations to
11813 // be) that makes this tractable.
11814 //
11815 // FIXME: handle "template <> friend class A<T>;", which
11816 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000011817 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000011818 Diag(Loc, diag::err_tagless_friend_type_template)
11819 << DS.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011820 return nullptr;
John McCall11083da2009-09-16 22:47:08 +000011821 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011822
John McCallaa74a0c2009-08-28 07:59:38 +000011823 // C++98 [class.friend]p1: A friend of a class is a function
11824 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000011825 // This is fixed in DR77, which just barely didn't make the C++03
11826 // deadline. It's also a very silly restriction that seriously
11827 // affects inner classes and which nobody else seems to implement;
11828 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000011829 //
11830 // But note that we could warn about it: it's always useless to
11831 // friend one of your own members (it's not, however, worthless to
11832 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000011833
John McCall11083da2009-09-16 22:47:08 +000011834 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011835 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000011836 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011837 NumTempParamLists,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011838 TempParams.data(),
John McCall15ad0962010-03-25 18:04:51 +000011839 TSI,
John McCall11083da2009-09-16 22:47:08 +000011840 DS.getFriendSpecLoc());
11841 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000011842 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011843
11844 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +000011845 return nullptr;
11846
John McCall11083da2009-09-16 22:47:08 +000011847 D->setAccess(AS_public);
11848 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000011849
John McCall48871652010-08-21 09:40:31 +000011850 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000011851}
11852
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000011853NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11854 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000011855 const DeclSpec &DS = D.getDeclSpec();
11856
11857 assert(DS.isFriendSpecified());
11858 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11859
11860 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000011861 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000011862
11863 // C++ [class.friend]p1
11864 // A friend of a class is a function or class....
11865 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000011866 // It *doesn't* see through dependent types, which is correct
11867 // according to [temp.arg.type]p3:
11868 // If a declaration acquires a function type through a
11869 // type dependent on a template-parameter and this causes
11870 // a declaration that does not use the syntactic form of a
11871 // function declarator to have a function type, the program
11872 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000011873 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000011874 Diag(Loc, diag::err_unexpected_friend);
11875
11876 // It might be worthwhile to try to recover by creating an
11877 // appropriate declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000011878 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000011879 }
11880
11881 // C++ [namespace.memdef]p3
11882 // - If a friend declaration in a non-local class first declares a
11883 // class or function, the friend class or function is a member
11884 // of the innermost enclosing namespace.
11885 // - The name of the friend is not found by simple name lookup
11886 // until a matching declaration is provided in that namespace
11887 // scope (either before or after the class declaration granting
11888 // friendship).
11889 // - If a friend function is called, its name may be found by the
11890 // name lookup that considers functions from namespaces and
11891 // classes associated with the types of the function arguments.
11892 // - When looking for a prior declaration of a class or a function
11893 // declared as a friend, scopes outside the innermost enclosing
11894 // namespace scope are not considered.
11895
John McCallde3fd222010-10-12 23:13:28 +000011896 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011897 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11898 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000011899 assert(Name);
11900
Douglas Gregor6c110f32010-12-16 01:14:37 +000011901 // Check for unexpanded parameter packs.
11902 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11903 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11904 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000011905 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000011906
John McCall07e91c02009-08-06 02:15:43 +000011907 // The context we found the declaration in, or in which we should
11908 // create the declaration.
11909 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000011910 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011911 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000011912 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000011913
Richard Smith114394f2013-08-09 04:35:01 +000011914 // There are five cases here.
11915 // - There's no scope specifier and we're in a local class. Only look
11916 // for functions declared in the immediately-enclosing block scope.
11917 // We recover from invalid scope qualifiers as if they just weren't there.
Craig Topperc3ec1492014-05-26 06:22:03 +000011918 FunctionDecl *FunctionContainingLocalClass = nullptr;
Richard Smith114394f2013-08-09 04:35:01 +000011919 if ((SS.isInvalid() || !SS.isSet()) &&
11920 (FunctionContainingLocalClass =
11921 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11922 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000011923 // If a friend declaration appears in a local class and the name
11924 // specified is an unqualified name, a prior declaration is
11925 // looked up without considering scopes that are outside the
11926 // innermost enclosing non-class scope. For a friend function
11927 // declaration, if there is no prior declaration, the program is
11928 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000011929
11930 // Find the innermost enclosing non-class scope. This is the block
11931 // scope containing the local class definition (or for a nested class,
11932 // the outer local class).
11933 DCScope = S->getFnParent();
11934
11935 // Look up the function name in the scope.
11936 Previous.clear(LookupLocalFriendName);
11937 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11938
11939 if (!Previous.empty()) {
11940 // All possible previous declarations must have the same context:
11941 // either they were declared at block scope or they are members of
11942 // one of the enclosing local classes.
11943 DC = Previous.getRepresentativeDecl()->getDeclContext();
11944 } else {
11945 // This is ill-formed, but provide the context that we would have
11946 // declared the function in, if we were permitted to, for error recovery.
11947 DC = FunctionContainingLocalClass;
11948 }
Richard Smith541b38b2013-09-20 01:15:31 +000011949 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000011950
11951 // C++ [class.friend]p6:
11952 // A function can be defined in a friend declaration of a class if and
11953 // only if the class is a non-local class (9.8), the function name is
11954 // unqualified, and the function has namespace scope.
11955 if (D.isFunctionDefinition()) {
11956 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11957 }
11958
11959 // - There's no scope specifier, in which case we just go to the
11960 // appropriate scope and look for a function or function template
11961 // there as appropriate.
11962 } else if (SS.isInvalid() || !SS.isSet()) {
11963 // C++11 [namespace.memdef]p3:
11964 // If the name in a friend declaration is neither qualified nor
11965 // a template-id and the declaration is a function or an
11966 // elaborated-type-specifier, the lookup to determine whether
11967 // the entity has been previously declared shall not consider
11968 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000011969 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000011970
John McCallf7cfb222010-10-13 05:45:15 +000011971 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000011972 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000011973
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011974 // Skip class contexts. If someone can cite chapter and verse
11975 // for this behavior, that would be nice --- it's what GCC and
11976 // EDG do, and it seems like a reasonable intent, but the spec
11977 // really only says that checks for unqualified existing
11978 // declarations should stop at the nearest enclosing namespace,
11979 // not that they should only consider the nearest enclosing
11980 // namespace.
11981 while (DC->isRecord())
11982 DC = DC->getParent();
11983
11984 DeclContext *LookupDC = DC;
11985 while (LookupDC->isTransparentContext())
11986 LookupDC = LookupDC->getParent();
11987
11988 while (true) {
11989 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000011990
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011991 if (!Previous.empty()) {
11992 DC = LookupDC;
11993 break;
John McCallf4776592010-10-14 22:22:28 +000011994 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000011995
11996 if (isTemplateId) {
11997 if (isa<TranslationUnitDecl>(LookupDC)) break;
11998 } else {
11999 if (LookupDC->isFileContext()) break;
12000 }
12001 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000012002 }
12003
John McCallccbc0322010-10-13 06:22:15 +000012004 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000012005
John McCallde3fd222010-10-12 23:13:28 +000012006 // - There's a non-dependent scope specifier, in which case we
12007 // compute it and do a previous lookup there for a function
12008 // or function template.
12009 } else if (!SS.getScopeRep()->isDependent()) {
12010 DC = computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +000012011 if (!DC) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012012
Craig Topperc3ec1492014-05-26 06:22:03 +000012013 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012014
12015 LookupQualifiedName(Previous, DC);
12016
12017 // Ignore things found implicitly in the wrong scope.
12018 // TODO: better diagnostics for this case. Suggesting the right
12019 // qualified scope would be nice...
12020 LookupResult::Filter F = Previous.makeFilter();
12021 while (F.hasNext()) {
12022 NamedDecl *D = F.next();
12023 if (!DC->InEnclosingNamespaceSetOf(
12024 D->getDeclContext()->getRedeclContext()))
12025 F.erase();
12026 }
12027 F.done();
12028
12029 if (Previous.empty()) {
12030 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012031 Diag(Loc, diag::err_qualified_friend_not_found)
12032 << Name << TInfo->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +000012033 return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012034 }
12035
12036 // C++ [class.friend]p1: A friend of a class is a function or
12037 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000012038 if (DC->Equals(CurContext))
12039 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012040 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000012041 diag::warn_cxx98_compat_friend_is_member :
12042 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000012043
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012044 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012045 // C++ [class.friend]p6:
12046 // A function can be defined in a friend declaration of a class if and
12047 // only if the class is a non-local class (9.8), the function name is
12048 // unqualified, and the function has namespace scope.
12049 SemaDiagnosticBuilder DB
12050 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12051
12052 DB << SS.getScopeRep();
12053 if (DC->isFileContext())
12054 DB << FixItHint::CreateRemoval(SS.getRange());
12055 SS.clear();
12056 }
John McCallde3fd222010-10-12 23:13:28 +000012057
12058 // - There's a scope specifier that does not match any template
12059 // parameter lists, in which case we use some arbitrary context,
12060 // create a method or method template, and wait for instantiation.
12061 // - There's a scope specifier that does match some template
12062 // parameter lists, which we don't handle right now.
12063 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012064 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012065 // C++ [class.friend]p6:
12066 // A function can be defined in a friend declaration of a class if and
12067 // only if the class is a non-local class (9.8), the function name is
12068 // unqualified, and the function has namespace scope.
12069 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12070 << SS.getScopeRep();
12071 }
12072
John McCallde3fd222010-10-12 23:13:28 +000012073 DC = CurContext;
12074 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000012075 }
Douglas Gregor16e65612011-10-10 01:11:59 +000012076
John McCallf7cfb222010-10-13 05:45:15 +000012077 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000012078 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000012079 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
12080 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
12081 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000012082 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000012083 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
12084 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
Craig Topperc3ec1492014-05-26 06:22:03 +000012085 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012086 }
John McCall07e91c02009-08-06 02:15:43 +000012087 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012088
Douglas Gregordd847ba2011-11-03 16:37:14 +000012089 // FIXME: This is an egregious hack to cope with cases where the scope stack
12090 // does not contain the declaration context, i.e., in an out-of-line
12091 // definition of a class.
12092 Scope FakeDCScope(S, Scope::DeclScope, Diags);
12093 if (!DCScope) {
12094 FakeDCScope.setEntity(DC);
12095 DCScope = &FakeDCScope;
12096 }
Richard Smith114394f2013-08-09 04:35:01 +000012097
Francois Pichet00c7e6c2011-08-14 03:52:19 +000012098 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012099 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012100 TemplateParams, AddToScope);
Craig Topperc3ec1492014-05-26 06:22:03 +000012101 if (!ND) return nullptr;
John McCall759e32b2009-08-31 22:39:49 +000012102
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012103 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000012104
Richard Smith114394f2013-08-09 04:35:01 +000012105 // If we performed typo correction, we might have added a scope specifier
12106 // and changed the decl context.
12107 DC = ND->getDeclContext();
12108
John McCall759e32b2009-08-31 22:39:49 +000012109 // Add the function declaration to the appropriate lookup tables,
12110 // adjusting the redeclarations list as necessary. We don't
12111 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000012112 //
John McCall759e32b2009-08-31 22:39:49 +000012113 // Also update the scope-based lookup if the target context's
12114 // lookup context is in lexical scope.
12115 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000012116 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000012117 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000012118 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012119 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000012120 }
John McCallaa74a0c2009-08-28 07:59:38 +000012121
12122 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012123 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000012124 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000012125 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000012126 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000012127
John McCalla0a96892012-08-10 03:15:35 +000012128 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000012129 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000012130 } else {
12131 if (DC->isRecord()) CheckFriendAccess(ND);
12132
John McCall2c2eb122010-10-16 06:59:13 +000012133 FunctionDecl *FD;
12134 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12135 FD = FTD->getTemplatedDecl();
12136 else
12137 FD = cast<FunctionDecl>(ND);
12138
David Majnemer502b0ed2013-06-25 23:09:30 +000012139 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12140 // default argument expression, that declaration shall be a definition
12141 // and shall be the only declaration of the function or function
12142 // template in the translation unit.
12143 if (functionDeclHasDefaultArgument(FD)) {
12144 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12145 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12146 Diag(OldFD->getLocation(), diag::note_previous_declaration);
12147 } else if (!D.isFunctionDefinition())
12148 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12149 }
12150
John McCall2c2eb122010-10-16 06:59:13 +000012151 // Mark templated-scope function declarations as unsupported.
12152 if (FD->getNumTemplateParameterLists())
12153 FrD->setUnsupportedFriend(true);
12154 }
John McCallde3fd222010-10-12 23:13:28 +000012155
John McCall48871652010-08-21 09:40:31 +000012156 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000012157}
12158
John McCall48871652010-08-21 09:40:31 +000012159void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12160 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000012161
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012162 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000012163 if (!Fn) {
12164 Diag(DelLoc, diag::err_deleted_non_function);
12165 return;
12166 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012167
Douglas Gregorec9fd132012-01-14 16:38:05 +000012168 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000012169 // Don't consider the implicit declaration we generate for explicit
12170 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000012171 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12172 Prev->getPreviousDecl()) &&
12173 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000012174 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000012175 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12176 Prev->isImplicit() ? diag::note_previous_implicit_declaration
12177 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000012178 }
Sebastian Redlf769df52009-03-24 22:27:57 +000012179 // If the declaration wasn't the first, we delete the function anyway for
12180 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000012181 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000012182 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012183
Nico Rieck9de0a572014-05-29 16:51:19 +000012184 // dllimport/dllexport cannot be deleted.
12185 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12186 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12187 Fn->setInvalidDecl();
12188 }
12189
Richard Smithb4d2a152013-04-02 19:38:47 +000012190 if (Fn->isDeleted())
12191 return;
12192
12193 // See if we're deleting a function which is already known to override a
12194 // non-deleted virtual function.
12195 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12196 bool IssuedDiagnostic = false;
12197 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12198 E = MD->end_overridden_methods();
12199 I != E; ++I) {
12200 if (!(*MD->begin_overridden_methods())->isDeleted()) {
12201 if (!IssuedDiagnostic) {
12202 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12203 IssuedDiagnostic = true;
12204 }
12205 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12206 }
12207 }
12208 }
12209
Richard Smithb63b6ee2014-01-22 01:43:19 +000012210 // C++11 [basic.start.main]p3:
12211 // A program that defines main as deleted [...] is ill-formed.
12212 if (Fn->isMain())
12213 Diag(DelLoc, diag::err_deleted_main);
12214
Alexis Hunt4a8ea102011-05-06 20:44:56 +000012215 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000012216}
Sebastian Redl4c018662009-04-27 21:33:24 +000012217
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012218void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012219 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012220
12221 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000012222 if (MD->getParent()->isDependentType()) {
12223 MD->setDefaulted();
12224 MD->setExplicitlyDefaulted();
12225 return;
12226 }
12227
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012228 CXXSpecialMember Member = getSpecialMember(MD);
12229 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000012230 if (!MD->isInvalidDecl())
12231 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012232 return;
12233 }
12234
12235 MD->setDefaulted();
12236 MD->setExplicitlyDefaulted();
12237
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012238 // If this definition appears within the record, do the checking when
12239 // the record is complete.
12240 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000012241 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012242 // Find the uninstantiated declaration that actually had the '= default'
12243 // on it.
Richard Smith802c4b72012-08-23 06:16:52 +000012244 Pattern->isDefined(Primary);
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012245
Richard Smith3901dfe2013-03-27 00:22:47 +000012246 // If the method was defaulted on its first declaration, we will have
12247 // already performed the checking in CheckCompletedCXXClass. Such a
12248 // declaration doesn't trigger an implicit definition.
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012249 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012250 return;
12251
Richard Smithd3b5c9082012-07-27 04:22:15 +000012252 CheckExplicitlyDefaultedSpecialMember(MD);
12253
Richard Smithbd305122012-12-11 01:14:52 +000012254 // The exception specification is needed because we are defining the
12255 // function.
12256 ResolveExceptionSpec(DefaultLoc,
12257 MD->getType()->castAs<FunctionProtoType>());
12258
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012259 if (MD->isInvalidDecl())
12260 return;
12261
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012262 switch (Member) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012263 case CXXDefaultConstructor:
12264 DefineImplicitDefaultConstructor(DefaultLoc,
12265 cast<CXXConstructorDecl>(MD));
Alexis Hunt913820d2011-05-13 06:10:58 +000012266 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012267 case CXXCopyConstructor:
12268 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012269 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012270 case CXXCopyAssignment:
12271 DefineImplicitCopyAssignment(DefaultLoc, MD);
Alexis Huntc9a55732011-05-14 05:23:28 +000012272 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012273 case CXXDestructor:
12274 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Alexis Huntf91729462011-05-12 22:46:25 +000012275 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012276 case CXXMoveConstructor:
12277 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt119c10e2011-05-25 23:16:36 +000012278 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012279 case CXXMoveAssignment:
12280 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012281 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000012282 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000012283 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012284 }
12285 } else {
12286 Diag(DefaultLoc, diag::err_default_special_members);
12287 }
12288}
12289
Sebastian Redl4c018662009-04-27 21:33:24 +000012290static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000012291 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000012292 Stmt *SubStmt = *CI;
12293 if (!SubStmt)
12294 continue;
12295 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012296 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000012297 diag::err_return_in_constructor_handler);
12298 if (!isa<Expr>(SubStmt))
12299 SearchForReturnInStmt(Self, SubStmt);
12300 }
12301}
12302
12303void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12304 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12305 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12306 SearchForReturnInStmt(*this, Handler);
12307 }
12308}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012309
David Blaikie68f71a32013-01-18 23:03:15 +000012310bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000012311 const CXXMethodDecl *Old) {
12312 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12313 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12314
12315 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12316
12317 // If the calling conventions match, everything is fine
12318 if (NewCC == OldCC)
12319 return false;
12320
Hans Wennborg2545efe2013-12-11 17:42:11 +000012321 // If the calling conventions mismatch because the new function is static,
12322 // suppress the calling convention mismatch error; the error about static
12323 // function override (err_static_overrides_virtual from
12324 // Sema::CheckFunctionDeclaration) is more clear.
12325 if (New->getStorageClass() == SC_Static)
12326 return false;
12327
Reid Kleckner78af0702013-08-27 23:08:25 +000012328 Diag(New->getLocation(),
12329 diag::err_conflicting_overriding_cc_attributes)
12330 << New->getDeclName() << New->getType() << Old->getType();
12331 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12332 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000012333}
12334
Mike Stump11289f42009-09-09 15:08:12 +000012335bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012336 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000012337 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12338 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012339
Chandler Carruth284bb2e2010-02-15 11:53:20 +000012340 if (Context.hasSameType(NewTy, OldTy) ||
12341 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012342 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012343
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012344 // Check if the return types are covariant
12345 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000012346
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012347 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012348 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12349 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012350 NewClassTy = NewPT->getPointeeType();
12351 OldClassTy = OldPT->getPointeeType();
12352 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012353 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12354 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12355 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12356 NewClassTy = NewRT->getPointeeType();
12357 OldClassTy = OldRT->getPointeeType();
12358 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012359 }
12360 }
Mike Stump11289f42009-09-09 15:08:12 +000012361
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012362 // The return types aren't either both pointers or references to a class type.
12363 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000012364 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012365 diag::err_different_return_type_for_overriding_virtual_function)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012366 << New->getDeclName() << NewTy << OldTy
12367 << New->getReturnTypeSourceRange();
12368 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12369 << Old->getReturnTypeSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000012370
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012371 return true;
12372 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012373
Anders Carlssone60365b2009-12-31 18:34:24 +000012374 // C++ [class.virtual]p6:
12375 // If the return type of D::f differs from the return type of B::f, the
12376 // class type in the return type of D::f shall be complete at the point of
12377 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012378 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12379 if (!RT->isBeingDefined() &&
12380 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012381 diag::err_covariant_return_incomplete,
12382 New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000012383 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012384 }
Anders Carlssone60365b2009-12-31 18:34:24 +000012385
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000012386 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012387 // Check if the new class derives from the old class.
12388 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
Alp Tokerd0787eb2014-07-02 01:47:15 +000012389 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
12390 << New->getDeclName() << NewTy << OldTy
12391 << New->getReturnTypeSourceRange();
12392 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12393 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012394 return true;
12395 }
Mike Stump11289f42009-09-09 15:08:12 +000012396
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012397 // Check if we the conversion from derived to base is valid.
Alp Tokerd0787eb2014-07-02 01:47:15 +000012398 if (CheckDerivedToBaseConversion(
12399 NewClassTy, OldClassTy,
12400 diag::err_covariant_return_inaccessible_base,
12401 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12402 New->getLocation(), New->getReturnTypeSourceRange(),
12403 New->getDeclName(), nullptr)) {
John McCallc1465822011-02-14 07:13:47 +000012404 // FIXME: this note won't trigger for delayed access control
12405 // diagnostics, and it's impossible to get an undelayed error
12406 // here from access control during the original parse because
12407 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Alp Tokerd0787eb2014-07-02 01:47:15 +000012408 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12409 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012410 return true;
12411 }
12412 }
Mike Stump11289f42009-09-09 15:08:12 +000012413
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012414 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012415 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012416 Diag(New->getLocation(),
12417 diag::err_covariant_return_type_different_qualifications)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012418 << New->getDeclName() << NewTy << OldTy
12419 << New->getReturnTypeSourceRange();
12420 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12421 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012422 return true;
12423 };
Mike Stump11289f42009-09-09 15:08:12 +000012424
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012425
12426 // The new class type must have the same or less qualifiers as the old type.
12427 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12428 Diag(New->getLocation(),
12429 diag::err_covariant_return_type_class_type_more_qualified)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012430 << New->getDeclName() << NewTy << OldTy
12431 << New->getReturnTypeSourceRange();
12432 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12433 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012434 return true;
12435 };
Mike Stump11289f42009-09-09 15:08:12 +000012436
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012437 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012438}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012439
Douglas Gregor21920e372009-12-01 17:24:26 +000012440/// \brief Mark the given method pure.
12441///
12442/// \param Method the method to be marked pure.
12443///
12444/// \param InitRange the source range that covers the "0" initializer.
12445bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012446 SourceLocation EndLoc = InitRange.getEnd();
12447 if (EndLoc.isValid())
12448 Method->setRangeEnd(EndLoc);
12449
Douglas Gregor21920e372009-12-01 17:24:26 +000012450 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12451 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000012452 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012453 }
Douglas Gregor21920e372009-12-01 17:24:26 +000012454
12455 if (!Method->isInvalidDecl())
12456 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12457 << Method->getDeclName() << InitRange;
12458 return true;
12459}
12460
Douglas Gregor926410d2012-02-21 02:22:07 +000012461/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012462static bool isStaticDataMember(const Decl *D) {
12463 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12464 return Var->isStaticDataMember();
12465
12466 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000012467}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012468
John McCall1f4ee7b2009-12-19 09:28:58 +000012469/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12470/// an initializer for the out-of-line declaration 'Dcl'. The scope
12471/// is a fresh scope pushed for just this purpose.
12472///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012473/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12474/// static data member of class X, names should be looked up in the scope of
12475/// class X.
John McCall48871652010-08-21 09:40:31 +000012476void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012477 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000012478 if (!D || D->isInvalidDecl())
12479 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012480
Richard Smitha2302242013-12-05 07:51:02 +000012481 // We will always have a nested name specifier here, but this declaration
12482 // might not be out of line if the specifier names the current namespace:
12483 // extern int n;
12484 // int ::n = 0;
12485 if (D->isOutOfLine())
12486 EnterDeclaratorContext(S, D->getDeclContext());
12487
Douglas Gregor926410d2012-02-21 02:22:07 +000012488 // If we are parsing the initializer for a static data member, push a
12489 // new expression evaluation context that is associated with this static
12490 // data member.
12491 if (isStaticDataMember(D))
12492 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012493}
12494
12495/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000012496/// initializer for the out-of-line declaration 'D'.
12497void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012498 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000012499 if (!D || D->isInvalidDecl())
12500 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012501
Douglas Gregor926410d2012-02-21 02:22:07 +000012502 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000012503 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000012504
Richard Smitha2302242013-12-05 07:51:02 +000012505 if (D->isOutOfLine())
12506 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012507}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012508
12509/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12510/// C++ if/switch/while/for statement.
12511/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000012512DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012513 // C++ 6.4p2:
12514 // The declarator shall not specify a function or an array.
12515 // The type-specifier-seq shall not contain typedef and shall not declare a
12516 // new class or enumeration.
12517 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12518 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012519
12520 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012521 if (!Dcl)
12522 return true;
12523
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012524 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12525 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012526 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012527 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012528 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012529
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012530 return Dcl;
12531}
Anders Carlssonf98849e2009-12-02 17:15:43 +000012532
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012533void Sema::LoadExternalVTableUses() {
12534 if (!ExternalSource)
12535 return;
12536
12537 SmallVector<ExternalVTableUse, 4> VTables;
12538 ExternalSource->ReadUsedVTables(VTables);
12539 SmallVector<VTableUse, 4> NewUses;
12540 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12541 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12542 = VTablesUsed.find(VTables[I].Record);
12543 // Even if a definition wasn't required before, it may be required now.
12544 if (Pos != VTablesUsed.end()) {
12545 if (!Pos->second && VTables[I].DefinitionRequired)
12546 Pos->second = true;
12547 continue;
12548 }
12549
12550 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12551 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12552 }
12553
12554 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12555}
12556
Douglas Gregor88d292c2010-05-13 16:44:06 +000012557void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12558 bool DefinitionRequired) {
12559 // Ignore any vtable uses in unevaluated operands or for classes that do
12560 // not have a vtable.
12561 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000012562 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000012563 return;
12564
Douglas Gregor88d292c2010-05-13 16:44:06 +000012565 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012566 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012567 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12568 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12569 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12570 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000012571 // If we already had an entry, check to see if we are promoting this vtable
12572 // to required a definition. If so, we need to reappend to the VTableUses
12573 // list, since we may have already processed the first entry.
12574 if (DefinitionRequired && !Pos.first->second) {
12575 Pos.first->second = true;
12576 } else {
12577 // Otherwise, we can early exit.
12578 return;
12579 }
Hans Wennborg3d791542014-02-24 15:58:24 +000012580 } else {
12581 // The Microsoft ABI requires that we perform the destructor body
12582 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
12583 // the deleting destructor is emitted with the vtable, not with the
12584 // destructor definition as in the Itanium ABI.
12585 // If it has a definition, we do the check at that point instead.
12586 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12587 Class->hasUserDeclaredDestructor() &&
12588 !Class->getDestructor()->isDefined() &&
12589 !Class->getDestructor()->isDeleted()) {
Reid Kleckner67130862014-06-12 22:39:12 +000012590 CXXDestructorDecl *DD = Class->getDestructor();
12591 ContextRAII SavedContext(*this, DD);
12592 CheckDestructor(DD);
Hans Wennborg3d791542014-02-24 15:58:24 +000012593 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012594 }
12595
12596 // Local classes need to have their virtual members marked
12597 // immediately. For all other classes, we mark their virtual members
12598 // at the end of the translation unit.
12599 if (Class->isLocalClass())
12600 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000012601 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000012602 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000012603}
12604
Douglas Gregor88d292c2010-05-13 16:44:06 +000012605bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012606 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012607 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000012608 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000012609
Douglas Gregor88d292c2010-05-13 16:44:06 +000012610 // Note: The VTableUses vector could grow as a result of marking
12611 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000012612 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000012613 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000012614 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012615 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000012616 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012617 if (!Class)
12618 continue;
12619
12620 SourceLocation Loc = VTableUses[I].second;
12621
Richard Smithd3b5c9082012-07-27 04:22:15 +000012622 bool DefineVTable = true;
12623
Douglas Gregor88d292c2010-05-13 16:44:06 +000012624 // If this class has a key function, but that key function is
12625 // defined in another translation unit, we don't need to emit the
12626 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000012627 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000012628 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000012629 // The key function is in another translation unit.
12630 DefineVTable = false;
12631 TemplateSpecializationKind TSK =
12632 KeyFunction->getTemplateSpecializationKind();
12633 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12634 TSK != TSK_ImplicitInstantiation &&
12635 "Instantiations don't have key functions");
12636 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012637 } else if (!KeyFunction) {
12638 // If we have a class with no key function that is the subject
12639 // of an explicit instantiation declaration, suppress the
12640 // vtable; it will live with the explicit instantiation
12641 // definition.
12642 bool IsExplicitInstantiationDeclaration
12643 = Class->getTemplateSpecializationKind()
12644 == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000012645 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000012646 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000012647 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012648 if (TSK == TSK_ExplicitInstantiationDeclaration)
12649 IsExplicitInstantiationDeclaration = true;
12650 else if (TSK == TSK_ExplicitInstantiationDefinition) {
12651 IsExplicitInstantiationDeclaration = false;
12652 break;
12653 }
12654 }
12655
12656 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000012657 DefineVTable = false;
12658 }
12659
12660 // The exception specifications for all virtual members may be needed even
12661 // if we are not providing an authoritative form of the vtable in this TU.
12662 // We may choose to emit it available_externally anyway.
12663 if (!DefineVTable) {
12664 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12665 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012666 }
12667
12668 // Mark all of the virtual members of this class as referenced, so
12669 // that we can build a vtable. Then, tell the AST consumer that a
12670 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000012671 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012672 MarkVirtualMembersReferenced(Loc, Class);
12673 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12674 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12675
12676 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000012677 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000012678 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012679 const FunctionDecl *KeyFunctionDef = nullptr;
Douglas Gregor34bc6e52011-09-23 19:04:03 +000012680 if (!KeyFunction ||
12681 (KeyFunction->hasBody(KeyFunctionDef) &&
12682 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000012683 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12684 TSK_ExplicitInstantiationDefinition
12685 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12686 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012687 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000012688 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012689 VTableUses.clear();
12690
Douglas Gregor97509692011-04-22 22:25:37 +000012691 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000012692}
Anders Carlsson82fccd02009-12-07 08:24:59 +000012693
Richard Smithd3b5c9082012-07-27 04:22:15 +000012694void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12695 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000012696 for (const auto *I : RD->methods())
12697 if (I->isVirtual() && !I->isPure())
12698 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000012699}
12700
Rafael Espindola5b334082010-03-26 00:36:59 +000012701void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12702 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000012703 // Mark all functions which will appear in RD's vtable as used.
12704 CXXFinalOverriderMap FinalOverriders;
12705 RD->getFinalOverriders(FinalOverriders);
12706 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12707 E = FinalOverriders.end();
12708 I != E; ++I) {
12709 for (OverridingMethods::const_iterator OI = I->second.begin(),
12710 OE = I->second.end();
12711 OI != OE; ++OI) {
12712 assert(OI->second.size() > 0 && "no final overrider");
12713 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000012714
Richard Smith4ff9ff92012-07-07 06:59:51 +000012715 // C++ [basic.def.odr]p2:
12716 // [...] A virtual member function is used if it is not pure. [...]
12717 if (!Overrider->isPure())
12718 MarkFunctionReferenced(Loc, Overrider);
12719 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012720 }
Rafael Espindola5b334082010-03-26 00:36:59 +000012721
12722 // Only classes that have virtual bases need a VTT.
12723 if (RD->getNumVBases() == 0)
12724 return;
12725
Aaron Ballman574705e2014-03-13 15:41:46 +000012726 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000012727 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000012728 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000012729 if (Base->getNumVBases() == 0)
12730 continue;
12731 MarkVirtualMembersReferenced(Loc, Base);
12732 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000012733}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012734
12735/// SetIvarInitializers - This routine builds initialization ASTs for the
12736/// Objective-C implementation whose ivars need be initialized.
12737void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000012738 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012739 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000012740 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012741 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012742 CollectIvarsToConstructOrDestruct(OID, ivars);
12743 if (ivars.empty())
12744 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012745 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012746 for (unsigned i = 0; i < ivars.size(); i++) {
12747 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000012748 if (Field->isInvalidDecl())
12749 continue;
12750
Alexis Hunt1d792652011-01-08 20:30:50 +000012751 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012752 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12753 InitializationKind InitKind =
12754 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000012755
12756 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12757 ExprResult MemberInit =
12758 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000012759 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012760 // Note, MemberInit could actually come back empty if no initialization
12761 // is required (e.g., because it would call a trivial default constructor)
12762 if (!MemberInit.get() || MemberInit.isInvalid())
12763 continue;
John McCallacf0ee52010-10-08 02:01:28 +000012764
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012765 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000012766 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12767 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012768 MemberInit.getAs<Expr>(),
Alexis Hunt1d792652011-01-08 20:30:50 +000012769 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012770 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000012771
12772 // Be sure that the destructor is accessible and is marked as referenced.
12773 if (const RecordType *RecordTy
12774 = Context.getBaseElementType(Field->getType())
12775 ->getAs<RecordType>()) {
12776 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000012777 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000012778 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000012779 CheckDestructorAccess(Field->getLocation(), Destructor,
12780 PDiag(diag::err_access_dtor_ivar)
12781 << Context.getBaseElementType(Field->getType()));
12782 }
12783 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000012784 }
12785 ObjCImplementation->setIvarInitializers(Context,
12786 AllToInit.data(), AllToInit.size());
12787 }
12788}
Alexis Hunt6118d662011-05-04 05:57:24 +000012789
Alexis Hunt27a761d2011-05-04 23:29:54 +000012790static
12791void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12792 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12793 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12794 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12795 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000012796 if (Ctor->isInvalidDecl())
12797 return;
12798
Richard Smith802c4b72012-08-23 06:16:52 +000012799 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12800
12801 // Target may not be determinable yet, for instance if this is a dependent
12802 // call in an uninstantiated template.
12803 if (Target) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012804 const FunctionDecl *FNTarget = nullptr;
Richard Smith802c4b72012-08-23 06:16:52 +000012805 (void)Target->hasBody(FNTarget);
12806 Target = const_cast<CXXConstructorDecl*>(
12807 cast_or_null<CXXConstructorDecl>(FNTarget));
12808 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000012809
12810 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12811 // Avoid dereferencing a null pointer here.
Craig Topperc3ec1492014-05-26 06:22:03 +000012812 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000012813
12814 if (!Current.insert(Canonical))
12815 return;
12816
12817 // We know that beyond here, we aren't chaining into a cycle.
12818 if (!Target || !Target->isDelegatingConstructor() ||
12819 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012820 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012821 Current.clear();
12822 // We've hit a cycle.
12823 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12824 Current.count(TCanonical)) {
12825 // If we haven't diagnosed this cycle yet, do so now.
12826 if (!Invalid.count(TCanonical)) {
12827 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000012828 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012829 << Ctor;
12830
Richard Smith802c4b72012-08-23 06:16:52 +000012831 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000012832 if (TCanonical != Canonical)
12833 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12834
12835 CXXConstructorDecl *C = Target;
12836 while (C->getCanonicalDecl() != Canonical) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012837 const FunctionDecl *FNTarget = nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000012838 (void)C->getTargetConstructor()->hasBody(FNTarget);
12839 assert(FNTarget && "Ctor cycle through bodiless function");
12840
Richard Smith802c4b72012-08-23 06:16:52 +000012841 C = const_cast<CXXConstructorDecl*>(
12842 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000012843 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12844 }
12845 }
12846
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012847 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000012848 Current.clear();
12849 } else {
12850 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12851 }
12852}
12853
12854
Alexis Hunt6118d662011-05-04 05:57:24 +000012855void Sema::CheckDelegatingCtorCycles() {
12856 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12857
Douglas Gregorbae31202011-07-27 21:57:17 +000012858 for (DelegatingCtorDeclsType::iterator
12859 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000012860 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000012861 I != E; ++I)
12862 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000012863
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012864 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12865 CE = Invalid.end();
12866 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000012867 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000012868}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000012869
Douglas Gregor3024f072012-04-16 07:05:22 +000012870namespace {
12871 /// \brief AST visitor that finds references to the 'this' expression.
12872 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12873 Sema &S;
12874
12875 public:
12876 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12877
12878 bool VisitCXXThisExpr(CXXThisExpr *E) {
12879 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12880 << E->isImplicit();
12881 return false;
12882 }
12883 };
12884}
12885
12886bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12887 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12888 if (!TSInfo)
12889 return false;
12890
12891 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012892 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000012893 if (!ProtoTL)
12894 return false;
12895
12896 // C++11 [expr.prim.general]p3:
12897 // [The expression this] shall not appear before the optional
12898 // cv-qualifier-seq and it shall not appear within the declaration of a
12899 // static member function (although its type and value category are defined
12900 // within a static member function as they are within a non-static member
12901 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000012902 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000012903 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000012904 FindCXXThisExpr Finder(*this);
12905
12906 // If the return type came after the cv-qualifier-seq, check it now.
12907 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000012908 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000012909 return true;
12910
12911 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000012912 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12913 return true;
12914
12915 return checkThisInStaticMemberFunctionAttributes(Method);
12916}
12917
12918bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12919 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12920 if (!TSInfo)
12921 return false;
12922
12923 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000012924 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000012925 if (!ProtoTL)
12926 return false;
12927
David Blaikie6adc78e2013-02-18 22:06:02 +000012928 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000012929 FindCXXThisExpr Finder(*this);
12930
Douglas Gregor3024f072012-04-16 07:05:22 +000012931 switch (Proto->getExceptionSpecType()) {
Richard Smithf623c962012-04-17 00:58:00 +000012932 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000012933 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000012934 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000012935 case EST_DynamicNone:
12936 case EST_MSAny:
12937 case EST_None:
12938 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000012939
Douglas Gregor3024f072012-04-16 07:05:22 +000012940 case EST_ComputedNoexcept:
12941 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12942 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000012943
Douglas Gregor3024f072012-04-16 07:05:22 +000012944 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000012945 for (const auto &E : Proto->exceptions()) {
12946 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000012947 return true;
12948 }
12949 break;
12950 }
Douglas Gregor433e0532012-04-16 18:27:27 +000012951
12952 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000012953}
12954
12955bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12956 FindCXXThisExpr Finder(*this);
12957
12958 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012959 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012960 // FIXME: This should be emitted by tblgen.
Craig Topperc3ec1492014-05-26 06:22:03 +000012961 Expr *Arg = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +000012962 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012963 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012964 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012965 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012966 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012967 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012968 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012969 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012970 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012971 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012972 Arg = ETLF->getSuccessValue();
12973 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012974 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000012975 Arg = STLF->getSuccessValue();
12976 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
Aaron Ballman18d85ae2014-03-20 16:02:49 +000012977 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012978 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012979 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000012980 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012981 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Aaron Ballmanefe348e2014-02-18 17:36:50 +000012982 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012983 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Aaron Ballman9e9d1842014-02-21 21:05:14 +000012984 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000012985 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
12986 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size());
12987 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Aaron Ballman9e9d1842014-02-21 21:05:14 +000012988 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000012989
12990 if (Arg && !Finder.TraverseStmt(Arg))
12991 return true;
12992
12993 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12994 if (!Finder.TraverseStmt(Args[I]))
12995 return true;
12996 }
12997 }
12998
12999 return false;
13000}
13001
Douglas Gregor433e0532012-04-16 18:27:27 +000013002void
13003Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
13004 ArrayRef<ParsedType> DynamicExceptions,
13005 ArrayRef<SourceRange> DynamicExceptionRanges,
13006 Expr *NoexceptExpr,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013007 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +000013008 FunctionProtoType::ExceptionSpecInfo &ESI) {
Douglas Gregor433e0532012-04-16 18:27:27 +000013009 Exceptions.clear();
Richard Smith8acb4282014-07-31 21:57:55 +000013010 ESI.Type = EST;
Douglas Gregor433e0532012-04-16 18:27:27 +000013011 if (EST == EST_Dynamic) {
13012 Exceptions.reserve(DynamicExceptions.size());
13013 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13014 // FIXME: Preserve type source info.
13015 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13016
13017 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13018 collectUnexpandedParameterPacks(ET, Unexpanded);
13019 if (!Unexpanded.empty()) {
13020 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
13021 UPPC_ExceptionType,
13022 Unexpanded);
13023 continue;
13024 }
13025
13026 // Check that the type is valid for an exception spec, and
13027 // drop it if not.
13028 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13029 Exceptions.push_back(ET);
13030 }
Richard Smith8acb4282014-07-31 21:57:55 +000013031 ESI.Exceptions = Exceptions;
Douglas Gregor433e0532012-04-16 18:27:27 +000013032 return;
13033 }
Richard Smith8acb4282014-07-31 21:57:55 +000013034
Douglas Gregor433e0532012-04-16 18:27:27 +000013035 if (EST == EST_ComputedNoexcept) {
13036 // If an error occurred, there's no expression here.
13037 if (NoexceptExpr) {
13038 assert((NoexceptExpr->isTypeDependent() ||
13039 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13040 Context.BoolTy) &&
13041 "Parser should have made sure that the expression is boolean");
13042 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
Richard Smith8acb4282014-07-31 21:57:55 +000013043 ESI.Type = EST_BasicNoexcept;
Douglas Gregor433e0532012-04-16 18:27:27 +000013044 return;
13045 }
Richard Smith8acb4282014-07-31 21:57:55 +000013046
Douglas Gregor433e0532012-04-16 18:27:27 +000013047 if (!NoexceptExpr->isValueDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +000013048 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
Douglas Gregore2b37442012-05-04 22:38:52 +000013049 diag::err_noexcept_needs_constant_expression,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013050 /*AllowFold*/ false).get();
Richard Smith8acb4282014-07-31 21:57:55 +000013051 ESI.NoexceptExpr = NoexceptExpr;
Douglas Gregor433e0532012-04-16 18:27:27 +000013052 }
13053 return;
13054 }
13055}
13056
Peter Collingbourne7277fe82011-10-02 23:49:40 +000013057/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
13058Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
13059 // Implicitly declared functions (e.g. copy constructors) are
13060 // __host__ __device__
13061 if (D->isImplicit())
13062 return CFT_HostDevice;
13063
13064 if (D->hasAttr<CUDAGlobalAttr>())
13065 return CFT_Global;
13066
13067 if (D->hasAttr<CUDADeviceAttr>()) {
13068 if (D->hasAttr<CUDAHostAttr>())
13069 return CFT_HostDevice;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013070 return CFT_Device;
Peter Collingbourne7277fe82011-10-02 23:49:40 +000013071 }
13072
13073 return CFT_Host;
13074}
13075
13076bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
13077 CUDAFunctionTarget CalleeTarget) {
13078 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
13079 // Callable from the device only."
13080 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
13081 return true;
13082
13083 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
13084 // Callable from the host only."
13085 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
13086 // Callable from the host only."
13087 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
13088 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
13089 return true;
13090
13091 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
13092 return true;
13093
13094 return false;
13095}
John McCall5e77d762013-04-16 07:28:30 +000013096
13097/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13098///
13099MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13100 SourceLocation DeclStart,
13101 Declarator &D, Expr *BitWidth,
13102 InClassInitStyle InitStyle,
13103 AccessSpecifier AS,
13104 AttributeList *MSPropertyAttr) {
13105 IdentifierInfo *II = D.getIdentifier();
13106 if (!II) {
13107 Diag(DeclStart, diag::err_anonymous_property);
Craig Topperc3ec1492014-05-26 06:22:03 +000013108 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013109 }
13110 SourceLocation Loc = D.getIdentifierLoc();
13111
13112 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13113 QualType T = TInfo->getType();
13114 if (getLangOpts().CPlusPlus) {
13115 CheckExtraCXXDefaultArguments(D);
13116
13117 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13118 UPPC_DataMemberType)) {
13119 D.setInvalidType();
13120 T = Context.IntTy;
13121 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13122 }
13123 }
13124
13125 DiagnoseFunctionSpecifiers(D.getDeclSpec());
13126
13127 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13128 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13129 diag::err_invalid_thread)
13130 << DeclSpec::getSpecifierName(TSCS);
13131
13132 // Check to see if this name was declared as a member previously
Craig Topperc3ec1492014-05-26 06:22:03 +000013133 NamedDecl *PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013134 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13135 LookupName(Previous, S);
13136 switch (Previous.getResultKind()) {
13137 case LookupResult::Found:
13138 case LookupResult::FoundUnresolvedValue:
13139 PrevDecl = Previous.getAsSingle<NamedDecl>();
13140 break;
13141
13142 case LookupResult::FoundOverloaded:
13143 PrevDecl = Previous.getRepresentativeDecl();
13144 break;
13145
13146 case LookupResult::NotFound:
13147 case LookupResult::NotFoundInCurrentInstantiation:
13148 case LookupResult::Ambiguous:
13149 break;
13150 }
13151
13152 if (PrevDecl && PrevDecl->isTemplateParameter()) {
13153 // Maybe we will complain about the shadowed template parameter.
13154 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13155 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000013156 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013157 }
13158
13159 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Craig Topperc3ec1492014-05-26 06:22:03 +000013160 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013161
13162 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000013163 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000013164 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13165 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000013166 ProcessDeclAttributes(TUScope, NewPD, D);
13167 NewPD->setAccess(AS);
13168
13169 if (NewPD->isInvalidDecl())
13170 Record->setInvalidDecl();
13171
13172 if (D.getDeclSpec().isModulePrivateSpecified())
13173 NewPD->setModulePrivate();
13174
13175 if (NewPD->isInvalidDecl() && PrevDecl) {
13176 // Don't introduce NewFD into scope; there's already something
13177 // with the same name in the same scope.
13178 } else if (II) {
13179 PushOnScopeChains(NewPD, S);
13180 } else
13181 Record->addDecl(NewPD);
13182
13183 return NewPD;
13184}