blob: c11574519663ac5e981f6ebade7218f704a87e8a [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)
Fariborz Jahanian7bd22e92014-10-01 18:03:51 +0000356 OpaqueValueExpr(EqualLoc,
357 Param->getType().getNonReferenceType(),
358 VK_RValue));
Douglas Gregor4d87df52008-12-16 21:30:33 +0000359}
360
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000361/// CheckExtraCXXDefaultArguments - Check for any extra default
362/// arguments in the declarator, which is not a function declaration
363/// or definition and therefore is not permitted to have default
364/// arguments. This routine should be invoked for every declarator
365/// that is not a function declaration or definition.
366void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
367 // C++ [dcl.fct.default]p3
368 // A default argument expression shall be specified only in the
369 // parameter-declaration-clause of a function declaration or in a
370 // template-parameter (14.1). It shall not be specified for a
371 // parameter pack. If it is specified in a
372 // parameter-declaration-clause, it shall not occur within a
373 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000374 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattner83f095c2009-03-28 19:18:32 +0000375 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000376 DeclaratorChunk &chunk = D.getTypeObject(i);
377 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000378 if (MightBeFunction) {
379 // This is a function declaration. It can have default arguments, but
380 // keep looking in case its return type is a function type with default
381 // arguments.
382 MightBeFunction = false;
383 continue;
384 }
Alp Tokerc5350722014-02-26 22:27:52 +0000385 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
386 ++argIdx) {
387 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000388 if (Param->hasUnparsedDefaultArg()) {
Alp Tokerc5350722014-02-26 22:27:52 +0000389 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000390 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000391 << SourceRange((*Toks)[1].getLocation(),
392 Toks->back().getLocation());
Douglas Gregor4d87df52008-12-16 21:30:33 +0000393 delete Toks;
Craig Topperc3ec1492014-05-26 06:22:03 +0000394 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
Douglas Gregor58354032008-12-24 00:01:03 +0000395 } else if (Param->getDefaultArg()) {
396 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
397 << Param->getDefaultArg()->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +0000398 Param->setDefaultArg(nullptr);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000399 }
400 }
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000401 } else if (chunk.Kind != DeclaratorChunk::Paren) {
402 MightBeFunction = false;
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000403 }
404 }
405}
406
David Majnemer502b0ed2013-06-25 23:09:30 +0000407static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
408 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
409 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
410 if (!PVD->hasDefaultArg())
411 return false;
412 if (!PVD->hasInheritedDefaultArg())
413 return true;
414 }
415 return false;
416}
417
Craig Toppere4794282012-09-21 04:33:26 +0000418/// MergeCXXFunctionDecl - Merge two declarations of the same C++
419/// function, once we already know that they have the same
420/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
421/// error, false otherwise.
James Molloye9430032012-03-13 08:55:35 +0000422bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
423 Scope *S) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000424 bool Invalid = false;
425
Chris Lattner199abbc2008-04-08 05:04:30 +0000426 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000427 // For non-template functions, default arguments can be added in
428 // later declarations of a function in the same
429 // scope. Declarations in different scopes have completely
430 // distinct sets of default arguments. That is, declarations in
431 // inner scopes do not acquire default arguments from
432 // declarations in outer scopes, and vice versa. In a given
433 // function declaration, all parameters subsequent to a
434 // parameter with a default argument shall have default
435 // arguments supplied in this or previous declarations. A
436 // default argument shall not be redefined by a later
437 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000438 //
439 // C++ [dcl.fct.default]p6:
Richard Smith541b38b2013-09-20 01:15:31 +0000440 // Except for member functions of class templates, the default arguments
441 // in a member function definition that appears outside of the class
442 // definition are added to the set of default arguments provided by the
Douglas Gregorc732aba2009-09-11 18:44:32 +0000443 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000444 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
445 ParmVarDecl *OldParam = Old->getParamDecl(p);
446 ParmVarDecl *NewParam = New->getParamDecl(p);
447
James Molloye9430032012-03-13 08:55:35 +0000448 bool OldParamHasDfl = OldParam->hasDefaultArg();
449 bool NewParamHasDfl = NewParam->hasDefaultArg();
450
Richard Smith541b38b2013-09-20 01:15:31 +0000451 // 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.
Richard Smith5971e8c2014-08-27 22:31:34 +0000454 DeclContext *ScopeDC = New->isLocalExternDecl()
455 ? New->getLexicalDeclContext()
456 : New->getDeclContext();
457 if (S && !isDeclInScope(Old, ScopeDC, S) &&
Richard Smith541b38b2013-09-20 01:15:31 +0000458 !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;
Richard Smith5971e8c2014-08-27 22:31:34 +0000463 if (New->isLocalExternDecl() != Old->isLocalExternDecl())
464 // If only one of these is a local function declaration, then they are
465 // declared in different scopes, even though isDeclInScope may think
466 // they're in the same scope. (If both are local, the scope check is
467 // sufficent, and if neither is local, then they are in the same scope.)
468 OldParamHasDfl = false;
James Molloye9430032012-03-13 08:55:35 +0000469
470 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000471
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000472 unsigned DiagDefaultParamID =
473 diag::err_param_default_argument_redefinition;
474
475 // MSVC accepts that default parameters be redefined for member functions
476 // of template class. The new default parameter's value is ignored.
477 Invalid = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000478 if (getLangOpts().MicrosoftExt) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000479 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
480 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000481 // Merge the old default argument into the new parameter.
482 NewParam->setHasInheritedDefaultArg();
483 if (OldParam->hasUninstantiatedDefaultArg())
484 NewParam->setUninstantiatedDefaultArg(
485 OldParam->getUninstantiatedDefaultArg());
486 else
487 NewParam->setDefaultArg(OldParam->getInit());
Richard Smith1b98ccc2014-07-19 01:39:17 +0000488 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000489 Invalid = false;
490 }
491 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000492
Francois Pichet8cb243a2011-04-10 04:58:30 +0000493 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
494 // hint here. Alternatively, we could walk the type-source information
495 // for NewParam to find the last source location in the type... but it
496 // isn't worth the effort right now. This is the kind of test case that
497 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000498 // int f(int);
499 // void g(int (*fp)(int) = f);
500 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000501 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000502 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000503
504 // Look for the function declaration where the default argument was
505 // actually written, which may be a declaration prior to Old.
Douglas Gregorec9fd132012-01-14 16:38:05 +0000506 for (FunctionDecl *Older = Old->getPreviousDecl();
507 Older; Older = Older->getPreviousDecl()) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000508 if (!Older->getParamDecl(p)->hasDefaultArg())
509 break;
510
511 OldParam = Older->getParamDecl(p);
512 }
513
514 Diag(OldParam->getLocation(), diag::note_previous_definition)
515 << OldParam->getDefaultArgRange();
James Molloye9430032012-03-13 08:55:35 +0000516 } else if (OldParamHasDfl) {
John McCalle61b02b2010-05-04 01:53:42 +0000517 // Merge the old default argument into the new parameter.
518 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000519 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000520 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000521 if (OldParam->hasUninstantiatedDefaultArg())
522 NewParam->setUninstantiatedDefaultArg(
523 OldParam->getUninstantiatedDefaultArg());
524 else
John McCalle61b02b2010-05-04 01:53:42 +0000525 NewParam->setDefaultArg(OldParam->getInit());
James Molloye9430032012-03-13 08:55:35 +0000526 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000527 if (New->getDescribedFunctionTemplate()) {
528 // Paragraph 4, quoted above, only applies to non-template functions.
529 Diag(NewParam->getLocation(),
530 diag::err_param_default_argument_template_redecl)
531 << NewParam->getDefaultArgRange();
532 Diag(Old->getLocation(), diag::note_template_prev_declaration)
533 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000534 } else if (New->getTemplateSpecializationKind()
535 != TSK_ImplicitInstantiation &&
536 New->getTemplateSpecializationKind() != TSK_Undeclared) {
537 // C++ [temp.expr.spec]p21:
538 // Default function arguments shall not be specified in a declaration
539 // or a definition for one of the following explicit specializations:
540 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000541 // - the explicit specialization of a member function template;
542 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000543 // template where the class template specialization to which the
544 // member function specialization belongs is implicitly
545 // instantiated.
546 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
547 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
548 << New->getDeclName()
549 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000550 } else if (New->getDeclContext()->isDependentContext()) {
551 // C++ [dcl.fct.default]p6 (DR217):
552 // Default arguments for a member function of a class template shall
553 // be specified on the initial declaration of the member function
554 // within the class template.
555 //
556 // Reading the tea leaves a bit in DR217 and its reference to DR205
557 // leads me to the conclusion that one cannot add default function
558 // arguments for an out-of-line definition of a member function of a
559 // dependent type.
560 int WhichKind = 2;
561 if (CXXRecordDecl *Record
562 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
563 if (Record->getDescribedClassTemplate())
564 WhichKind = 0;
565 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
566 WhichKind = 1;
567 else
568 WhichKind = 2;
569 }
570
571 Diag(NewParam->getLocation(),
572 diag::err_param_default_argument_member_template_redecl)
573 << WhichKind
574 << NewParam->getDefaultArgRange();
575 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000576 }
577 }
578
Richard Smith58c3cc12012-11-28 03:45:24 +0000579 // DR1344: If a default argument is added outside a class definition and that
580 // default argument makes the function a special member function, the program
581 // is ill-formed. This can only happen for constructors.
582 if (isa<CXXConstructorDecl>(New) &&
583 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
584 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
585 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
586 if (NewSM != OldSM) {
587 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
588 assert(NewParam->hasDefaultArg());
589 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
590 << NewParam->getDefaultArgRange() << NewSM;
591 Diag(Old->getLocation(), diag::note_previous_declaration);
592 }
593 }
594
David Majnemeree4f4022014-03-30 06:44:54 +0000595 const FunctionDecl *Def;
Richard Smith5b8b3db2012-02-20 23:28:05 +0000596 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000597 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000598 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000599 if (New->isConstexpr() != Old->isConstexpr()) {
600 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
601 << New << New->isConstexpr();
602 Diag(Old->getLocation(), diag::note_previous_declaration);
603 Invalid = true;
David Majnemeree4f4022014-03-30 06:44:54 +0000604 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) {
605 // C++11 [dcl.fcn.spec]p4:
606 // If the definition of a function appears in a translation unit before its
607 // first declaration as inline, the program is ill-formed.
608 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
609 Diag(Def->getLocation(), diag::note_previous_definition);
610 Invalid = true;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000611 }
612
David Majnemer502b0ed2013-06-25 23:09:30 +0000613 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000614 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000615 // the only declaration of the function or function template in the
616 // translation unit.
617 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
618 functionDeclHasDefaultArgument(Old)) {
619 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
620 Diag(Old->getLocation(), diag::note_previous_declaration);
621 Invalid = true;
622 }
623
Douglas Gregorf40863c2010-02-12 07:32:17 +0000624 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000625 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000626
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000627 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000628}
629
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000630/// \brief Merge the exception specifications of two variable declarations.
631///
632/// This is called when there's a redeclaration of a VarDecl. The function
633/// checks if the redeclaration might have an exception specification and
634/// validates compatibility and merges the specs if necessary.
635void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
636 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000637 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000638 return;
639
640 assert(Context.hasSameType(New->getType(), Old->getType()) &&
641 "Should only be called if types are otherwise the same.");
642
643 QualType NewType = New->getType();
644 QualType OldType = Old->getType();
645
646 // We're only interested in pointers and references to functions, as well
647 // as pointers to member functions.
648 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
649 NewType = R->getPointeeType();
650 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
651 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
652 NewType = P->getPointeeType();
653 OldType = OldType->getAs<PointerType>()->getPointeeType();
654 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
655 NewType = M->getPointeeType();
656 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
657 }
658
659 if (!NewType->isFunctionProtoType())
660 return;
661
662 // There's lots of special cases for functions. For function pointers, system
663 // libraries are hopefully not as broken so that we don't need these
664 // workarounds.
665 if (CheckEquivalentExceptionSpec(
666 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
667 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
668 New->setInvalidDecl();
669 }
670}
671
Chris Lattner199abbc2008-04-08 05:04:30 +0000672/// CheckCXXDefaultArguments - Verify that the default arguments for a
673/// function declaration are well-formed according to C++
674/// [dcl.fct.default].
675void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
676 unsigned NumParams = FD->getNumParams();
677 unsigned p;
678
679 // Find first parameter with a default argument
680 for (p = 0; p < NumParams; ++p) {
681 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +0000682 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000683 break;
684 }
685
686 // C++ [dcl.fct.default]p4:
687 // In a given function declaration, all parameters
688 // subsequent to a parameter with a default argument shall
689 // have default arguments supplied in this or previous
690 // declarations. A default argument shall not be redefined
691 // by a later declaration (not even to the same value).
692 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000693 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000694 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000695 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000696 if (Param->isInvalidDecl())
697 /* We already complained about this parameter. */;
698 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000699 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000700 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000701 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000702 else
Mike Stump11289f42009-09-09 15:08:12 +0000703 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000704 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000705
Chris Lattner199abbc2008-04-08 05:04:30 +0000706 LastMissingDefaultArg = p;
707 }
708 }
709
710 if (LastMissingDefaultArg > 0) {
711 // Some default arguments were missing. Clear out all of the
712 // default arguments up to (and including) the last missing
713 // default argument, so that we leave the function parameters
714 // in a semantically valid state.
715 for (p = 0; p <= LastMissingDefaultArg; ++p) {
716 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000717 if (Param->hasDefaultArg()) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000718 Param->setDefaultArg(nullptr);
Chris Lattner199abbc2008-04-08 05:04:30 +0000719 }
720 }
721 }
722}
Douglas Gregor556877c2008-04-13 21:30:24 +0000723
Richard Smitheb3c10c2011-10-01 02:31:28 +0000724// CheckConstexprParameterTypes - Check whether a function's parameter types
725// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +0000726// diagnostic and return false.
727static bool CheckConstexprParameterTypes(Sema &SemaRef,
728 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000729 unsigned ArgIndex = 0;
730 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +0000731 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
732 e = FT->param_type_end();
733 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000734 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
735 SourceLocation ParamLoc = PD->getLocation();
736 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000737 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000738 diag::err_constexpr_non_literal_param,
739 ArgIndex+1, PD->getSourceRange(),
740 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000741 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000742 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000743 return true;
744}
745
746/// \brief Get diagnostic %select index for tag kind for
747/// record diagnostic message.
748/// WARNING: Indexes apply to particular diagnostics only!
749///
750/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +0000751static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +0000752 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +0000753 case TTK_Struct: return 0;
754 case TTK_Interface: return 1;
755 case TTK_Class: return 2;
756 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +0000757 }
Joao Matose9a3ed42012-08-31 22:18:20 +0000758}
759
760// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
761// the requirements of a constexpr function definition or a constexpr
762// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +0000763// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000764//
Richard Smith3607ffe2012-02-13 03:54:03 +0000765// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
766bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +0000767 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
768 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000769 // C++11 [dcl.constexpr]p4:
770 // The definition of a constexpr constructor shall satisfy the following
771 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000772 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +0000773 const CXXRecordDecl *RD = MD->getParent();
774 if (RD->getNumVBases()) {
775 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
776 << isa<CXXConstructorDecl>(NewFD)
777 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Aaron Ballman445a9392014-03-13 16:15:17 +0000778 for (const auto &I : RD->vbases())
779 Diag(I.getLocStart(),
780 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000781 return false;
782 }
Richard Smith7971b692012-01-13 04:54:00 +0000783 }
784
785 if (!isa<CXXConstructorDecl>(NewFD)) {
786 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000787 // The definition of a constexpr function shall satisfy the following
788 // constraints:
789 // - it shall not be virtual;
790 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
791 if (Method && Method->isVirtual()) {
Richard Smith3607ffe2012-02-13 03:54:03 +0000792 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000793
Richard Smith3607ffe2012-02-13 03:54:03 +0000794 // If it's not obvious why this function is virtual, find an overridden
795 // function which uses the 'virtual' keyword.
796 const CXXMethodDecl *WrittenVirtual = Method;
797 while (!WrittenVirtual->isVirtualAsWritten())
798 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
799 if (WrittenVirtual != Method)
800 Diag(WrittenVirtual->getLocation(),
801 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000802 return false;
803 }
804
805 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +0000806 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000807 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +0000808 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +0000809 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +0000810 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000811 }
812
Richard Smith7971b692012-01-13 04:54:00 +0000813 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +0000814 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +0000815 return false;
816
Richard Smitheb3c10c2011-10-01 02:31:28 +0000817 return true;
818}
819
820/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +0000821/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000822///
Richard Smithd9f663b2013-04-22 15:31:51 +0000823/// \return true if the body is OK (maybe only as an extension), false if we
824/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000825static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +0000826 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
827 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000828 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
829 // contain only
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000830 for (const auto *DclIt : DS->decls()) {
831 switch (DclIt->getKind()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000832 case Decl::StaticAssert:
833 case Decl::Using:
834 case Decl::UsingShadow:
835 case Decl::UsingDirective:
836 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +0000837 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000838 // - static_assert-declarations
839 // - using-declarations,
840 // - using-directives,
841 continue;
842
843 case Decl::Typedef:
844 case Decl::TypeAlias: {
845 // - typedef declarations and alias-declarations that do not define
846 // classes or enumerations,
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000847 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000848 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
849 // Don't allow variably-modified types in constexpr functions.
850 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
851 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
852 << TL.getSourceRange() << TL.getType()
853 << isa<CXXConstructorDecl>(Dcl);
854 return false;
855 }
856 continue;
857 }
858
859 case Decl::Enum:
860 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +0000861 // C++1y allows types to be defined, not just declared.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000862 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smithd9f663b2013-04-22 15:31:51 +0000863 SemaRef.Diag(DS->getLocStart(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000864 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +0000865 ? diag::warn_cxx11_compat_constexpr_type_definition
866 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000867 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000868 continue;
869
Richard Smithd9f663b2013-04-22 15:31:51 +0000870 case Decl::EnumConstant:
871 case Decl::IndirectField:
872 case Decl::ParmVar:
873 // These can only appear with other declarations which are banned in
874 // C++11 and permitted in C++1y, so ignore them.
875 continue;
876
877 case Decl::Var: {
878 // C++1y [dcl.constexpr]p3 allows anything except:
879 // a definition of a variable of non-literal type or of static or
880 // thread storage duration or for which no initialization is performed.
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000881 const auto *VD = cast<VarDecl>(DclIt);
Richard Smithd9f663b2013-04-22 15:31:51 +0000882 if (VD->isThisDeclarationADefinition()) {
883 if (VD->isStaticLocal()) {
884 SemaRef.Diag(VD->getLocation(),
885 diag::err_constexpr_local_var_static)
886 << isa<CXXConstructorDecl>(Dcl)
887 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
888 return false;
889 }
Richard Smith3da88fa2013-04-26 14:36:30 +0000890 if (!VD->getType()->isDependentType() &&
891 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +0000892 VD->getLocation(), VD->getType(),
893 diag::err_constexpr_local_var_non_literal_type,
894 isa<CXXConstructorDecl>(Dcl)))
895 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +0000896 if (!VD->getType()->isDependentType() &&
897 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +0000898 SemaRef.Diag(VD->getLocation(),
899 diag::err_constexpr_local_var_no_init)
900 << isa<CXXConstructorDecl>(Dcl);
901 return false;
902 }
903 }
904 SemaRef.Diag(VD->getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000905 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +0000906 ? diag::warn_cxx11_compat_constexpr_local_var
907 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +0000908 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +0000909 continue;
910 }
911
912 case Decl::NamespaceAlias:
913 case Decl::Function:
914 // These are disallowed in C++11 and permitted in C++1y. Allow them
915 // everywhere as an extension.
916 if (!Cxx1yLoc.isValid())
917 Cxx1yLoc = DS->getLocStart();
918 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000919
920 default:
921 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
922 << isa<CXXConstructorDecl>(Dcl);
923 return false;
924 }
925 }
926
927 return true;
928}
929
930/// Check that the given field is initialized within a constexpr constructor.
931///
932/// \param Dcl The constexpr constructor being checked.
933/// \param Field The field being checked. This may be a member of an anonymous
934/// struct or union nested within the class being checked.
935/// \param Inits All declarations, including anonymous struct/union members and
936/// indirect members, for which any initialization was provided.
937/// \param Diagnosed Set to true if an error is produced.
938static void CheckConstexprCtorInitializer(Sema &SemaRef,
939 const FunctionDecl *Dcl,
940 FieldDecl *Field,
941 llvm::SmallSet<Decl*, 16> &Inits,
942 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +0000943 if (Field->isInvalidDecl())
944 return;
945
Douglas Gregor556e5862011-10-10 17:22:13 +0000946 if (Field->isUnnamedBitfield())
947 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +0000948
Richard Smithab44d5b2013-12-10 08:25:00 +0000949 // Anonymous unions with no variant members and empty anonymous structs do not
950 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
951 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +0000952 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +0000953 (Field->getType()->isUnionType()
954 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
955 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +0000956 return;
957
Richard Smitheb3c10c2011-10-01 02:31:28 +0000958 if (!Inits.count(Field)) {
959 if (!Diagnosed) {
960 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
961 Diagnosed = true;
962 }
963 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
964 } else if (Field->isAnonymousStructOrUnion()) {
965 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000966 for (auto *I : RD->fields())
Richard Smitheb3c10c2011-10-01 02:31:28 +0000967 // If an anonymous union contains an anonymous struct of which any member
968 // is initialized, all members must be initialized.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000969 if (!RD->isUnion() || Inits.count(I))
970 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +0000971 }
972}
973
Richard Smithd9f663b2013-04-22 15:31:51 +0000974/// Check the provided statement is allowed in a constexpr function
975/// definition.
976static bool
977CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +0000978 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +0000979 SourceLocation &Cxx1yLoc) {
980 // - its function-body shall be [...] a compound-statement that contains only
981 switch (S->getStmtClass()) {
982 case Stmt::NullStmtClass:
983 // - null statements,
984 return true;
985
986 case Stmt::DeclStmtClass:
987 // - static_assert-declarations
988 // - using-declarations,
989 // - using-directives,
990 // - typedef declarations and alias-declarations that do not define
991 // classes or enumerations,
992 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
993 return false;
994 return true;
995
996 case Stmt::ReturnStmtClass:
997 // - and exactly one return statement;
998 if (isa<CXXConstructorDecl>(Dcl)) {
999 // C++1y allows return statements in constexpr constructors.
1000 if (!Cxx1yLoc.isValid())
1001 Cxx1yLoc = S->getLocStart();
1002 return true;
1003 }
1004
1005 ReturnStmts.push_back(S->getLocStart());
1006 return true;
1007
1008 case Stmt::CompoundStmtClass: {
1009 // C++1y allows compound-statements.
1010 if (!Cxx1yLoc.isValid())
1011 Cxx1yLoc = S->getLocStart();
1012
1013 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001014 for (auto *BodyIt : CompStmt->body()) {
1015 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001016 Cxx1yLoc))
1017 return false;
1018 }
1019 return true;
1020 }
1021
1022 case Stmt::AttributedStmtClass:
1023 if (!Cxx1yLoc.isValid())
1024 Cxx1yLoc = S->getLocStart();
1025 return true;
1026
1027 case Stmt::IfStmtClass: {
1028 // C++1y allows if-statements.
1029 if (!Cxx1yLoc.isValid())
1030 Cxx1yLoc = S->getLocStart();
1031
1032 IfStmt *If = cast<IfStmt>(S);
1033 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1034 Cxx1yLoc))
1035 return false;
1036 if (If->getElse() &&
1037 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1038 Cxx1yLoc))
1039 return false;
1040 return true;
1041 }
1042
1043 case Stmt::WhileStmtClass:
1044 case Stmt::DoStmtClass:
1045 case Stmt::ForStmtClass:
1046 case Stmt::CXXForRangeStmtClass:
1047 case Stmt::ContinueStmtClass:
1048 // C++1y allows all of these. We don't allow them as extensions in C++11,
1049 // because they don't make sense without variable mutation.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001050 if (!SemaRef.getLangOpts().CPlusPlus14)
Richard Smithd9f663b2013-04-22 15:31:51 +00001051 break;
1052 if (!Cxx1yLoc.isValid())
1053 Cxx1yLoc = S->getLocStart();
1054 for (Stmt::child_range Children = S->children(); Children; ++Children)
1055 if (*Children &&
1056 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1057 Cxx1yLoc))
1058 return false;
1059 return true;
1060
1061 case Stmt::SwitchStmtClass:
1062 case Stmt::CaseStmtClass:
1063 case Stmt::DefaultStmtClass:
1064 case Stmt::BreakStmtClass:
1065 // C++1y allows switch-statements, and since they don't need variable
1066 // mutation, we can reasonably allow them in C++11 as an extension.
1067 if (!Cxx1yLoc.isValid())
1068 Cxx1yLoc = S->getLocStart();
1069 for (Stmt::child_range Children = S->children(); Children; ++Children)
1070 if (*Children &&
1071 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1072 Cxx1yLoc))
1073 return false;
1074 return true;
1075
1076 default:
1077 if (!isa<Expr>(S))
1078 break;
1079
1080 // C++1y allows expression-statements.
1081 if (!Cxx1yLoc.isValid())
1082 Cxx1yLoc = S->getLocStart();
1083 return true;
1084 }
1085
1086 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1087 << isa<CXXConstructorDecl>(Dcl);
1088 return false;
1089}
1090
Richard Smitheb3c10c2011-10-01 02:31:28 +00001091/// Check the body for the given constexpr function declaration only contains
1092/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1093///
1094/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001095bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001096 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001097 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001098 // The definition of a constexpr function shall satisfy the following
1099 // constraints: [...]
1100 // - its function-body shall be = delete, = default, or a
1101 // compound-statement
1102 //
Richard Smith74388b42012-02-04 00:33:54 +00001103 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001104 // In the definition of a constexpr constructor, [...]
1105 // - its function-body shall not be a function-try-block;
1106 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1107 << isa<CXXConstructorDecl>(Dcl);
1108 return false;
1109 }
1110
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001111 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001112
1113 // - its function-body shall be [...] a compound-statement that contains only
1114 // [... list of cases ...]
1115 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1116 SourceLocation Cxx1yLoc;
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001117 for (auto *BodyIt : CompBody->body()) {
1118 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smithd9f663b2013-04-22 15:31:51 +00001119 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001120 }
1121
Richard Smithd9f663b2013-04-22 15:31:51 +00001122 if (Cxx1yLoc.isValid())
1123 Diag(Cxx1yLoc,
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001124 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001125 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1126 : diag::ext_constexpr_body_invalid_stmt)
1127 << isa<CXXConstructorDecl>(Dcl);
1128
Richard Smitheb3c10c2011-10-01 02:31:28 +00001129 if (const CXXConstructorDecl *Constructor
1130 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1131 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001132 // DR1359:
1133 // - every non-variant non-static data member and base class sub-object
1134 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001135 // DR1460:
1136 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001137 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001138 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001139 if (Constructor->getNumCtorInitializers() == 0 &&
1140 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001141 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1142 return false;
1143 }
Richard Smithf368fb42011-10-10 16:38:04 +00001144 } else if (!Constructor->isDependentContext() &&
1145 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001146 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1147
1148 // Skip detailed checking if we have enough initializers, and we would
1149 // allow at most one initializer per member.
1150 bool AnyAnonStructUnionMembers = false;
1151 unsigned Fields = 0;
1152 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1153 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001154 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001155 AnyAnonStructUnionMembers = true;
1156 break;
1157 }
1158 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001159 // DR1460:
1160 // - if the class is a union-like class, but is not a union, for each of
1161 // its anonymous union members having variant members, exactly one of
1162 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001163 if (AnyAnonStructUnionMembers ||
1164 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1165 // Check initialization of non-static data members. Base classes are
1166 // always initialized so do not need to be checked. Dependent bases
1167 // might not have initializers in the member initializer list.
1168 llvm::SmallSet<Decl*, 16> Inits;
Aaron Ballman0ad78302014-03-13 17:34:31 +00001169 for (const auto *I: Constructor->inits()) {
1170 if (FieldDecl *FD = I->getMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001171 Inits.insert(FD);
Aaron Ballman0ad78302014-03-13 17:34:31 +00001172 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001173 Inits.insert(ID->chain_begin(), ID->chain_end());
1174 }
1175
1176 bool Diagnosed = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001177 for (auto *I : RD->fields())
1178 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001179 if (Diagnosed)
1180 return false;
1181 }
1182 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001183 } else {
1184 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001185 // C++1y doesn't require constexpr functions to contain a 'return'
Richard Smith06ffb452014-04-22 23:14:23 +00001186 // statement. We still do, unless the return type might be void, because
Richard Smithd9f663b2013-04-22 15:31:51 +00001187 // otherwise if there's no return statement, the function cannot
1188 // be used in a core constant expression.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001189 bool OK = getLangOpts().CPlusPlus14 &&
Richard Smith06ffb452014-04-22 23:14:23 +00001190 (Dcl->getReturnType()->isVoidType() ||
1191 Dcl->getReturnType()->isDependentType());
Richard Smithd9f663b2013-04-22 15:31:51 +00001192 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00001193 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1194 : diag::err_constexpr_body_no_return);
1195 return OK;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001196 }
1197 if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001198 Diag(ReturnStmts.back(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001199 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001200 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1201 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001202 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1203 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001204 }
1205 }
1206
Richard Smith74388b42012-02-04 00:33:54 +00001207 // C++11 [dcl.constexpr]p5:
1208 // if no function argument values exist such that the function invocation
1209 // substitution would produce a constant expression, the program is
1210 // ill-formed; no diagnostic required.
1211 // C++11 [dcl.constexpr]p3:
1212 // - every constructor call and implicit conversion used in initializing the
1213 // return value shall be one of those allowed in a constant expression.
1214 // C++11 [dcl.constexpr]p4:
1215 // - every constructor involved in initializing non-static data members and
1216 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001217 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00001218 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00001219 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00001220 << isa<CXXConstructorDecl>(Dcl);
1221 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1222 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00001223 // Don't return false here: we allow this for compatibility in
1224 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00001225 }
1226
Richard Smitheb3c10c2011-10-01 02:31:28 +00001227 return true;
1228}
1229
Douglas Gregor61956c42008-10-31 09:07:45 +00001230/// isCurrentClassName - Determine whether the identifier II is the
1231/// name of the class type currently being defined. In the case of
1232/// nested classes, this will only return true if II is the name of
1233/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001234bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1235 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001236 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00001237
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001238 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00001239 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00001240 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001241 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1242 } else
1243 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1244
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00001245 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00001246 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00001247 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00001248}
1249
Richard Smithfb8b7b92013-10-15 00:00:26 +00001250/// \brief Determine whether the identifier II is a typo for the name of
1251/// the class type currently being defined. If so, update it to the identifier
1252/// that should have been used.
1253bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1254 assert(getLangOpts().CPlusPlus && "No class names in C!");
1255
1256 if (!getLangOpts().SpellChecking)
1257 return false;
1258
1259 CXXRecordDecl *CurDecl;
1260 if (SS && SS->isSet() && !SS->isInvalid()) {
1261 DeclContext *DC = computeDeclContext(*SS, true);
1262 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1263 } else
1264 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1265
1266 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1267 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1268 < II->getLength()) {
1269 II = CurDecl->getIdentifier();
1270 return true;
1271 }
1272
1273 return false;
1274}
1275
Douglas Gregordc974572012-11-10 07:24:09 +00001276/// \brief Determine whether the given class is a base class of the given
1277/// class, including looking at dependent bases.
1278static bool findCircularInheritance(const CXXRecordDecl *Class,
1279 const CXXRecordDecl *Current) {
1280 SmallVector<const CXXRecordDecl*, 8> Queue;
1281
1282 Class = Class->getCanonicalDecl();
1283 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001284 for (const auto &I : Current->bases()) {
1285 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregordc974572012-11-10 07:24:09 +00001286 if (!Base)
1287 continue;
1288
1289 Base = Base->getDefinition();
1290 if (!Base)
1291 continue;
1292
1293 if (Base->getCanonicalDecl() == Class)
1294 return true;
1295
1296 Queue.push_back(Base);
1297 }
1298
1299 if (Queue.empty())
1300 return false;
1301
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001302 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00001303 }
1304
1305 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00001306}
1307
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00001308/// \brief Perform propagation of DLL attributes from a derived class to a
1309/// templated base class for MS compatibility.
1310static void propagateDLLAttrToBaseClassTemplate(
1311 Sema &S, CXXRecordDecl *Class, Attr *ClassAttr,
1312 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
1313 if (getDLLAttr(
1314 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
1315 // If the base class template has a DLL attribute, don't try to change it.
1316 return;
1317 }
1318
1319 if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
1320 // If the base class is not already specialized, we can do the propagation.
1321 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
1322 NewAttr->setInherited(true);
1323 BaseTemplateSpec->addAttr(NewAttr);
1324 return;
1325 }
1326
1327 bool DifferentAttribute = false;
1328 if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) {
1329 if (!SpecializationAttr->isInherited()) {
1330 // The template has previously been specialized or instantiated with an
1331 // explicit attribute. We should not try to change it.
1332 return;
1333 }
1334 if (SpecializationAttr->getKind() == ClassAttr->getKind()) {
1335 // The specialization already has the right attribute.
1336 return;
1337 }
1338 DifferentAttribute = true;
1339 }
1340
1341 // The template was previously instantiated or explicitly specialized without
1342 // a dll attribute, or the template was previously instantiated with a
1343 // different inherited attribute. It's too late for us to change the
1344 // attribute, so warn that this is unsupported.
1345 S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
1346 << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute;
1347 S.Diag(ClassAttr->getLocation(), diag::note_attribute);
1348 if (BaseTemplateSpec->isExplicitSpecialization()) {
1349 S.Diag(BaseTemplateSpec->getLocation(),
1350 diag::note_template_class_explicit_specialization_was_here)
1351 << BaseTemplateSpec;
1352 } else {
1353 S.Diag(BaseTemplateSpec->getPointOfInstantiation(),
1354 diag::note_template_class_instantiation_was_here)
1355 << BaseTemplateSpec;
1356 }
1357}
1358
Mike Stump11289f42009-09-09 15:08:12 +00001359/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001360///
1361/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1362/// and returns NULL otherwise.
1363CXXBaseSpecifier *
1364Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1365 SourceRange SpecifierRange,
1366 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001367 TypeSourceInfo *TInfo,
1368 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001369 QualType BaseType = TInfo->getType();
1370
Douglas Gregor463421d2009-03-03 04:44:36 +00001371 // C++ [class.union]p1:
1372 // A union shall not have base classes.
1373 if (Class->isUnion()) {
1374 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1375 << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001376 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001377 }
1378
Douglas Gregor752a5952011-01-03 22:36:02 +00001379 if (EllipsisLoc.isValid() &&
1380 !TInfo->getType()->containsUnexpandedParameterPack()) {
1381 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1382 << TInfo->getTypeLoc().getSourceRange();
1383 EllipsisLoc = SourceLocation();
1384 }
Douglas Gregor62004702012-11-10 01:18:17 +00001385
1386 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1387
1388 if (BaseType->isDependentType()) {
1389 // Make sure that we don't have circular inheritance among our dependent
1390 // bases. For non-dependent bases, the check for completeness below handles
1391 // this.
1392 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1393 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1394 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00001395 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00001396 Diag(BaseLoc, diag::err_circular_inheritance)
1397 << BaseType << Context.getTypeDeclType(Class);
1398
1399 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1400 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1401 << BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00001402
1403 return nullptr;
Douglas Gregor62004702012-11-10 01:18:17 +00001404 }
1405 }
1406
Mike Stump11289f42009-09-09 15:08:12 +00001407 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001408 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001409 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00001410 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001411
1412 // Base specifiers must be record types.
1413 if (!BaseType->isRecordType()) {
1414 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001415 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001416 }
1417
1418 // C++ [class.union]p1:
1419 // A union shall not be used as a base class.
1420 if (BaseType->isUnionType()) {
1421 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00001422 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00001423 }
1424
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00001425 // For the MS ABI, propagate DLL attributes to base class templates.
1426 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1427 if (Attr *ClassAttr = getDLLAttr(Class)) {
1428 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1429 BaseType->getAsCXXRecordDecl())) {
1430 propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr,
1431 BaseTemplate, BaseLoc);
1432 }
1433 }
1434 }
1435
Douglas Gregor463421d2009-03-03 04:44:36 +00001436 // C++ [class.derived]p2:
1437 // The class-name in a base-specifier shall not be an incompletely
1438 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001439 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001440 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00001441 Class->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00001442 return nullptr;
John McCall3696dcb2010-08-17 07:23:57 +00001443 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001444
Eli Friedmanc96d4962009-08-15 21:55:26 +00001445 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001446 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001447 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001448 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001449 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00001450 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00001451 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001452
David Majnemer9b1754d2013-11-02 12:00:36 +00001453 // A class which contains a flexible array member is not suitable for use as a
1454 // base class:
1455 // - If the layout determines that a base comes before another base,
1456 // the flexible array member would index into the subsequent base.
1457 // - If the layout determines that base comes before the derived class,
1458 // the flexible array member would index into the derived class.
1459 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1460 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1461 << CXXBaseDecl->getDeclName();
Craig Topperc3ec1492014-05-26 06:22:03 +00001462 return nullptr;
David Majnemer9b1754d2013-11-02 12:00:36 +00001463 }
1464
Anders Carlsson65c76d32011-03-25 14:55:14 +00001465 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00001466 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00001467 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00001468 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00001469 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00001470 << CXXBaseDecl->getDeclName()
1471 << FA->isSpelledAsSealed();
Alp Toker2afa8782014-05-28 12:20:14 +00001472 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1473 << CXXBaseDecl->getDeclName() << FA->getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00001474 return nullptr;
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001475 }
1476
John McCall3696dcb2010-08-17 07:23:57 +00001477 if (BaseDecl->isInvalidDecl())
1478 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00001479
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001480 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001481 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001482 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001483 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001484}
1485
Douglas Gregor556877c2008-04-13 21:30:24 +00001486/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1487/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001488/// example:
1489/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001490/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001491BaseResult
John McCall48871652010-08-21 09:40:31 +00001492Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00001493 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00001494 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001495 ParsedType basetype, SourceLocation BaseLoc,
1496 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001497 if (!classdecl)
1498 return true;
1499
Douglas Gregorc40290e2009-03-09 23:48:35 +00001500 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001501 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001502 if (!Class)
1503 return true;
1504
David Majnemer5ef4fe72014-06-13 06:43:46 +00001505 // We haven't yet attached the base specifiers.
1506 Class->setIsParsingBaseSpecifiers();
1507
Richard Smith4c96e992013-02-19 23:47:15 +00001508 // We do not support any C++11 attributes on base-specifiers yet.
1509 // Diagnose any attributes we see.
1510 if (!Attributes.empty()) {
1511 for (AttributeList *Attr = Attributes.getList(); Attr;
1512 Attr = Attr->getNext()) {
1513 if (Attr->isInvalid() ||
1514 Attr->getKind() == AttributeList::IgnoredAttribute)
1515 continue;
1516 Diag(Attr->getLoc(),
1517 Attr->getKind() == AttributeList::UnknownAttribute
1518 ? diag::warn_unknown_attribute_ignored
1519 : diag::err_base_specifier_attribute)
1520 << Attr->getName();
1521 }
1522 }
1523
Craig Topperc3ec1492014-05-26 06:22:03 +00001524 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00001525 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001526
Douglas Gregor752a5952011-01-03 22:36:02 +00001527 if (EllipsisLoc.isInvalid() &&
1528 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001529 UPPC_BaseType))
1530 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001531
Douglas Gregor463421d2009-03-03 04:44:36 +00001532 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001533 Virtual, Access, TInfo,
1534 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001535 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001536 else
1537 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001538
Douglas Gregor463421d2009-03-03 04:44:36 +00001539 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001540}
Douglas Gregor556877c2008-04-13 21:30:24 +00001541
Douglas Gregor463421d2009-03-03 04:44:36 +00001542/// \brief Performs the actual work of attaching the given base class
1543/// specifiers to a C++ class.
1544bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1545 unsigned NumBases) {
1546 if (NumBases == 0)
1547 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001548
1549 // Used to keep track of which base types we have already seen, so
1550 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001551 // that the key is always the unqualified canonical type of the base
1552 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001553 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1554
1555 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001556 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001557 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001558 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001559 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001560 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001561 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001562
1563 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1564 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00001565 // C++ [class.mi]p3:
1566 // A class shall not be specified as a direct base class of a
1567 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001568 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001569 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001570 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001571 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001572
1573 // Delete the duplicate base class specifier; we're going to
1574 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001575 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001576
1577 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001578 } else {
1579 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00001580 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00001581 Bases[NumGoodBases++] = Bases[idx];
John McCalldb632ac2012-09-25 07:32:39 +00001582 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1583 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1584 if (Class->isInterface() &&
1585 (!RD->isInterface() ||
1586 KnownBase->getAccessSpecifier() != AS_public)) {
1587 // The Microsoft extension __interface does not permit bases that
1588 // are not themselves public interfaces.
1589 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1590 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1591 << RD->getSourceRange();
1592 Invalid = true;
1593 }
1594 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00001595 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00001596 }
Douglas Gregor29a92472008-10-22 17:49:05 +00001597 }
1598 }
1599
1600 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001601 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001602
1603 // Delete the remaining (good) base class specifiers, since their
1604 // data has been copied into the CXXRecordDecl.
1605 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001606 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001607
1608 return Invalid;
1609}
1610
1611/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1612/// class, after checking whether there are any duplicate base
1613/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001614void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001615 unsigned NumBases) {
1616 if (!ClassDecl || !Bases || !NumBases)
1617 return;
1618
1619 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelme3cea802013-07-22 05:04:01 +00001620 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001621}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001622
Douglas Gregor36d1b142009-10-06 17:59:45 +00001623/// \brief Determine whether the type \p Derived is a C++ class that is
1624/// derived from the type \p Base.
1625bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001626 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001627 return false;
John McCalle78aac42010-03-10 03:28:59 +00001628
Douglas Gregor45bb4832013-03-26 23:36:30 +00001629 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001630 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001631 return false;
1632
Douglas Gregor45bb4832013-03-26 23:36:30 +00001633 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001634 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001635 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00001636
1637 // If either the base or the derived type is invalid, don't try to
1638 // check whether one is derived from the other.
1639 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1640 return false;
1641
John McCall67da35c2010-02-04 22:26:26 +00001642 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1643 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001644}
1645
1646/// \brief Determine whether the type \p Derived is a C++ class that is
1647/// derived from the type \p Base.
1648bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001649 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001650 return false;
1651
Douglas Gregor45bb4832013-03-26 23:36:30 +00001652 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001653 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001654 return false;
1655
Douglas Gregor45bb4832013-03-26 23:36:30 +00001656 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00001657 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001658 return false;
1659
Douglas Gregor36d1b142009-10-06 17:59:45 +00001660 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1661}
1662
Anders Carlssona70cff62010-04-24 19:06:50 +00001663void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001664 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001665 assert(BasePathArray.empty() && "Base path array must be empty!");
1666 assert(Paths.isRecordingPaths() && "Must record paths!");
1667
1668 const CXXBasePath &Path = Paths.front();
1669
1670 // We first go backward and check if we have a virtual base.
1671 // FIXME: It would be better if CXXBasePath had the base specifier for
1672 // the nearest virtual base.
1673 unsigned Start = 0;
1674 for (unsigned I = Path.size(); I != 0; --I) {
1675 if (Path[I - 1].Base->isVirtual()) {
1676 Start = I - 1;
1677 break;
1678 }
1679 }
1680
1681 // Now add all bases.
1682 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001683 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001684}
1685
Douglas Gregor88d292c2010-05-13 16:44:06 +00001686/// \brief Determine whether the given base path includes a virtual
1687/// base class.
John McCallcf142162010-08-07 06:22:56 +00001688bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1689 for (CXXCastPath::const_iterator B = BasePath.begin(),
1690 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +00001691 B != BEnd; ++B)
1692 if ((*B)->isVirtual())
1693 return true;
1694
1695 return false;
1696}
1697
Douglas Gregor36d1b142009-10-06 17:59:45 +00001698/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1699/// conversion (where Derived and Base are class types) is
1700/// well-formed, meaning that the conversion is unambiguous (and
1701/// that all of the base classes are accessible). Returns true
1702/// and emits a diagnostic if the code is ill-formed, returns false
1703/// otherwise. Loc is the location where this routine should point to
1704/// if there is an error, and Range is the source range to highlight
1705/// if there is an error.
1706bool
1707Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001708 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001709 unsigned AmbigiousBaseConvID,
1710 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001711 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001712 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001713 // First, determine whether the path from Derived to Base is
1714 // ambiguous. This is slightly more expensive than checking whether
1715 // the Derived to Base conversion exists, because here we need to
1716 // explore multiple paths to determine if there is an ambiguity.
1717 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1718 /*DetectVirtual=*/false);
1719 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1720 assert(DerivationOkay &&
1721 "Can only be used with a derived-to-base conversion");
1722 (void)DerivationOkay;
1723
1724 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001725 if (InaccessibleBaseID) {
1726 // Check that the base class can be accessed.
1727 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1728 InaccessibleBaseID)) {
1729 case AR_inaccessible:
1730 return true;
1731 case AR_accessible:
1732 case AR_dependent:
1733 case AR_delayed:
1734 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001735 }
John McCall5b0829a2010-02-10 09:31:12 +00001736 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001737
1738 // Build a base path if necessary.
1739 if (BasePath)
1740 BuildBasePathArray(Paths, *BasePath);
1741 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001742 }
1743
David Majnemer626032f2013-06-22 06:43:58 +00001744 if (AmbigiousBaseConvID) {
1745 // We know that the derived-to-base conversion is ambiguous, and
1746 // we're going to produce a diagnostic. Perform the derived-to-base
1747 // search just one more time to compute all of the possible paths so
1748 // that we can print them out. This is more expensive than any of
1749 // the previous derived-to-base checks we've done, but at this point
1750 // performance isn't as much of an issue.
1751 Paths.clear();
1752 Paths.setRecordingPaths(true);
1753 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1754 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1755 (void)StillOkay;
1756
1757 // Build up a textual representation of the ambiguous paths, e.g.,
1758 // D -> B -> A, that will be used to illustrate the ambiguous
1759 // conversions in the diagnostic. We only print one of the paths
1760 // to each base class subobject.
1761 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1762
1763 Diag(Loc, AmbigiousBaseConvID)
1764 << Derived << Base << PathDisplayStr << Range << Name;
1765 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00001766 return true;
1767}
1768
1769bool
1770Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001771 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001772 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001773 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001774 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001775 IgnoreAccess ? 0
1776 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001777 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001778 Loc, Range, DeclarationName(),
1779 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001780}
1781
1782
1783/// @brief Builds a string representing ambiguous paths from a
1784/// specific derived class to different subobjects of the same base
1785/// class.
1786///
1787/// This function builds a string that can be used in error messages
1788/// to show the different paths that one can take through the
1789/// inheritance hierarchy to go from the derived class to different
1790/// subobjects of a base class. The result looks something like this:
1791/// @code
1792/// struct D -> struct B -> struct A
1793/// struct D -> struct C -> struct A
1794/// @endcode
1795std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1796 std::string PathDisplayStr;
1797 std::set<unsigned> DisplayedPaths;
1798 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1799 Path != Paths.end(); ++Path) {
1800 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1801 // We haven't displayed a path to this particular base
1802 // class subobject yet.
1803 PathDisplayStr += "\n ";
1804 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1805 for (CXXBasePath::const_iterator Element = Path->begin();
1806 Element != Path->end(); ++Element)
1807 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1808 }
1809 }
1810
1811 return PathDisplayStr;
1812}
1813
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001814//===----------------------------------------------------------------------===//
1815// C++ class member Handling
1816//===----------------------------------------------------------------------===//
1817
Abramo Bagnarad7340582010-06-05 05:09:32 +00001818/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001819bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1820 SourceLocation ASLoc,
1821 SourceLocation ColonLoc,
1822 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001823 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001824 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001825 ASLoc, ColonLoc);
1826 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001827 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001828}
1829
Richard Smith18f07db2012-08-06 03:25:17 +00001830/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001831void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00001832 if (D->isInvalidDecl())
1833 return;
1834
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001835 // We only care about "override" and "final" declarations.
1836 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1837 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00001838
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001839 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001840
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001841 // We can't check dependent instance methods.
1842 if (MD && MD->isInstance() &&
1843 (MD->getParent()->hasAnyDependentBases() ||
1844 MD->getType()->isDependentType()))
1845 return;
1846
1847 if (MD && !MD->isVirtual()) {
1848 // If we have a non-virtual method, check if if hides a virtual method.
1849 // (In that case, it's most likely the method has the wrong type.)
1850 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1851 FindHiddenVirtualMethods(MD, OverloadedMethods);
1852
1853 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001854 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1855 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001856 diag::override_keyword_hides_virtual_member_function)
1857 << "override" << (OverloadedMethods.size() > 1);
1858 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00001859 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001860 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00001861 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1862 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00001863 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001864 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1865 MD->setInvalidDecl();
1866 return;
1867 }
1868 // Fall through into the general case diagnostic.
1869 // FIXME: We might want to attempt typo correction here.
1870 }
1871
1872 if (!MD || !MD->isVirtual()) {
1873 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1874 Diag(OA->getLocation(),
1875 diag::override_keyword_only_allowed_on_virtual_member_functions)
1876 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1877 D->dropAttr<OverrideAttr>();
1878 }
1879 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1880 Diag(FA->getLocation(),
1881 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00001882 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1883 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00001884 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00001885 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001886 return;
1887 }
Richard Smith18f07db2012-08-06 03:25:17 +00001888
Richard Smith18f07db2012-08-06 03:25:17 +00001889 // C++11 [class.virtual]p5:
1890 // If a virtual function is marked with the virt-specifier override and
1891 // does not override a member function of a base class, the program is
1892 // ill-formed.
1893 bool HasOverriddenMethods =
1894 MD->begin_overridden_methods() != MD->end_overridden_methods();
1895 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1896 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1897 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00001898}
1899
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00001900void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
1901 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
1902 return;
1903 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1904 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
1905 isa<CXXDestructorDecl>(MD))
1906 return;
1907
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00001908 SourceLocation Loc = MD->getLocation();
1909 SourceLocation SpellingLoc = Loc;
1910 if (getSourceManager().isMacroArgExpansion(Loc))
1911 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
1912 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
1913 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
Fariborz Jahanian6e213382014-10-31 19:56:27 +00001914 return;
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00001915
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00001916 if (MD->size_overridden_methods() > 0) {
1917 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
1918 << MD->getDeclName();
1919 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
1920 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
1921 }
1922}
1923
Richard Smith18f07db2012-08-06 03:25:17 +00001924/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00001925/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00001926/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00001927bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1928 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00001929 FinalAttr *FA = Old->getAttr<FinalAttr>();
1930 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00001931 return false;
1932
1933 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00001934 << New->getDeclName()
1935 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00001936 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1937 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001938}
1939
Daniel Jasper0baec5492012-06-06 08:32:04 +00001940static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00001941 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1942 // FIXME: Destruction of ObjC lifetime types has side-effects.
1943 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1944 return !RD->isCompleteDefinition() ||
1945 !RD->hasTrivialDefaultConstructor() ||
1946 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00001947 return false;
1948}
1949
John McCall5e77d762013-04-16 07:28:30 +00001950static AttributeList *getMSPropertyAttr(AttributeList *list) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001951 for (AttributeList *it = list; it != nullptr; it = it->getNext())
John McCall5e77d762013-04-16 07:28:30 +00001952 if (it->isDeclspecPropertyAttribute())
1953 return it;
Craig Topperc3ec1492014-05-26 06:22:03 +00001954 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +00001955}
1956
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001957/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1958/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001959/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00001960/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1961/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00001962NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001963Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001964 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001965 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00001966 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001967 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001968 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1969 DeclarationName Name = NameInfo.getName();
1970 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001971
1972 // For anonymous bitfields, the location should point to the type.
1973 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001974 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001975
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001976 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001977
John McCallb1cd7da2010-06-04 08:34:12 +00001978 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001979 assert(!DS.isFriendSpecified());
1980
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001981 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001982
John McCalldb632ac2012-09-25 07:32:39 +00001983 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1984 // The Microsoft extension __interface only permits public member functions
1985 // and prohibits constructors, destructors, operators, non-public member
1986 // functions, static methods and data members.
1987 unsigned InvalidDecl;
1988 bool ShowDeclName = true;
1989 if (!isFunc)
1990 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1991 else if (AS != AS_public)
1992 InvalidDecl = 2;
1993 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1994 InvalidDecl = 3;
1995 else switch (Name.getNameKind()) {
1996 case DeclarationName::CXXConstructorName:
1997 InvalidDecl = 4;
1998 ShowDeclName = false;
1999 break;
2000
2001 case DeclarationName::CXXDestructorName:
2002 InvalidDecl = 5;
2003 ShowDeclName = false;
2004 break;
2005
2006 case DeclarationName::CXXOperatorName:
2007 case DeclarationName::CXXConversionFunctionName:
2008 InvalidDecl = 6;
2009 break;
2010
2011 default:
2012 InvalidDecl = 0;
2013 break;
2014 }
2015
2016 if (InvalidDecl) {
2017 if (ShowDeclName)
2018 Diag(Loc, diag::err_invalid_member_in_interface)
2019 << (InvalidDecl-1) << Name;
2020 else
2021 Diag(Loc, diag::err_invalid_member_in_interface)
2022 << (InvalidDecl-1) << "";
Craig Topperc3ec1492014-05-26 06:22:03 +00002023 return nullptr;
John McCalldb632ac2012-09-25 07:32:39 +00002024 }
2025 }
2026
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002027 // C++ 9.2p6: A member shall not be declared to have automatic storage
2028 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002029 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2030 // data members and cannot be applied to names declared const or static,
2031 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002032 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00002033 case DeclSpec::SCS_unspecified:
2034 case DeclSpec::SCS_typedef:
2035 case DeclSpec::SCS_static:
2036 break;
2037 case DeclSpec::SCS_mutable:
2038 if (isFunc) {
2039 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00002040
Richard Smithb4a9e862013-04-12 22:46:28 +00002041 // FIXME: It would be nicer if the keyword was ignored only for this
2042 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002043 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00002044 }
2045 break;
2046 default:
2047 Diag(DS.getStorageClassSpecLoc(),
2048 diag::err_storageclass_invalid_for_member);
2049 D.getMutableDeclSpec().ClearStorageClassSpecs();
2050 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002051 }
2052
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002053 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2054 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00002055 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002056
David Blaikie35506f82013-01-30 01:22:18 +00002057 if (DS.isConstexprSpecified() && isInstField) {
2058 SemaDiagnosticBuilder B =
2059 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2060 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2061 if (InitStyle == ICIS_NoInit) {
Richard Smith82dce552014-04-14 21:00:40 +00002062 B << 0 << 0;
2063 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2064 B << FixItHint::CreateRemoval(ConstexprLoc);
2065 else {
2066 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2067 D.getMutableDeclSpec().ClearConstexprSpec();
2068 const char *PrevSpec;
2069 unsigned DiagID;
2070 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2071 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2072 (void)Failed;
2073 assert(!Failed && "Making a constexpr member const shouldn't fail");
2074 }
David Blaikie35506f82013-01-30 01:22:18 +00002075 } else {
2076 B << 1;
2077 const char *PrevSpec;
2078 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00002079 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002080 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2081 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00002082 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00002083 "This is the only DeclSpec that should fail to be applied");
2084 B << 1;
2085 } else {
2086 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2087 isInstField = false;
2088 }
2089 }
2090 }
2091
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002092 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00002093 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00002094 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002095
2096 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00002097 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002098 Diag(Loc, diag::err_bad_variable_name)
2099 << Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002100 return nullptr;
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002101 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002102
Benjamin Kramer365082d2012-05-19 16:34:46 +00002103 IdentifierInfo *II = Name.getAsIdentifierInfo();
2104
Douglas Gregor7c26c042011-09-21 14:40:46 +00002105 // Member field could not be with "template" keyword.
2106 // So TemplateParameterLists should be empty in this case.
2107 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002108 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002109 if (TemplateParams->size()) {
2110 // There is no such thing as a member field template.
2111 Diag(D.getIdentifierLoc(), diag::err_template_member)
2112 << II
2113 << SourceRange(TemplateParams->getTemplateLoc(),
2114 TemplateParams->getRAngleLoc());
2115 } else {
2116 // There is an extraneous 'template<>' for this member.
2117 Diag(TemplateParams->getTemplateLoc(),
2118 diag::err_template_member_noparams)
2119 << II
2120 << SourceRange(TemplateParams->getTemplateLoc(),
2121 TemplateParams->getRAngleLoc());
2122 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002123 return nullptr;
Douglas Gregor7c26c042011-09-21 14:40:46 +00002124 }
2125
Douglas Gregora007d362010-10-13 22:19:53 +00002126 if (SS.isSet() && !SS.isInvalid()) {
2127 // The user provided a superfluous scope specifier inside a class
2128 // definition:
2129 //
2130 // class X {
2131 // int X::member;
2132 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002133 if (DeclContext *DC = computeDeclContext(SS, false))
2134 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002135 else
2136 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2137 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002138
Douglas Gregora007d362010-10-13 22:19:53 +00002139 SS.clear();
2140 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002141
John McCall5e77d762013-04-16 07:28:30 +00002142 AttributeList *MSPropertyAttr =
2143 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002144 if (MSPropertyAttr) {
2145 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2146 BitWidth, InitStyle, AS, MSPropertyAttr);
2147 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002148 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002149 isInstField = false;
2150 } else {
2151 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2152 BitWidth, InitStyle, AS);
2153 assert(Member && "HandleField never returns null");
2154 }
2155 } else {
2156 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2157
2158 Member = HandleDeclarator(S, D, TemplateParameterLists);
2159 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002160 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002161
2162 // Non-instance-fields can't have a bitfield.
2163 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002164 if (Member->isInvalidDecl()) {
2165 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00002166 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002167 // C++ 9.6p3: A bit-field shall not be a static member.
2168 // "static member 'A' cannot be a bit-field"
2169 Diag(Loc, diag::err_static_not_bitfield)
2170 << Name << BitWidth->getSourceRange();
2171 } else if (isa<TypedefDecl>(Member)) {
2172 // "typedef member 'x' cannot be a bit-field"
2173 Diag(Loc, diag::err_typedef_not_bitfield)
2174 << Name << BitWidth->getSourceRange();
2175 } else {
2176 // A function typedef ("typedef int f(); f a;").
2177 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2178 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002179 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002180 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002181 }
Mike Stump11289f42009-09-09 15:08:12 +00002182
Craig Topperc3ec1492014-05-26 06:22:03 +00002183 BitWidth = nullptr;
Chris Lattnerd26760a2009-03-05 23:01:03 +00002184 Member->setInvalidDecl();
2185 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002186
2187 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002188
Larisse Voufo39a1e502013-08-06 01:03:05 +00002189 // If we have declared a member function template or static data member
2190 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002191 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2192 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002193 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2194 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00002195 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002196
Richard Smith18f07db2012-08-06 03:25:17 +00002197 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00002198 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00002199 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00002200 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2201 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00002202
Douglas Gregorf2f08062011-03-08 17:10:18 +00002203 if (VS.getLastLocation().isValid()) {
2204 // Update the end location of a method that has a virt-specifiers.
2205 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2206 MD->setRangeEnd(VS.getLastLocation());
2207 }
Richard Smith18f07db2012-08-06 03:25:17 +00002208
Anders Carlssonc87f8612011-01-20 06:29:02 +00002209 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00002210
Douglas Gregor92751d42008-11-17 22:58:34 +00002211 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002212
Daniel Jasper0baec5492012-06-06 08:32:04 +00002213 if (isInstField) {
2214 FieldDecl *FD = cast<FieldDecl>(Member);
2215 FieldCollector->Add(FD);
2216
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002217 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
Daniel Jasper0baec5492012-06-06 08:32:04 +00002218 // Remember all explicit private FieldDecls that have a name, no side
2219 // effects and are not part of a dependent type declaration.
2220 if (!FD->isImplicit() && FD->getDeclName() &&
2221 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00002222 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00002223 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00002224 !InitializationHasSideEffects(*FD))
2225 UnusedPrivateFields.insert(FD);
2226 }
2227 }
2228
John McCall48871652010-08-21 09:40:31 +00002229 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002230}
2231
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002232namespace {
2233 class UninitializedFieldVisitor
2234 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2235 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00002236 // List of Decls to generate a warning on. Also remove Decls that become
2237 // initialized.
Craig Topper4dd9b432014-08-17 23:49:53 +00002238 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
Richard Trieu8d08a272014-08-28 03:23:47 +00002239 // Vector of decls to be removed from the Decl set prior to visiting the
2240 // nodes. These Decls may have been initialized in the prior initializer.
2241 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
Richard Trieu406e65c2013-09-20 03:03:06 +00002242 // If non-null, add a note to the warning pointing back to the constructor.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00002243 const CXXConstructorDecl *Constructor;
Nick Lewycky314a4492014-10-17 22:45:44 +00002244 // Variables to hold state when processing an initializer list. When
Richard Trieufa1d0a72014-10-17 20:56:10 +00002245 // InitList is true, special case initialization of FieldDecls matching
2246 // InitListFieldDecl.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00002247 bool InitList;
2248 FieldDecl *InitListFieldDecl;
Richard Trieufa1d0a72014-10-17 20:56:10 +00002249 llvm::SmallVector<unsigned, 4> InitFieldIndex;
2250
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002251 public:
2252 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00002253 UninitializedFieldVisitor(Sema &S,
Richard Trieu8d08a272014-08-28 03:23:47 +00002254 llvm::SmallPtrSetImpl<ValueDecl*> &Decls)
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00002255 : Inherited(S.Context), S(S), Decls(Decls), Constructor(nullptr),
2256 InitList(false), InitListFieldDecl(nullptr) {}
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002257
Richard Trieufa1d0a72014-10-17 20:56:10 +00002258 // Returns true if the use of ME is not an uninitialized use.
2259 bool IsInitListMemberExprInitialized(MemberExpr *ME,
2260 bool CheckReferenceOnly) {
2261 llvm::SmallVector<FieldDecl*, 4> Fields;
2262 bool ReferenceField = false;
2263 while (ME) {
2264 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
2265 if (!FD)
2266 return false;
2267 Fields.push_back(FD);
2268 if (FD->getType()->isReferenceType())
2269 ReferenceField = true;
2270 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
2271 }
2272
2273 // Binding a reference to an unintialized field is not an
2274 // uninitialized use.
2275 if (CheckReferenceOnly && !ReferenceField)
2276 return true;
2277
2278 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
2279 // Discard the first field since it is the field decl that is being
2280 // initialized.
2281 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
2282 UsedFieldIndex.push_back((*I)->getFieldIndex());
2283 }
2284
2285 for (auto UsedIter = UsedFieldIndex.begin(),
2286 UsedEnd = UsedFieldIndex.end(),
2287 OrigIter = InitFieldIndex.begin(),
2288 OrigEnd = InitFieldIndex.end();
2289 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
2290 if (*UsedIter < *OrigIter)
2291 return true;
2292 if (*UsedIter > *OrigIter)
2293 break;
2294 }
2295
2296 return false;
2297 }
2298
Richard Trieu2d779b92014-10-01 03:44:58 +00002299 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
2300 bool AddressOf) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002301 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2302 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002303
Richard Trieu1bc22c12013-09-13 03:20:53 +00002304 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2305 // or union.
2306 MemberExpr *FieldME = ME;
2307
Richard Trieu2d779b92014-10-01 03:44:58 +00002308 bool AllPODFields = FieldME->getType().isPODType(S.Context);
2309
Richard Trieu1bc22c12013-09-13 03:20:53 +00002310 Expr *Base = ME;
Richard Trieufa1d0a72014-10-17 20:56:10 +00002311 while (MemberExpr *SubME = dyn_cast<MemberExpr>(Base)) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00002312
Richard Trieufa1d0a72014-10-17 20:56:10 +00002313 if (isa<VarDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00002314 return;
2315
Richard Trieufa1d0a72014-10-17 20:56:10 +00002316 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00002317 if (!FD->isAnonymousStructOrUnion())
Richard Trieufa1d0a72014-10-17 20:56:10 +00002318 FieldME = SubME;
Richard Trieu1bc22c12013-09-13 03:20:53 +00002319
Richard Trieu2d779b92014-10-01 03:44:58 +00002320 if (!FieldME->getType().isPODType(S.Context))
2321 AllPODFields = false;
2322
Richard Trieufa1d0a72014-10-17 20:56:10 +00002323 Base = SubME->getBase()->IgnoreParenImpCasts();
Richard Trieu1bc22c12013-09-13 03:20:53 +00002324 }
2325
Richard Trieufd687772013-09-16 20:46:50 +00002326 if (!isa<CXXThisExpr>(Base))
2327 return;
2328
Richard Trieu2d779b92014-10-01 03:44:58 +00002329 if (AddressOf && AllPODFields)
2330 return;
2331
Richard Trieu406e65c2013-09-20 03:03:06 +00002332 ValueDecl* FoundVD = FieldME->getMemberDecl();
2333
Richard Trieuef64e942013-10-25 00:56:00 +00002334 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00002335 return;
2336
Richard Trieuef64e942013-10-25 00:56:00 +00002337 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00002338
Richard Trieufa1d0a72014-10-17 20:56:10 +00002339 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
2340 // Special checking for initializer lists.
2341 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
2342 return;
2343 }
2344 } else {
2345 // Prevent double warnings on use of unbounded references.
2346 if (CheckReferenceOnly && !IsReference)
2347 return;
2348 }
Richard Trieuef64e942013-10-25 00:56:00 +00002349
2350 unsigned diag = IsReference
2351 ? diag::warn_reference_field_is_uninit
2352 : diag::warn_field_is_uninit;
2353 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2354 if (Constructor)
2355 S.Diag(Constructor->getLocation(),
2356 diag::note_uninit_in_this_constructor)
2357 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2358
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002359 }
2360
Richard Trieu2d779b92014-10-01 03:44:58 +00002361 void HandleValue(Expr *E, bool AddressOf) {
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002362 E = E->IgnoreParens();
2363
2364 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002365 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
2366 AddressOf /*AddressOf*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00002367 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002368 }
2369
2370 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002371 Visit(CO->getCond());
2372 HandleValue(CO->getTrueExpr(), AddressOf);
2373 HandleValue(CO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002374 return;
2375 }
2376
2377 if (BinaryConditionalOperator *BCO =
2378 dyn_cast<BinaryConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002379 Visit(BCO->getCond());
2380 HandleValue(BCO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002381 return;
2382 }
2383
Richard Trieuabf6ec42014-08-27 22:15:10 +00002384 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002385 HandleValue(OVE->getSourceExpr(), AddressOf);
Richard Trieuabf6ec42014-08-27 22:15:10 +00002386 return;
2387 }
2388
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002389 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2390 switch (BO->getOpcode()) {
2391 default:
Richard Trieu2d779b92014-10-01 03:44:58 +00002392 break;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002393 case(BO_PtrMemD):
2394 case(BO_PtrMemI):
Richard Trieu2d779b92014-10-01 03:44:58 +00002395 HandleValue(BO->getLHS(), AddressOf);
2396 Visit(BO->getRHS());
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002397 return;
2398 case(BO_Comma):
Richard Trieu2d779b92014-10-01 03:44:58 +00002399 Visit(BO->getLHS());
2400 HandleValue(BO->getRHS(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002401 return;
2402 }
2403 }
Richard Trieu2d779b92014-10-01 03:44:58 +00002404
2405 Visit(E);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002406 }
2407
Richard Trieufa1d0a72014-10-17 20:56:10 +00002408 void CheckInitListExpr(InitListExpr *ILE) {
2409 InitFieldIndex.push_back(0);
2410 for (auto Child : ILE->children()) {
2411 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
2412 CheckInitListExpr(SubList);
2413 } else {
2414 Visit(Child);
2415 }
2416 ++InitFieldIndex.back();
2417 }
2418 InitFieldIndex.pop_back();
2419 }
2420
Richard Trieu8d08a272014-08-28 03:23:47 +00002421 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
2422 FieldDecl *Field) {
2423 // Remove Decls that may have been initialized in the previous
2424 // initializer.
2425 for (ValueDecl* VD : DeclsToRemove)
2426 Decls.erase(VD);
Richard Trieu8d08a272014-08-28 03:23:47 +00002427 DeclsToRemove.clear();
Richard Trieufa1d0a72014-10-17 20:56:10 +00002428
Richard Trieu8d08a272014-08-28 03:23:47 +00002429 Constructor = FieldConstructor;
Richard Trieufa1d0a72014-10-17 20:56:10 +00002430 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
2431
2432 if (ILE && Field) {
2433 InitList = true;
2434 InitListFieldDecl = Field;
2435 InitFieldIndex.clear();
2436 CheckInitListExpr(ILE);
2437 } else {
2438 InitList = false;
2439 Visit(E);
2440 }
2441
Richard Trieu8d08a272014-08-28 03:23:47 +00002442 if (Field)
2443 Decls.erase(Field);
2444 }
2445
Richard Trieu1bc22c12013-09-13 03:20:53 +00002446 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00002447 // All uses of unbounded reference fields will warn.
Richard Trieu2d779b92014-10-01 03:44:58 +00002448 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00002449 }
2450
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002451 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002452 if (E->getCastKind() == CK_LValueToRValue) {
2453 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2454 return;
2455 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002456
2457 Inherited::VisitImplicitCastExpr(E);
2458 }
2459
Richard Trieu1bc22c12013-09-13 03:20:53 +00002460 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu4834ad22014-08-12 21:05:04 +00002461 if (E->getConstructor()->isCopyConstructor()) {
2462 Expr *ArgExpr = E->getArg(0);
Richard Trieu2d779b92014-10-01 03:44:58 +00002463 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
2464 if (ILE->getNumInits() == 1)
2465 ArgExpr = ILE->getInit(0);
2466 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
2467 if (ICE->getCastKind() == CK_NoOp)
Richard Trieu4834ad22014-08-12 21:05:04 +00002468 ArgExpr = ICE->getSubExpr();
Richard Trieu2d779b92014-10-01 03:44:58 +00002469 HandleValue(ArgExpr, false /*AddressOf*/);
2470 return;
Richard Trieu4834ad22014-08-12 21:05:04 +00002471 }
Richard Trieu1bc22c12013-09-13 03:20:53 +00002472 Inherited::VisitCXXConstructExpr(E);
2473 }
2474
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002475 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2476 Expr *Callee = E->getCallee();
Richard Trieu2d779b92014-10-01 03:44:58 +00002477 if (isa<MemberExpr>(Callee)) {
2478 HandleValue(Callee, false /*AddressOf*/);
Richard Trieu46847422014-11-01 00:46:54 +00002479 for (auto Arg : E->arguments())
2480 Visit(Arg);
Richard Trieu2d779b92014-10-01 03:44:58 +00002481 return;
2482 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002483
2484 Inherited::VisitCXXMemberCallExpr(E);
2485 }
Richard Trieu406e65c2013-09-20 03:03:06 +00002486
Richard Trieu11fd0792014-08-26 04:30:55 +00002487 void VisitCallExpr(CallExpr *E) {
2488 // Treat std::move as a use.
2489 if (E->getNumArgs() == 1) {
2490 if (FunctionDecl *FD = E->getDirectCallee()) {
2491 if (FD->getIdentifier() && FD->getIdentifier()->isStr("move")) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002492 HandleValue(E->getArg(0), false /*AddressOf*/);
2493 return;
Richard Trieu11fd0792014-08-26 04:30:55 +00002494 }
2495 }
2496 }
2497
2498 Inherited::VisitCallExpr(E);
2499 }
2500
Richard Trieud4a01362014-10-31 21:10:22 +00002501 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
2502 Expr *Callee = E->getCallee();
2503
2504 if (isa<UnresolvedLookupExpr>(Callee))
2505 return Inherited::VisitCXXOperatorCallExpr(E);
2506
2507 Visit(Callee);
2508 for (auto Arg : E->arguments())
2509 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
2510 }
2511
Richard Trieu406e65c2013-09-20 03:03:06 +00002512 void VisitBinaryOperator(BinaryOperator *E) {
2513 // If a field assignment is detected, remove the field from the
2514 // uninitiailized field set.
2515 if (E->getOpcode() == BO_Assign)
2516 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2517 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00002518 if (!FD->getType()->isReferenceType())
Richard Trieu8d08a272014-08-28 03:23:47 +00002519 DeclsToRemove.push_back(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00002520
Richard Trieu52b8b602014-09-25 01:15:40 +00002521 if (E->isCompoundAssignmentOp()) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002522 HandleValue(E->getLHS(), false /*AddressOf*/);
2523 Visit(E->getRHS());
2524 return;
Richard Trieu52b8b602014-09-25 01:15:40 +00002525 }
2526
Richard Trieu406e65c2013-09-20 03:03:06 +00002527 Inherited::VisitBinaryOperator(E);
2528 }
Richard Trieu52b8b602014-09-25 01:15:40 +00002529
2530 void VisitUnaryOperator(UnaryOperator *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00002531 if (E->isIncrementDecrementOp()) {
2532 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2533 return;
2534 }
2535 if (E->getOpcode() == UO_AddrOf) {
2536 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
2537 HandleValue(ME->getBase(), true /*AddressOf*/);
2538 return;
2539 }
2540 }
Richard Trieu52b8b602014-09-25 01:15:40 +00002541
2542 Inherited::VisitUnaryOperator(E);
2543 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002544 };
Richard Trieuef64e942013-10-25 00:56:00 +00002545
2546 // Diagnose value-uses of fields to initialize themselves, e.g.
2547 // foo(foo)
2548 // where foo is not also a parameter to the constructor.
2549 // Also diagnose across field uninitialized use such as
2550 // x(y), y(x)
2551 // TODO: implement -Wuninitialized and fold this into that framework.
2552 static void DiagnoseUninitializedFields(
2553 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2554
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002555 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2556 Constructor->getLocation())) {
Richard Trieuef64e942013-10-25 00:56:00 +00002557 return;
2558 }
2559
2560 if (Constructor->isInvalidDecl())
2561 return;
2562
2563 const CXXRecordDecl *RD = Constructor->getParent();
2564
Richard Trieu353a4b42014-10-22 05:21:59 +00002565 if (RD->getDescribedClassTemplate())
Richard Trieu277ace02014-10-22 02:52:00 +00002566 return;
2567
Richard Trieuef64e942013-10-25 00:56:00 +00002568 // Holds fields that are uninitialized.
2569 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2570
2571 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00002572 for (auto *I : RD->decls()) {
2573 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002574 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00002575 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00002576 UninitializedFields.insert(IFD->getAnonField());
2577 }
2578 }
2579
Richard Trieu8d08a272014-08-28 03:23:47 +00002580 if (UninitializedFields.empty())
2581 return;
2582
2583 UninitializedFieldVisitor UninitializedChecker(SemaRef,
2584 UninitializedFields);
2585
Aaron Ballman0ad78302014-03-13 17:34:31 +00002586 for (const auto *FieldInit : Constructor->inits()) {
Richard Trieu8d08a272014-08-28 03:23:47 +00002587 if (UninitializedFields.empty())
2588 break;
2589
Aaron Ballman0ad78302014-03-13 17:34:31 +00002590 Expr *InitExpr = FieldInit->getInit();
Richard Trieu8d08a272014-08-28 03:23:47 +00002591 if (!InitExpr)
2592 continue;
Richard Trieuef64e942013-10-25 00:56:00 +00002593
Richard Trieu8d08a272014-08-28 03:23:47 +00002594 if (CXXDefaultInitExpr *Default =
2595 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
2596 InitExpr = Default->getExpr();
2597 if (!InitExpr)
2598 continue;
2599 // In class initializers will point to the constructor.
2600 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
2601 FieldInit->getAnyMember());
2602 } else {
2603 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
2604 FieldInit->getAnyMember());
2605 }
Richard Trieuef64e942013-10-25 00:56:00 +00002606 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00002607 }
2608} // namespace
2609
Richard Smith74108172014-01-17 03:11:34 +00002610/// \brief Enter a new C++ default initializer scope. After calling this, the
2611/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2612/// parsing or instantiating the initializer failed.
2613void Sema::ActOnStartCXXInClassMemberInitializer() {
2614 // Create a synthetic function scope to represent the call to the constructor
2615 // that notionally surrounds a use of this initializer.
2616 PushFunctionScope();
2617}
2618
2619/// \brief This is invoked after parsing an in-class initializer for a
2620/// non-static C++ class member, and after instantiating an in-class initializer
2621/// in a class template. Such actions are deferred until the class is complete.
2622void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2623 SourceLocation InitLoc,
2624 Expr *InitExpr) {
2625 // Pop the notional constructor scope we created earlier.
Craig Topperc3ec1492014-05-26 06:22:03 +00002626 PopFunctionScopeInfo(nullptr, D);
Richard Smith74108172014-01-17 03:11:34 +00002627
Richard Smith938f40b2011-06-11 17:19:42 +00002628 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smith2b013182012-06-10 03:12:00 +00002629 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2630 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00002631
2632 if (!InitExpr) {
2633 FD->setInvalidDecl();
2634 FD->removeInClassInitializer();
2635 return;
2636 }
2637
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002638 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2639 FD->setInvalidDecl();
2640 FD->removeInClassInitializer();
2641 return;
2642 }
2643
Richard Smith938f40b2011-06-11 17:19:42 +00002644 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00002645 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00002646 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00002647 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00002648 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00002649 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002650 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2651 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00002652 if (Init.isInvalid()) {
2653 FD->setInvalidDecl();
2654 return;
2655 }
Richard Smith938f40b2011-06-11 17:19:42 +00002656 }
2657
Richard Smith945f8d32013-01-14 22:39:08 +00002658 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00002659 // The initialization of each base and member constitutes a
2660 // full-expression.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002661 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00002662 if (Init.isInvalid()) {
2663 FD->setInvalidDecl();
2664 return;
2665 }
2666
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002667 InitExpr = Init.get();
Richard Smith938f40b2011-06-11 17:19:42 +00002668
2669 FD->setInClassInitializer(InitExpr);
2670}
2671
Douglas Gregor15e77a22009-12-31 09:10:24 +00002672/// \brief Find the direct and/or virtual base specifiers that
2673/// correspond to the given base type, for use in base initialization
2674/// within a constructor.
2675static bool FindBaseInitializer(Sema &SemaRef,
2676 CXXRecordDecl *ClassDecl,
2677 QualType BaseType,
2678 const CXXBaseSpecifier *&DirectBaseSpec,
2679 const CXXBaseSpecifier *&VirtualBaseSpec) {
2680 // First, check for a direct base class.
Craig Topperc3ec1492014-05-26 06:22:03 +00002681 DirectBaseSpec = nullptr;
Aaron Ballman574705e2014-03-13 15:41:46 +00002682 for (const auto &Base : ClassDecl->bases()) {
2683 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002684 // We found a direct base of this type. That's what we're
2685 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00002686 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002687 break;
2688 }
2689 }
2690
2691 // Check for a virtual base class.
2692 // FIXME: We might be able to short-circuit this if we know in advance that
2693 // there are no virtual bases.
Craig Topperc3ec1492014-05-26 06:22:03 +00002694 VirtualBaseSpec = nullptr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00002695 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2696 // We haven't found a base yet; search the class hierarchy for a
2697 // virtual base class.
2698 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2699 /*DetectVirtual=*/false);
2700 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2701 BaseType, Paths)) {
2702 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2703 Path != Paths.end(); ++Path) {
2704 if (Path->back().Base->isVirtual()) {
2705 VirtualBaseSpec = Path->back().Base;
2706 break;
2707 }
2708 }
2709 }
2710 }
2711
2712 return DirectBaseSpec || VirtualBaseSpec;
2713}
2714
Sebastian Redla74948d2011-09-24 17:48:25 +00002715/// \brief Handle a C++ member initializer using braced-init-list syntax.
2716MemInitResult
2717Sema::ActOnMemInitializer(Decl *ConstructorD,
2718 Scope *S,
2719 CXXScopeSpec &SS,
2720 IdentifierInfo *MemberOrBase,
2721 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002722 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002723 SourceLocation IdLoc,
2724 Expr *InitList,
2725 SourceLocation EllipsisLoc) {
2726 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002727 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00002728 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002729}
2730
2731/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00002732MemInitResult
John McCall48871652010-08-21 09:40:31 +00002733Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00002734 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00002735 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002736 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00002737 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002738 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00002739 SourceLocation IdLoc,
2740 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002741 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002742 SourceLocation RParenLoc,
2743 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00002744 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00002745 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002746 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00002747 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00002748}
2749
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002750namespace {
2751
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00002752// Callback to only accept typo corrections that can be a valid C++ member
2753// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002754class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002755public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002756 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2757 : ClassDecl(ClassDecl) {}
2758
Craig Toppera798a9d2014-03-02 09:32:10 +00002759 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002760 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2761 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2762 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002763 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002764 }
2765 return false;
2766 }
2767
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002768private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002769 CXXRecordDecl *ClassDecl;
2770};
2771
2772}
2773
Sebastian Redla74948d2011-09-24 17:48:25 +00002774/// \brief Handle a C++ member initializer.
2775MemInitResult
2776Sema::BuildMemInitializer(Decl *ConstructorD,
2777 Scope *S,
2778 CXXScopeSpec &SS,
2779 IdentifierInfo *MemberOrBase,
2780 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00002781 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00002782 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00002783 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002784 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002785 if (!ConstructorD)
2786 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002787
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002788 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00002789
2790 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002791 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00002792 if (!Constructor) {
2793 // The user wrote a constructor initializer on a function that is
2794 // not a C++ constructor. Ignore the error for now, because we may
2795 // have more member initializers coming; we'll diagnose it just
2796 // once in ActOnMemInitializers.
2797 return true;
2798 }
2799
2800 CXXRecordDecl *ClassDecl = Constructor->getParent();
2801
2802 // C++ [class.base.init]p2:
2803 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00002804 // constructor's class and, if not found in that scope, are looked
2805 // up in the scope containing the constructor's definition.
2806 // [Note: if the constructor's class contains a member with the
2807 // same name as a direct or virtual base class of the class, a
2808 // mem-initializer-id naming the member or base class and composed
2809 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00002810 // mem-initializer-id for the hidden base class may be specified
2811 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00002812 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002813 // Look for a member, first.
Mike Stump11289f42009-09-09 15:08:12 +00002814 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00002815 = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00002816 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00002817 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00002818 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2819 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00002820 if (EllipsisLoc.isValid())
2821 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00002822 << MemberOrBase
2823 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00002824
Sebastian Redla9351792012-02-11 23:51:47 +00002825 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00002826 }
Francois Pichetd583da02010-12-04 09:14:42 +00002827 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002828 }
Douglas Gregore8381c02008-11-05 04:29:56 +00002829 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002830 QualType BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002831 TypeSourceInfo *TInfo = nullptr;
John McCallb5a0d312009-12-21 10:41:20 +00002832
2833 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00002834 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00002835 } else if (DS.getTypeSpecType() == TST_decltype) {
2836 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00002837 } else {
2838 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2839 LookupParsedName(R, S, &SS);
2840
2841 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2842 if (!TyD) {
2843 if (R.isAmbiguous()) return true;
2844
John McCallda6841b2010-04-09 19:01:14 +00002845 // We don't want access-control diagnostics here.
2846 R.suppressDiagnostics();
2847
Douglas Gregora3b624a2010-01-19 06:46:48 +00002848 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2849 bool NotUnknownSpecialization = false;
2850 DeclContext *DC = computeDeclContext(SS, false);
2851 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2852 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2853
2854 if (!NotUnknownSpecialization) {
2855 // When the scope specifier can refer to a member of an unknown
2856 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00002857 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2858 SS.getWithLocInContext(Context),
2859 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00002860 if (BaseType.isNull())
2861 return true;
2862
Douglas Gregora3b624a2010-01-19 06:46:48 +00002863 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00002864 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00002865 }
2866 }
2867
Douglas Gregor15e77a22009-12-31 09:10:24 +00002868 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002869 TypoCorrection Corr;
Douglas Gregora3b624a2010-01-19 06:46:48 +00002870 if (R.empty() && BaseType.isNull() &&
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002871 (Corr = CorrectTypo(
2872 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2873 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
2874 CTK_ErrorRecovery, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002875 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00002876 // We have found a non-static data member with a similar
2877 // name to what was typed; complain and initialize that
2878 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00002879 diagnoseTypo(Corr,
2880 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2881 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00002882 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00002883 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002884 const CXXBaseSpecifier *DirectBaseSpec;
2885 const CXXBaseSpecifier *VirtualBaseSpec;
2886 if (FindBaseInitializer(*this, ClassDecl,
2887 Context.getTypeDeclType(Type),
2888 DirectBaseSpec, VirtualBaseSpec)) {
2889 // We have found a direct or virtual base class with a
2890 // similar name to what was typed; complain and initialize
2891 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00002892 diagnoseTypo(Corr,
2893 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2894 << MemberOrBase << false,
2895 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00002896
Richard Smithf9b15102013-08-17 00:46:16 +00002897 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2898 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002899 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00002900 diag::note_base_class_specified_here)
2901 << BaseSpec->getType()
2902 << BaseSpec->getSourceRange();
2903
Douglas Gregor15e77a22009-12-31 09:10:24 +00002904 TyD = Type;
2905 }
2906 }
2907 }
2908
Douglas Gregora3b624a2010-01-19 06:46:48 +00002909 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00002910 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00002911 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00002912 return true;
2913 }
John McCallb5a0d312009-12-21 10:41:20 +00002914 }
2915
Douglas Gregora3b624a2010-01-19 06:46:48 +00002916 if (BaseType.isNull()) {
2917 BaseType = Context.getTypeDeclType(TyD);
Aaron Ballman4a979672014-01-03 13:56:08 +00002918 if (SS.isSet())
Douglas Gregora3b624a2010-01-19 06:46:48 +00002919 // FIXME: preserve source range information
Aaron Ballman4a979672014-01-03 13:56:08 +00002920 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2921 BaseType);
John McCallb5a0d312009-12-21 10:41:20 +00002922 }
2923 }
Mike Stump11289f42009-09-09 15:08:12 +00002924
John McCallbcd03502009-12-07 02:54:59 +00002925 if (!TInfo)
2926 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002927
Sebastian Redla9351792012-02-11 23:51:47 +00002928 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00002929}
2930
Chandler Carruth599deef2011-09-03 01:14:15 +00002931/// Checks a member initializer expression for cases where reference (or
2932/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00002933static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2934 Expr *Init,
2935 SourceLocation IdLoc) {
2936 QualType MemberTy = Member->getType();
2937
2938 // We only handle pointers and references currently.
2939 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2940 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2941 return;
2942
2943 const bool IsPointer = MemberTy->isPointerType();
2944 if (IsPointer) {
2945 if (const UnaryOperator *Op
2946 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2947 // The only case we're worried about with pointers requires taking the
2948 // address.
2949 if (Op->getOpcode() != UO_AddrOf)
2950 return;
2951
2952 Init = Op->getSubExpr();
2953 } else {
2954 // We only handle address-of expression initializers for pointers.
2955 return;
2956 }
2957 }
2958
Richard Smithe3b28bc2013-06-12 21:51:50 +00002959 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002960 // We only warn when referring to a non-reference parameter declaration.
2961 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2962 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00002963 return;
2964
2965 S.Diag(Init->getExprLoc(),
2966 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2967 : diag::warn_bind_ref_member_to_parameter)
2968 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002969 } else {
2970 // Other initializers are fine.
2971 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00002972 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002973
2974 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2975 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00002976}
2977
John McCallfaf5fb42010-08-26 23:41:50 +00002978MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00002979Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00002980 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002981 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2982 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2983 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00002984 "Member must be a FieldDecl or IndirectFieldDecl");
2985
Sebastian Redla9351792012-02-11 23:51:47 +00002986 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002987 return true;
2988
Douglas Gregor266bb5f2010-11-05 22:21:31 +00002989 if (Member->isInvalidDecl())
2990 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00002991
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002992 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00002993 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002994 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00002995 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002996 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00002997 } else {
2998 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00002999 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003000 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00003001
Sebastian Redla9351792012-02-11 23:51:47 +00003002 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00003003
Sebastian Redla9351792012-02-11 23:51:47 +00003004 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003005 // Can't check initialization for a member of dependent type or when
3006 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00003007 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00003008 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00003009 bool InitList = false;
3010 if (isa<InitListExpr>(Init)) {
3011 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003012 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003013 }
3014
Chandler Carruthd44c3102010-12-06 09:23:57 +00003015 // Initialize the member.
3016 InitializedEntity MemberEntity =
Craig Topperc3ec1492014-05-26 06:22:03 +00003017 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3018 : InitializedEntity::InitializeMember(IndirectMember,
3019 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003020 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003021 InitList ? InitializationKind::CreateDirectList(IdLoc)
3022 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3023 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00003024
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003025 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003026 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3027 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003028 if (MemberInit.isInvalid())
3029 return true;
3030
Richard Smith736a9472013-06-12 20:42:33 +00003031 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3032
Richard Smith945f8d32013-01-14 22:39:08 +00003033 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00003034 // The initialization of each base and member constitutes a
3035 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003036 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003037 if (MemberInit.isInvalid())
3038 return true;
3039
Richard Smithd59b8322012-12-19 01:39:02 +00003040 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003041 }
3042
Chandler Carruthd44c3102010-12-06 09:23:57 +00003043 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00003044 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3045 InitRange.getBegin(), Init,
3046 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003047 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00003048 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3049 InitRange.getBegin(), Init,
3050 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003051 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00003052}
3053
John McCallfaf5fb42010-08-26 23:41:50 +00003054MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003055Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00003056 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003057 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003058 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003059 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003060 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003061 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00003062
Sebastian Redl0501c632012-02-12 16:37:36 +00003063 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003064 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003065 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3066 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003067 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00003068 }
3069
Sebastian Redla9351792012-02-11 23:51:47 +00003070 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00003071 // Initialize the object.
3072 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3073 QualType(ClassDecl->getTypeForDecl(), 0));
3074 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003075 InitList ? InitializationKind::CreateDirectList(NameLoc)
3076 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3077 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003078 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00003079 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Craig Topperc3ec1492014-05-26 06:22:03 +00003080 Args, nullptr);
Alexis Huntc5575cc2011-02-26 19:13:13 +00003081 if (DelegationInit.isInvalid())
3082 return true;
3083
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00003084 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3085 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00003086
Richard Smith945f8d32013-01-14 22:39:08 +00003087 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00003088 // The initialization of each base and member constitutes a
3089 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003090 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3091 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00003092 if (DelegationInit.isInvalid())
3093 return true;
3094
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00003095 // If we are in a dependent context, template instantiation will
3096 // perform this type-checking again. Just save the arguments that we
3097 // received in a ParenListExpr.
3098 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3099 // of the information that we have about the base
3100 // initializer. However, deconstructing the ASTs is a dicey process,
3101 // and this approach is far more likely to get the corner cases right.
3102 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003103 DelegationInit = Init;
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00003104
Sebastian Redla9351792012-02-11 23:51:47 +00003105 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003106 DelegationInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003107 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003108}
3109
3110MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00003111Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00003112 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00003113 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003114 SourceLocation BaseLoc
3115 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00003116
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003117 if (!BaseType->isDependentType() && !BaseType->isRecordType())
3118 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3119 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3120
3121 // C++ [class.base.init]p2:
3122 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00003123 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003124 // of that class, the mem-initializer is ill-formed. A
3125 // mem-initializer-list can initialize a base class using any
3126 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00003127 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003128
Sebastian Redla9351792012-02-11 23:51:47 +00003129 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00003130 if (EllipsisLoc.isValid()) {
3131 // This is a pack expansion.
3132 if (!BaseType->containsUnexpandedParameterPack()) {
3133 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00003134 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00003135
Douglas Gregor44e7df62011-01-04 00:32:56 +00003136 EllipsisLoc = SourceLocation();
3137 }
3138 } else {
3139 // Check for any unexpanded parameter packs.
3140 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3141 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00003142
Sebastian Redla9351792012-02-11 23:51:47 +00003143 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00003144 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00003145 }
Sebastian Redla74948d2011-09-24 17:48:25 +00003146
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003147 // Check for direct and virtual base classes.
Craig Topperc3ec1492014-05-26 06:22:03 +00003148 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3149 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003150 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003151 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3152 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00003153 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003154
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003155 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
3156 VirtualBaseSpec);
3157
3158 // C++ [base.class.init]p2:
3159 // Unless the mem-initializer-id names a nonstatic data member of the
3160 // constructor's class or a direct or virtual base of that class, the
3161 // mem-initializer is ill-formed.
3162 if (!DirectBaseSpec && !VirtualBaseSpec) {
3163 // If the class has any dependent bases, then it's possible that
3164 // one of those types will resolve to the same type as
3165 // BaseType. Therefore, just treat this as a dependent base
3166 // class initialization. FIXME: Should we try to check the
3167 // initialization anyway? It seems odd.
3168 if (ClassDecl->hasAnyDependentBases())
3169 Dependent = true;
3170 else
3171 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
3172 << BaseType << Context.getTypeDeclType(ClassDecl)
3173 << BaseTInfo->getTypeLoc().getLocalSourceRange();
3174 }
3175 }
3176
3177 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00003178 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00003179
Sebastian Redla74948d2011-09-24 17:48:25 +00003180 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3181 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00003182 InitRange.getBegin(), Init,
3183 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003184 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003185
3186 // C++ [base.class.init]p2:
3187 // If a mem-initializer-id is ambiguous because it designates both
3188 // a direct non-virtual base class and an inherited virtual base
3189 // class, the mem-initializer is ill-formed.
3190 if (DirectBaseSpec && VirtualBaseSpec)
3191 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00003192 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003193
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003194 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003195 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003196 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003197
3198 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00003199 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003200 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003201 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00003202 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003203 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00003204 }
Sebastian Redl0501c632012-02-12 16:37:36 +00003205
3206 InitializedEntity BaseEntity =
3207 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3208 InitializationKind Kind =
3209 InitList ? InitializationKind::CreateDirectList(BaseLoc)
3210 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3211 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003212 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003213 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003214 if (BaseInit.isInvalid())
3215 return true;
John McCallacf0ee52010-10-08 02:01:28 +00003216
Richard Smith945f8d32013-01-14 22:39:08 +00003217 // C++11 [class.base.init]p7:
3218 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003219 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003220 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003221 if (BaseInit.isInvalid())
3222 return true;
3223
3224 // If we are in a dependent context, template instantiation will
3225 // perform this type-checking again. Just save the arguments that we
3226 // received in a ParenListExpr.
3227 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3228 // of the information that we have about the base
3229 // initializer. However, deconstructing the ASTs is a dicey process,
3230 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00003231 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003232 BaseInit = Init;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003233
Alexis Hunt1d792652011-01-08 20:30:50 +00003234 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00003235 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00003236 InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003237 BaseInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003238 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003239}
3240
Sebastian Redl22653ba2011-08-30 19:58:05 +00003241// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00003242static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3243 if (T.isNull()) T = E->getType();
3244 QualType TargetType = SemaRef.BuildReferenceType(
3245 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003246 SourceLocation ExprLoc = E->getLocStart();
3247 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3248 TargetType, ExprLoc);
3249
3250 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3251 SourceRange(ExprLoc, ExprLoc),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003252 E->getSourceRange()).get();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003253}
3254
Anders Carlsson1b00e242010-04-23 03:10:23 +00003255/// ImplicitInitializerKind - How an implicit base or member initializer should
3256/// initialize its base or member.
3257enum ImplicitInitializerKind {
3258 IIK_Default,
3259 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00003260 IIK_Move,
3261 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00003262};
3263
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003264static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00003265BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003266 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00003267 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003268 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00003269 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003270 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00003271 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3272 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003273
John McCalldadc5752010-08-24 06:29:42 +00003274 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003275
3276 switch (ImplicitInitKind) {
Richard Smithc2bc61b2013-03-18 21:12:30 +00003277 case IIK_Inherit: {
3278 const CXXRecordDecl *Inherited =
3279 Constructor->getInheritedConstructor()->getParent();
3280 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3281 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3282 // C++11 [class.inhctor]p8:
3283 // Each expression in the expression-list is of the form
3284 // static_cast<T&&>(p), where p is the name of the corresponding
3285 // constructor parameter and T is the declared type of p.
3286 SmallVector<Expr*, 16> Args;
3287 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3288 ParmVarDecl *PD = Constructor->getParamDecl(I);
3289 ExprResult ArgExpr =
3290 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3291 VK_LValue, SourceLocation());
3292 if (ArgExpr.isInvalid())
3293 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003294 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
Richard Smithc2bc61b2013-03-18 21:12:30 +00003295 }
3296
3297 InitializationKind InitKind = InitializationKind::CreateDirect(
3298 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003299 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smithc2bc61b2013-03-18 21:12:30 +00003300 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3301 break;
3302 }
3303 }
3304 // Fall through.
Anders Carlsson1b00e242010-04-23 03:10:23 +00003305 case IIK_Default: {
3306 InitializationKind InitKind
3307 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003308 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3309 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003310 break;
3311 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003312
Sebastian Redl22653ba2011-08-30 19:58:05 +00003313 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00003314 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003315 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00003316 ParmVarDecl *Param = Constructor->getParamDecl(0);
3317 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00003318
Anders Carlsson1b00e242010-04-23 03:10:23 +00003319 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003320 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003321 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00003322 Constructor->getLocation(), ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003323 VK_LValue, nullptr);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003324
Eli Friedmanfa0df832012-02-02 03:46:19 +00003325 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3326
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003327 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00003328 QualType ArgTy =
3329 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3330 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00003331
Sebastian Redl22653ba2011-08-30 19:58:05 +00003332 if (Moving) {
3333 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3334 }
3335
John McCallcf142162010-08-07 06:22:56 +00003336 CXXCastPath BasePath;
3337 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00003338 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3339 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003340 Moving ? VK_XValue : VK_LValue,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003341 &BasePath).get();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00003342
Anders Carlsson1b00e242010-04-23 03:10:23 +00003343 InitializationKind InitKind
3344 = InitializationKind::CreateDirect(Constructor->getLocation(),
3345 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003346 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3347 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003348 break;
3349 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00003350 }
John McCallb268a282010-08-23 23:25:46 +00003351
Douglas Gregora40433a2010-12-07 00:41:46 +00003352 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003353 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003354 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003355
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003356 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00003357 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003358 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3359 SourceLocation()),
3360 BaseSpec->isVirtual(),
3361 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003362 BaseInit.getAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003363 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003364 SourceLocation());
3365
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003366 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003367}
3368
Sebastian Redl22653ba2011-08-30 19:58:05 +00003369static bool RefersToRValueRef(Expr *MemRef) {
3370 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3371 return Referenced->getType()->isRValueReferenceType();
3372}
3373
Anders Carlsson3c1db572010-04-23 02:15:47 +00003374static bool
3375BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003376 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00003377 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00003378 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003379 if (Field->isInvalidDecl())
3380 return true;
3381
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003382 SourceLocation Loc = Constructor->getLocation();
3383
Sebastian Redl22653ba2011-08-30 19:58:05 +00003384 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3385 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00003386 ParmVarDecl *Param = Constructor->getParamDecl(0);
3387 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00003388
3389 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00003390 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3391 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003392
Anders Carlsson423f5d82010-04-23 16:04:08 +00003393 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00003394 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00003395 SourceLocation(), Param, false,
Craig Topperc3ec1492014-05-26 06:22:03 +00003396 Loc, ParamType, VK_LValue, nullptr);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003397
Eli Friedmanfa0df832012-02-02 03:46:19 +00003398 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3399
Sebastian Redl22653ba2011-08-30 19:58:05 +00003400 if (Moving) {
3401 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3402 }
3403
Douglas Gregor94f9a482010-05-05 05:51:00 +00003404 // Build a reference to this field within the parameter.
3405 CXXScopeSpec SS;
3406 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3407 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00003408 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3409 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003410 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00003411 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00003412 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003413 ParamType, Loc,
3414 /*IsArrow=*/false,
3415 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00003416 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003417 /*FirstQualifierInScope=*/nullptr,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003418 MemberLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00003419 /*TemplateArgs=*/nullptr);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003420 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00003421 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003422
3423 // C++11 [class.copy]p15:
3424 // - if a member m has rvalue reference type T&&, it is direct-initialized
3425 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00003426 if (RefersToRValueRef(CtorArg.get())) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003427 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003428 }
3429
Douglas Gregor94f9a482010-05-05 05:51:00 +00003430 // When the field we are copying is an array, create index variables for
3431 // each dimension of the array. We use these index variables to subscript
3432 // the source array, and other clients (e.g., CodeGen) will perform the
3433 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003434 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003435 QualType BaseType = Field->getType();
3436 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00003437 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003438 while (const ConstantArrayType *Array
3439 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003440 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003441 // Create the iteration variable for this array index.
Craig Topperc3ec1492014-05-26 06:22:03 +00003442 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003443 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003444 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003445 llvm::raw_svector_ostream OS(Str);
3446 OS << "__i" << IndexVariables.size();
3447 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3448 }
3449 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00003450 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00003451 IterationVarName, SizeType,
3452 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003453 SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003454 IndexVariables.push_back(IterationVar);
3455
3456 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00003457 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00003458 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003459 assert(!IterationVarRef.isInvalid() &&
3460 "Reference to invented variable cannot fail!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003461 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
Eli Friedman844f9452012-01-23 02:35:22 +00003462 assert(!IterationVarRef.isInvalid() &&
3463 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00003464
Douglas Gregor94f9a482010-05-05 05:51:00 +00003465 // Subscript the array with this iteration variable.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003466 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3467 IterationVarRef.get(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00003468 Loc);
3469 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00003470 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003471
Douglas Gregor94f9a482010-05-05 05:51:00 +00003472 BaseType = Array->getElementType();
3473 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00003474
3475 // The array subscript expression is an lvalue, which is wrong for moving.
3476 if (Moving && InitializingArray)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003477 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00003478
Douglas Gregor94f9a482010-05-05 05:51:00 +00003479 // Construct the entity that we will be initializing. For an array, this
3480 // will be first element in the array, which may require several levels
3481 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003482 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00003483 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00003484 if (Indirect)
3485 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3486 else
3487 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00003488 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3489 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3490 0,
3491 Entities.back()));
3492
3493 // Direct-initialize to use the copy constructor.
3494 InitializationKind InitKind =
3495 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3496
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003497 Expr *CtorArgE = CtorArg.getAs<Expr>();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003498 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003499
John McCalldadc5752010-08-24 06:29:42 +00003500 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00003501 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00003502 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00003503 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00003504 if (MemberInit.isInvalid())
3505 return true;
3506
Douglas Gregor493627b2011-08-10 15:22:55 +00003507 if (Indirect) {
3508 assert(IndexVariables.size() == 0 &&
3509 "Indirect field improperly initialized");
3510 CXXMemberInit
3511 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3512 Loc, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003513 MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003514 Loc);
3515 } else
3516 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003517 Loc, MemberInit.getAs<Expr>(),
Douglas Gregor493627b2011-08-10 15:22:55 +00003518 Loc,
3519 IndexVariables.data(),
3520 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00003521 return false;
3522 }
3523
Richard Smithc2bc61b2013-03-18 21:12:30 +00003524 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3525 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00003526
Anders Carlsson3c1db572010-04-23 02:15:47 +00003527 QualType FieldBaseElementType =
3528 SemaRef.Context.getBaseElementType(Field->getType());
3529
Anders Carlsson3c1db572010-04-23 02:15:47 +00003530 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003531 InitializedEntity InitEntity
3532 = Indirect? InitializedEntity::InitializeMember(Indirect)
3533 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00003534 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00003535 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00003536
3537 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3538 ExprResult MemberInit =
3539 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00003540
Douglas Gregora40433a2010-12-07 00:41:46 +00003541 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003542 if (MemberInit.isInvalid())
3543 return true;
3544
Douglas Gregor493627b2011-08-10 15:22:55 +00003545 if (Indirect)
3546 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3547 Indirect, Loc,
3548 Loc,
3549 MemberInit.get(),
3550 Loc);
3551 else
3552 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3553 Field, Loc, Loc,
3554 MemberInit.get(),
3555 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00003556 return false;
3557 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003558
Alexis Hunt8b455182011-05-17 00:19:05 +00003559 if (!Field->getParent()->isUnion()) {
3560 if (FieldBaseElementType->isReferenceType()) {
3561 SemaRef.Diag(Constructor->getLocation(),
3562 diag::err_uninitialized_member_in_ctor)
3563 << (int)Constructor->isImplicit()
3564 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3565 << 0 << Field->getDeclName();
3566 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3567 return true;
3568 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003569
Alexis Hunt8b455182011-05-17 00:19:05 +00003570 if (FieldBaseElementType.isConstQualified()) {
3571 SemaRef.Diag(Constructor->getLocation(),
3572 diag::err_uninitialized_member_in_ctor)
3573 << (int)Constructor->isImplicit()
3574 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3575 << 1 << Field->getDeclName();
3576 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3577 return true;
3578 }
Anders Carlssondca6be02010-04-23 03:07:47 +00003579 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00003580
David Blaikiebbafb8a2012-03-11 07:00:24 +00003581 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003582 FieldBaseElementType->isObjCRetainableType() &&
3583 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3584 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00003585 // ARC:
John McCall31168b02011-06-15 23:02:42 +00003586 // Default-initialize Objective-C pointers to NULL.
3587 CXXMemberInit
3588 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3589 Loc, Loc,
3590 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3591 Loc);
3592 return false;
3593 }
3594
Anders Carlsson3c1db572010-04-23 02:15:47 +00003595 // Nothing to initialize.
Craig Topperc3ec1492014-05-26 06:22:03 +00003596 CXXMemberInit = nullptr;
Anders Carlsson3c1db572010-04-23 02:15:47 +00003597 return false;
3598}
John McCallbc83b3f2010-05-20 23:23:51 +00003599
3600namespace {
3601struct BaseAndFieldInfo {
3602 Sema &S;
3603 CXXConstructorDecl *Ctor;
3604 bool AnyErrorsInInits;
3605 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00003606 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003607 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00003608 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00003609
3610 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3611 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00003612 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3613 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00003614 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00003615 else if (Generated && Ctor->isMoveConstructor())
3616 IIK = IIK_Move;
Richard Smithc2bc61b2013-03-18 21:12:30 +00003617 else if (Ctor->getInheritedConstructor())
3618 IIK = IIK_Inherit;
John McCallbc83b3f2010-05-20 23:23:51 +00003619 else
3620 IIK = IIK_Default;
3621 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00003622
3623 bool isImplicitCopyOrMove() const {
3624 switch (IIK) {
3625 case IIK_Copy:
3626 case IIK_Move:
3627 return true;
3628
3629 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00003630 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00003631 return false;
3632 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003633
3634 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00003635 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00003636
3637 bool addFieldInitializer(CXXCtorInitializer *Init) {
3638 AllToInit.push_back(Init);
3639
3640 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00003641 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003642 S.UnusedPrivateFields.remove(Init->getAnyMember());
3643
3644 return false;
3645 }
John McCallbc83b3f2010-05-20 23:23:51 +00003646
Richard Smithab44d5b2013-12-10 08:25:00 +00003647 bool isInactiveUnionMember(FieldDecl *Field) {
3648 RecordDecl *Record = Field->getParent();
3649 if (!Record->isUnion())
3650 return false;
3651
Richard Smith8d183852013-12-10 20:56:03 +00003652 if (FieldDecl *Active =
3653 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00003654 return Active != Field->getCanonicalDecl();
3655
3656 // In an implicit copy or move constructor, ignore any in-class initializer.
3657 if (isImplicitCopyOrMove())
3658 return true;
3659
3660 // If there's no explicit initialization, the field is active only if it
3661 // has an in-class initializer...
3662 if (Field->hasInClassInitializer())
3663 return false;
3664 // ... or it's an anonymous struct or union whose class has an in-class
3665 // initializer.
3666 if (!Field->isAnonymousStructOrUnion())
3667 return true;
3668 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3669 return !FieldRD->hasInClassInitializer();
3670 }
3671
3672 /// \brief Determine whether the given field is, or is within, a union member
3673 /// that is inactive (because there was an initializer given for a different
3674 /// member of the union, or because the union was not initialized at all).
3675 bool isWithinInactiveUnionMember(FieldDecl *Field,
3676 IndirectFieldDecl *Indirect) {
3677 if (!Indirect)
3678 return isInactiveUnionMember(Field);
3679
Aaron Ballman29c94602014-03-07 18:36:15 +00003680 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003681 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003682 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00003683 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00003684 }
3685 return false;
3686 }
3687};
Richard Smithc94ec842011-09-19 13:34:43 +00003688}
3689
Douglas Gregor10f939c2011-11-02 23:04:16 +00003690/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3691/// array type.
3692static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3693 if (T->isIncompleteArrayType())
3694 return true;
3695
3696 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3697 if (!ArrayT->getSize())
3698 return true;
3699
3700 T = ArrayT->getElementType();
3701 }
3702
3703 return false;
3704}
3705
Richard Smith938f40b2011-06-11 17:19:42 +00003706static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00003707 FieldDecl *Field,
Craig Topperc3ec1492014-05-26 06:22:03 +00003708 IndirectFieldDecl *Indirect = nullptr) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003709 if (Field->isInvalidDecl())
3710 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00003711
Chandler Carruth139e9622010-06-30 02:59:29 +00003712 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smithcd45dbc2014-04-19 03:48:30 +00003713 if (CXXCtorInitializer *Init =
3714 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
Richard Smith0a8cfc72012-08-07 21:30:42 +00003715 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003716
Richard Smithab44d5b2013-12-10 08:25:00 +00003717 // C++11 [class.base.init]p8:
3718 // if the entity is a non-static data member that has a
3719 // brace-or-equal-initializer and either
3720 // -- the constructor's class is a union and no other variant member of that
3721 // union is designated by a mem-initializer-id or
3722 // -- the constructor's class is not a union, and, if the entity is a member
3723 // of an anonymous union, no other member of that union is designated by
3724 // a mem-initializer-id,
3725 // the entity is initialized as specified in [dcl.init].
3726 //
3727 // We also apply the same rules to handle anonymous structs within anonymous
3728 // unions.
3729 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3730 return false;
3731
Douglas Gregor7db3e952011-11-28 20:03:15 +00003732 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smith852c9db2013-04-20 22:23:05 +00003733 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3734 Info.Ctor->getLocation(), Field);
Douglas Gregor493627b2011-08-10 15:22:55 +00003735 CXXCtorInitializer *Init;
3736 if (Indirect)
3737 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3738 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003739 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003740 SourceLocation());
3741 else
3742 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3743 SourceLocation(),
Richard Smith852c9db2013-04-20 22:23:05 +00003744 SourceLocation(), DIE,
Douglas Gregor493627b2011-08-10 15:22:55 +00003745 SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00003746 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003747 }
3748
Douglas Gregor10f939c2011-11-02 23:04:16 +00003749 // Don't initialize incomplete or zero-length arrays.
3750 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3751 return false;
3752
John McCallbc83b3f2010-05-20 23:23:51 +00003753 // Don't try to build an implicit initializer if there were semantic
3754 // errors in any of the initializers (and therefore we might be
3755 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00003756 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00003757 return false;
3758
Craig Topperc3ec1492014-05-26 06:22:03 +00003759 CXXCtorInitializer *Init = nullptr;
Douglas Gregor493627b2011-08-10 15:22:55 +00003760 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3761 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00003762 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00003763
Richard Smith0a8cfc72012-08-07 21:30:42 +00003764 if (!Init)
3765 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00003766
Richard Smith0a8cfc72012-08-07 21:30:42 +00003767 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00003768}
Alexis Hunt61bc1732011-05-01 07:04:31 +00003769
3770bool
3771Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3772 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00003773 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00003774 Constructor->setNumCtorInitializers(1);
3775 CXXCtorInitializer **initializer =
3776 new (Context) CXXCtorInitializer*[1];
3777 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3778 Constructor->setCtorInitializers(initializer);
3779
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003780 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003781 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00003782 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3783 }
3784
Alexis Hunte2622992011-05-05 00:05:47 +00003785 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00003786
Richard Trieu8a0c9e62014-09-12 22:47:58 +00003787 DiagnoseUninitializedFields(*this, Constructor);
3788
Alexis Hunt61bc1732011-05-01 07:04:31 +00003789 return false;
3790}
Douglas Gregor493627b2011-08-10 15:22:55 +00003791
David Blaikie3fc2f912013-01-17 05:26:25 +00003792bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3793 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00003794 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003795 // Just store the initializers as written, they will be checked during
3796 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00003797 if (!Initializers.empty()) {
3798 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00003799 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00003800 new (Context) CXXCtorInitializer*[Initializers.size()];
3801 memcpy(baseOrMemberInitializers, Initializers.data(),
3802 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00003803 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003804 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00003805
3806 // Let template instantiation know whether we had errors.
3807 if (AnyErrors)
3808 Constructor->setInvalidDecl();
3809
Anders Carlssondb0a9652010-04-02 06:26:44 +00003810 return false;
3811 }
3812
John McCallbc83b3f2010-05-20 23:23:51 +00003813 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00003814
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003815 // We need to build the initializer AST according to order of construction
3816 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003817 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00003818 if (!ClassDecl)
3819 return true;
3820
Eli Friedman9cf6b592009-11-09 19:20:36 +00003821 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00003822
David Blaikie3fc2f912013-01-17 05:26:25 +00003823 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003824 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00003825
Anders Carlssondb0a9652010-04-02 06:26:44 +00003826 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00003827 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003828 else {
Richard Smithcd45dbc2014-04-19 03:48:30 +00003829 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00003830
3831 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00003832 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003833 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00003834 if (FD && FD->getParent()->isUnion())
3835 Info.ActiveUnionMember.insert(std::make_pair(
3836 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3837 }
3838 } else if (FieldDecl *FD = Member->getMember()) {
3839 if (FD->getParent()->isUnion())
3840 Info.ActiveUnionMember.insert(std::make_pair(
3841 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3842 }
3843 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00003844 }
3845
Anders Carlsson43c64af2010-04-21 19:52:01 +00003846 // Keep track of the direct virtual bases.
3847 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00003848 for (auto &I : ClassDecl->bases()) {
3849 if (I.isVirtual())
3850 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00003851 }
3852
Anders Carlssondb0a9652010-04-02 06:26:44 +00003853 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00003854 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003855 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00003856 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00003857 // [class.base.init]p7, per DR257:
3858 // A mem-initializer where the mem-initializer-id names a virtual base
3859 // class is ignored during execution of a constructor of any class that
3860 // is not the most derived class.
3861 if (ClassDecl->isAbstract()) {
3862 // FIXME: Provide a fixit to remove the base specifier. This requires
3863 // tracking the location of the associated comma for a base specifier.
3864 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00003865 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00003866 DiagnoseAbstractType(ClassDecl);
3867 }
3868
John McCallbc83b3f2010-05-20 23:23:51 +00003869 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00003870 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3871 // [class.base.init]p8, per DR257:
3872 // If a given [...] base class is not named by a mem-initializer-id
3873 // [...] and the entity is not a virtual base class of an abstract
3874 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00003875 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00003876 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003877 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00003878 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00003879 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003880 HadError = true;
3881 continue;
3882 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00003883
John McCallbc83b3f2010-05-20 23:23:51 +00003884 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003885 }
3886 }
Mike Stump11289f42009-09-09 15:08:12 +00003887
John McCallbc83b3f2010-05-20 23:23:51 +00003888 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00003889 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003890 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00003891 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00003892 continue;
Mike Stump11289f42009-09-09 15:08:12 +00003893
Alexis Hunt1d792652011-01-08 20:30:50 +00003894 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00003895 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00003896 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00003897 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003898 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00003899 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00003900 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00003901 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00003902 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003903 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00003904 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00003905
John McCallbc83b3f2010-05-20 23:23:51 +00003906 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003907 }
3908 }
Mike Stump11289f42009-09-09 15:08:12 +00003909
John McCallbc83b3f2010-05-20 23:23:51 +00003910 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00003911 for (auto *Mem : ClassDecl->decls()) {
3912 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003913 // C++ [class.bit]p2:
3914 // A declaration for a bit-field that omits the identifier declares an
3915 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3916 // initialized.
3917 if (F->isUnnamedBitfield())
3918 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003919
Sebastian Redl22653ba2011-08-30 19:58:05 +00003920 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00003921 // handle anonymous struct/union fields based on their individual
3922 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003923 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003924 continue;
3925
3926 if (CollectFieldInitializer(*this, Info, F))
3927 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003928 continue;
3929 }
Douglas Gregor493627b2011-08-10 15:22:55 +00003930
3931 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00003932 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00003933 continue;
3934
Aaron Ballman629afae2014-03-07 19:56:05 +00003935 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00003936 if (F->getType()->isIncompleteArrayType()) {
3937 assert(ClassDecl->hasFlexibleArrayMember() &&
3938 "Incomplete array type is not valid");
3939 continue;
3940 }
3941
Douglas Gregor493627b2011-08-10 15:22:55 +00003942 // Initialize each field of an anonymous struct individually.
3943 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3944 HadError = true;
3945
3946 continue;
3947 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00003948 }
Mike Stump11289f42009-09-09 15:08:12 +00003949
David Blaikie3fc2f912013-01-17 05:26:25 +00003950 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003951 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003952 Constructor->setNumCtorInitializers(NumInitializers);
3953 CXXCtorInitializer **baseOrMemberInitializers =
3954 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00003955 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00003956 NumInitializers * sizeof(CXXCtorInitializer*));
3957 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00003958
John McCalla6309952010-03-16 21:39:52 +00003959 // Constructors implicitly reference the base and member
3960 // destructors.
3961 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3962 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003963 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00003964
3965 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00003966}
3967
David Blaikieb61b8152013-01-17 08:49:22 +00003968static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003969 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00003970 const RecordDecl *RD = RT->getDecl();
3971 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003972 for (auto *Field : RD->fields())
3973 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00003974 return;
3975 }
Eli Friedman952c15d2009-07-21 19:28:10 +00003976 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003977 IdealInits.push_back(Field->getCanonicalDecl());
Eli Friedman952c15d2009-07-21 19:28:10 +00003978}
3979
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003980static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3981 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00003982}
3983
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003984static const void *GetKeyForMember(ASTContext &Context,
3985 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00003986 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003987 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00003988
Richard Smithcd45dbc2014-04-19 03:48:30 +00003989 return Member->getAnyMember()->getCanonicalDecl();
Eli Friedman952c15d2009-07-21 19:28:10 +00003990}
3991
David Blaikie3fc2f912013-01-17 05:26:25 +00003992static void DiagnoseBaseOrMemInitializerOrder(
3993 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3994 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00003995 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00003996 return;
Mike Stump11289f42009-09-09 15:08:12 +00003997
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003998 // Don't check initializers order unless the warning is enabled at the
3999 // location of at least one initializer.
4000 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004001 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004002 CXXCtorInitializer *Init = Inits[InitIndex];
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004003 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4004 Init->getSourceLocation())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004005 ShouldCheckOrder = true;
4006 break;
4007 }
4008 }
4009 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00004010 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004011
John McCallbb7b6582010-04-10 07:37:23 +00004012 // Build the list of bases and members in the order that they'll
4013 // actually be initialized. The explicit initializers should be in
4014 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004015 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00004016
Anders Carlsson96b8fc62010-04-02 03:38:04 +00004017 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4018
John McCallbb7b6582010-04-10 07:37:23 +00004019 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004020 for (const auto &VBase : ClassDecl->vbases())
4021 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00004022
John McCallbb7b6582010-04-10 07:37:23 +00004023 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004024 for (const auto &Base : ClassDecl->bases()) {
4025 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00004026 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00004027 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00004028 }
Mike Stump11289f42009-09-09 15:08:12 +00004029
John McCallbb7b6582010-04-10 07:37:23 +00004030 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004031 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004032 if (Field->isUnnamedBitfield())
4033 continue;
4034
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004035 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00004036 }
4037
John McCallbb7b6582010-04-10 07:37:23 +00004038 unsigned NumIdealInits = IdealInitKeys.size();
4039 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00004040
Craig Topperc3ec1492014-05-26 06:22:03 +00004041 CXXCtorInitializer *PrevInit = nullptr;
David Blaikie3fc2f912013-01-17 05:26:25 +00004042 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004043 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004044 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00004045
4046 // Scan forward to try to find this initializer in the idealized
4047 // initializers list.
4048 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4049 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004050 break;
John McCallbb7b6582010-04-10 07:37:23 +00004051
4052 // If we didn't find this initializer, it must be because we
4053 // scanned past it on a previous iteration. That can only
4054 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00004055 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00004056 Sema::SemaDiagnosticBuilder D =
4057 SemaRef.Diag(PrevInit->getSourceLocation(),
4058 diag::warn_initializer_out_of_order);
4059
Francois Pichetd583da02010-12-04 09:14:42 +00004060 if (PrevInit->isAnyMemberInitializer())
4061 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004062 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004063 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004064
Francois Pichetd583da02010-12-04 09:14:42 +00004065 if (Init->isAnyMemberInitializer())
4066 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004067 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004068 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004069
4070 // Move back to the initializer's location in the ideal list.
4071 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4072 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004073 break;
John McCallbb7b6582010-04-10 07:37:23 +00004074
4075 assert(IdealIndex != NumIdealInits &&
4076 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004077 }
John McCallbb7b6582010-04-10 07:37:23 +00004078
4079 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004080 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00004081}
4082
John McCall23eebd92010-04-10 09:28:51 +00004083namespace {
4084bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004085 CXXCtorInitializer *Init,
4086 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00004087 if (!PrevInit) {
4088 PrevInit = Init;
4089 return false;
4090 }
4091
Douglas Gregorea306a12013-03-25 23:28:23 +00004092 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00004093 S.Diag(Init->getSourceLocation(),
4094 diag::err_multiple_mem_initialization)
4095 << Field->getDeclName()
4096 << Init->getSourceRange();
4097 else {
John McCall424cec92011-01-19 06:33:43 +00004098 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00004099 assert(BaseClass && "neither field nor base");
4100 S.Diag(Init->getSourceLocation(),
4101 diag::err_multiple_base_initialization)
4102 << QualType(BaseClass, 0)
4103 << Init->getSourceRange();
4104 }
4105 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4106 << 0 << PrevInit->getSourceRange();
4107
4108 return true;
4109}
4110
Alexis Hunt1d792652011-01-08 20:30:50 +00004111typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00004112typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4113
4114bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004115 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00004116 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00004117 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00004118 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00004119 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00004120
4121 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00004122 if (Parent->isUnion()) {
4123 UnionEntry &En = Unions[Parent];
4124 if (En.first && En.first != Child) {
4125 S.Diag(Init->getSourceLocation(),
4126 diag::err_multiple_mem_union_initialization)
4127 << Field->getDeclName()
4128 << Init->getSourceRange();
4129 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4130 << 0 << En.second->getSourceRange();
4131 return true;
David Blaikie256ee192011-11-12 20:54:14 +00004132 }
4133 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00004134 En.first = Child;
4135 En.second = Init;
4136 }
David Blaikie0f65d592011-11-17 06:01:57 +00004137 if (!Parent->isAnonymousStructOrUnion())
4138 return false;
John McCall23eebd92010-04-10 09:28:51 +00004139 }
4140
4141 Child = Parent;
4142 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00004143 }
John McCall23eebd92010-04-10 09:28:51 +00004144
4145 return false;
4146}
4147}
4148
Anders Carlssone857b292010-04-02 03:37:03 +00004149/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00004150void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00004151 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00004152 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00004153 bool AnyErrors) {
4154 if (!ConstructorDecl)
4155 return;
4156
4157 AdjustDeclIfTemplate(ConstructorDecl);
4158
4159 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00004160 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00004161
4162 if (!Constructor) {
4163 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4164 return;
4165 }
4166
John McCall23eebd92010-04-10 09:28:51 +00004167 // Mapping for the duplicate initializers check.
4168 // For member initializers, this is keyed with a FieldDecl*.
4169 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004170 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00004171
4172 // Mapping for the inconsistent anonymous-union initializers check.
4173 RedundantUnionMap MemberUnions;
4174
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004175 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004176 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004177 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00004178
Abramo Bagnara341d7832010-05-26 18:09:23 +00004179 // Set the source order index.
4180 Init->setSourceOrder(i);
4181
Francois Pichetd583da02010-12-04 09:14:42 +00004182 if (Init->isAnyMemberInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004183 const void *Key = GetKeyForMember(Context, Init);
4184 if (CheckRedundantInit(*this, Init, Members[Key]) ||
John McCall23eebd92010-04-10 09:28:51 +00004185 CheckRedundantUnionInit(*this, Init, MemberUnions))
4186 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00004187 } else if (Init->isBaseInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004188 const void *Key = GetKeyForMember(Context, Init);
John McCall23eebd92010-04-10 09:28:51 +00004189 if (CheckRedundantInit(*this, Init, Members[Key]))
4190 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00004191 } else {
4192 assert(Init->isDelegatingInitializer());
4193 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00004194 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00004195 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00004196 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00004197 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00004198 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00004199 }
Alexis Hunt6118d662011-05-04 05:57:24 +00004200 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00004201 // Return immediately as the initializer is set.
4202 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004203 }
Anders Carlssone857b292010-04-02 03:37:03 +00004204 }
4205
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004206 if (HadError)
4207 return;
4208
David Blaikie3fc2f912013-01-17 05:26:25 +00004209 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00004210
David Blaikie3fc2f912013-01-17 05:26:25 +00004211 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00004212
Richard Trieuef64e942013-10-25 00:56:00 +00004213 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00004214}
4215
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004216void
John McCalla6309952010-03-16 21:39:52 +00004217Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4218 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00004219 // Ignore dependent contexts. Also ignore unions, since their members never
4220 // have destructors implicitly called.
4221 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00004222 return;
John McCall1064d7e2010-03-16 05:22:47 +00004223
4224 // FIXME: all the access-control diagnostics are positioned on the
4225 // field/base declaration. That's probably good; that said, the
4226 // user might reasonably want to know why the destructor is being
4227 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00004228
Anders Carlssondee9a302009-11-17 04:44:12 +00004229 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004230 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00004231 if (Field->isInvalidDecl())
4232 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004233
4234 // Don't destroy incomplete or zero-length arrays.
4235 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4236 continue;
4237
Anders Carlssondee9a302009-11-17 04:44:12 +00004238 QualType FieldType = Context.getBaseElementType(Field->getType());
4239
4240 const RecordType* RT = FieldType->getAs<RecordType>();
4241 if (!RT)
4242 continue;
4243
4244 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004245 if (FieldClassDecl->isInvalidDecl())
4246 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004247 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004248 continue;
Richard Smith921bd202012-02-26 09:11:52 +00004249 // The destructor for an implicit anonymous union member is never invoked.
4250 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4251 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00004252
Douglas Gregore71edda2010-07-01 22:47:18 +00004253 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004254 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004255 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004256 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00004257 << Field->getDeclName()
4258 << FieldType);
4259
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004260 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004261 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004262 }
4263
John McCall1064d7e2010-03-16 05:22:47 +00004264 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4265
Anders Carlssondee9a302009-11-17 04:44:12 +00004266 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004267 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004268 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00004269 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004270
4271 // Remember direct virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004272 if (Base.isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00004273 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00004274
John McCall1064d7e2010-03-16 05:22:47 +00004275 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004276 // If our base class is invalid, we probably can't get its dtor anyway.
4277 if (BaseClassDecl->isInvalidDecl())
4278 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004279 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00004280 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004281
Douglas Gregore71edda2010-07-01 22:47:18 +00004282 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004283 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00004284
4285 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00004286 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004287 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00004288 << Base.getType()
4289 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00004290 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00004291
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004292 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004293 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00004294 }
4295
4296 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004297 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00004298 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00004299 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00004300
4301 // Ignore direct virtual bases.
4302 if (DirectVirtualBases.count(RT))
4303 continue;
4304
John McCall1064d7e2010-03-16 05:22:47 +00004305 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004306 // If our base class is invalid, we probably can't get its dtor anyway.
4307 if (BaseClassDecl->isInvalidDecl())
4308 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00004309 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004310 continue;
John McCall1064d7e2010-03-16 05:22:47 +00004311
Douglas Gregore71edda2010-07-01 22:47:18 +00004312 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004313 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00004314 if (CheckDestructorAccess(
4315 ClassDecl->getLocation(), Dtor,
4316 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00004317 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004318 Context.getTypeDeclType(ClassDecl)) ==
4319 AR_accessible) {
4320 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00004321 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00004322 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00004323 SourceRange(), DeclarationName(), nullptr);
David Majnemer626032f2013-06-22 06:43:58 +00004324 }
John McCall1064d7e2010-03-16 05:22:47 +00004325
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004326 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00004327 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004328 }
4329}
4330
John McCall48871652010-08-21 09:40:31 +00004331void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00004332 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004333 return;
Mike Stump11289f42009-09-09 15:08:12 +00004334
Mike Stump11289f42009-09-09 15:08:12 +00004335 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00004336 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00004337 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00004338 DiagnoseUninitializedFields(*this, Constructor);
4339 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00004340}
4341
Mike Stump11289f42009-09-09 15:08:12 +00004342bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00004343 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregorae298422012-05-04 17:09:59 +00004344 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4345 unsigned DiagID;
4346 AbstractDiagSelID SelID;
4347
4348 public:
4349 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4350 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004351
Craig Toppera798a9d2014-03-02 09:32:10 +00004352 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004353 if (Suppressed) return;
Douglas Gregorae298422012-05-04 17:09:59 +00004354 if (SelID == -1)
4355 S.Diag(Loc, DiagID) << T;
4356 else
4357 S.Diag(Loc, DiagID) << SelID << T;
4358 }
4359 } Diagnoser(DiagID, SelID);
4360
4361 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004362}
4363
Anders Carlssoneabf7702009-08-27 00:13:57 +00004364bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregorae298422012-05-04 17:09:59 +00004365 TypeDiagnoser &Diagnoser) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004366 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004367 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004368
Anders Carlssoneb0c5322009-03-23 19:10:31 +00004369 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregorae298422012-05-04 17:09:59 +00004370 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump11289f42009-09-09 15:08:12 +00004371
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004372 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004373 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004374 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004375 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00004376
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004377 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregorae298422012-05-04 17:09:59 +00004378 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00004379 }
Mike Stump11289f42009-09-09 15:08:12 +00004380
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004381 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004382 if (!RT)
4383 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004384
John McCall67da35c2010-02-04 22:26:26 +00004385 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004386
John McCall02db245d2010-08-18 09:41:07 +00004387 // We can't answer whether something is abstract until it has a
4388 // definition. If it's currently being defined, we'll walk back
4389 // over all the declarations when we have a full definition.
4390 const CXXRecordDecl *Def = RD->getDefinition();
4391 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00004392 return false;
4393
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004394 if (!RD->isAbstract())
4395 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004396
Douglas Gregorae298422012-05-04 17:09:59 +00004397 Diagnoser.diagnose(*this, Loc, T);
John McCall02db245d2010-08-18 09:41:07 +00004398 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00004399
John McCall02db245d2010-08-18 09:41:07 +00004400 return true;
4401}
4402
4403void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4404 // Check if we've already emitted the list of pure virtual functions
4405 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004406 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00004407 return;
Mike Stump11289f42009-09-09 15:08:12 +00004408
Richard Smithbc46e432013-07-22 02:56:56 +00004409 // If the diagnostic is suppressed, don't emit the notes. We're only
4410 // going to emit them once, so try to attach them to a diagnostic we're
4411 // actually going to show.
4412 if (Diags.isLastDiagnosticIgnored())
4413 return;
4414
Douglas Gregor4165bd62010-03-23 23:47:56 +00004415 CXXFinalOverriderMap FinalOverriders;
4416 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00004417
Anders Carlssona2f74f32010-06-03 01:00:02 +00004418 // Keep a set of seen pure methods so we won't diagnose the same method
4419 // more than once.
4420 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4421
Douglas Gregor4165bd62010-03-23 23:47:56 +00004422 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4423 MEnd = FinalOverriders.end();
4424 M != MEnd;
4425 ++M) {
4426 for (OverridingMethods::iterator SO = M->second.begin(),
4427 SOEnd = M->second.end();
4428 SO != SOEnd; ++SO) {
4429 // C++ [class.abstract]p4:
4430 // A class is abstract if it contains or inherits at least one
4431 // pure virtual function for which the final overrider is pure
4432 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00004433
Douglas Gregor4165bd62010-03-23 23:47:56 +00004434 //
4435 if (SO->second.size() != 1)
4436 continue;
4437
4438 if (!SO->second.front().Method->isPure())
4439 continue;
4440
Anders Carlssona2f74f32010-06-03 01:00:02 +00004441 if (!SeenPureMethods.insert(SO->second.front().Method))
4442 continue;
4443
Douglas Gregor4165bd62010-03-23 23:47:56 +00004444 Diag(SO->second.front().Method->getLocation(),
4445 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00004446 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00004447 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004448 }
4449
4450 if (!PureVirtualClassDiagSet)
4451 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4452 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00004453}
4454
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004455namespace {
John McCall02db245d2010-08-18 09:41:07 +00004456struct AbstractUsageInfo {
4457 Sema &S;
4458 CXXRecordDecl *Record;
4459 CanQualType AbstractType;
4460 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00004461
John McCall02db245d2010-08-18 09:41:07 +00004462 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4463 : S(S), Record(Record),
4464 AbstractType(S.Context.getCanonicalType(
4465 S.Context.getTypeDeclType(Record))),
4466 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004467
John McCall02db245d2010-08-18 09:41:07 +00004468 void DiagnoseAbstractType() {
4469 if (Invalid) return;
4470 S.DiagnoseAbstractType(Record);
4471 Invalid = true;
4472 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00004473
John McCall02db245d2010-08-18 09:41:07 +00004474 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4475};
4476
4477struct CheckAbstractUsage {
4478 AbstractUsageInfo &Info;
4479 const NamedDecl *Ctx;
4480
4481 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4482 : Info(Info), Ctx(Ctx) {}
4483
4484 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4485 switch (TL.getTypeLocClass()) {
4486#define ABSTRACT_TYPELOC(CLASS, PARENT)
4487#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00004488 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00004489#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004490 }
John McCall02db245d2010-08-18 09:41:07 +00004491 }
Mike Stump11289f42009-09-09 15:08:12 +00004492
John McCall02db245d2010-08-18 09:41:07 +00004493 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00004494 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004495 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4496 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00004497 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00004498
4499 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00004500 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004501 }
John McCall02db245d2010-08-18 09:41:07 +00004502 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004503
John McCall02db245d2010-08-18 09:41:07 +00004504 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4505 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4506 }
Mike Stump11289f42009-09-09 15:08:12 +00004507
John McCall02db245d2010-08-18 09:41:07 +00004508 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4509 // Visit the type parameters from a permissive context.
4510 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4511 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4512 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4513 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4514 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4515 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004516 }
John McCall02db245d2010-08-18 09:41:07 +00004517 }
Mike Stump11289f42009-09-09 15:08:12 +00004518
John McCall02db245d2010-08-18 09:41:07 +00004519 // Visit pointee types from a permissive context.
4520#define CheckPolymorphic(Type) \
4521 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4522 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4523 }
4524 CheckPolymorphic(PointerTypeLoc)
4525 CheckPolymorphic(ReferenceTypeLoc)
4526 CheckPolymorphic(MemberPointerTypeLoc)
4527 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00004528 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00004529
John McCall02db245d2010-08-18 09:41:07 +00004530 /// Handle all the types we haven't given a more specific
4531 /// implementation for above.
4532 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4533 // Every other kind of type that we haven't called out already
4534 // that has an inner type is either (1) sugar or (2) contains that
4535 // inner type in some way as a subobject.
4536 if (TypeLoc Next = TL.getNextTypeLoc())
4537 return Visit(Next, Sel);
4538
4539 // If there's no inner type and we're in a permissive context,
4540 // don't diagnose.
4541 if (Sel == Sema::AbstractNone) return;
4542
4543 // Check whether the type matches the abstract type.
4544 QualType T = TL.getType();
4545 if (T->isArrayType()) {
4546 Sel = Sema::AbstractArrayType;
4547 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00004548 }
John McCall02db245d2010-08-18 09:41:07 +00004549 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4550 if (CT != Info.AbstractType) return;
4551
4552 // It matched; do some magic.
4553 if (Sel == Sema::AbstractArrayType) {
4554 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4555 << T << TL.getSourceRange();
4556 } else {
4557 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4558 << Sel << T << TL.getSourceRange();
4559 }
4560 Info.DiagnoseAbstractType();
4561 }
4562};
4563
4564void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4565 Sema::AbstractDiagSelID Sel) {
4566 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4567}
4568
4569}
4570
4571/// Check for invalid uses of an abstract type in a method declaration.
4572static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4573 CXXMethodDecl *MD) {
4574 // No need to do the check on definitions, which require that
4575 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00004576 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00004577 return;
4578
4579 // For safety's sake, just ignore it if we don't have type source
4580 // information. This should never happen for non-implicit methods,
4581 // but...
4582 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4583 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4584}
4585
4586/// Check for invalid uses of an abstract type within a class definition.
4587static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4588 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00004589 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00004590 if (D->isImplicit()) continue;
4591
4592 // Methods and method templates.
4593 if (isa<CXXMethodDecl>(D)) {
4594 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4595 } else if (isa<FunctionTemplateDecl>(D)) {
4596 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4597 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4598
4599 // Fields and static variables.
4600 } else if (isa<FieldDecl>(D)) {
4601 FieldDecl *FD = cast<FieldDecl>(D);
4602 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4603 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4604 } else if (isa<VarDecl>(D)) {
4605 VarDecl *VD = cast<VarDecl>(D);
4606 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4607 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4608
4609 // Nested classes and class templates.
4610 } else if (isa<CXXRecordDecl>(D)) {
4611 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4612 } else if (isa<ClassTemplateDecl>(D)) {
4613 CheckAbstractClassUsage(Info,
4614 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4615 }
4616 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00004617}
4618
Hans Wennborg853ae942014-05-30 16:59:42 +00004619/// \brief Check class-level dllimport/dllexport attribute.
4620static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) {
4621 Attr *ClassAttr = getDLLAttr(Class);
Hans Wennborg205c39b2014-08-23 22:34:43 +00004622
4623 // MSVC inherits DLL attributes to partial class template specializations.
4624 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
4625 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4626 if (Attr *TemplateAttr =
4627 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
4628 auto *A = cast<InheritableAttr>(TemplateAttr->clone(S.getASTContext()));
4629 A->setInherited(true);
4630 ClassAttr = A;
4631 }
4632 }
4633 }
4634
Hans Wennborg853ae942014-05-30 16:59:42 +00004635 if (!ClassAttr)
4636 return;
4637
Hans Wennborg8313c762014-11-03 16:09:16 +00004638 if (!Class->isExternallyVisible()) {
4639 S.Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
4640 << Class << ClassAttr;
4641 return;
4642 }
4643
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004644 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4645 !ClassAttr->isInherited()) {
4646 // Diagnose dll attributes on members of class with dll attribute.
4647 for (Decl *Member : Class->decls()) {
4648 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4649 continue;
4650 InheritableAttr *MemberAttr = getDLLAttr(Member);
4651 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4652 continue;
4653
4654 S.Diag(MemberAttr->getLocation(),
4655 diag::err_attribute_dll_member_of_dll_class)
4656 << MemberAttr << ClassAttr;
4657 S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4658 Member->setInvalidDecl();
4659 }
4660 }
4661
4662 if (Class->getDescribedClassTemplate())
4663 // Don't inherit dll attribute until the template is instantiated.
4664 return;
4665
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004666 // The class is either imported or exported.
4667 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4668 const bool ClassImported = !ClassExported;
Hans Wennborg853ae942014-05-30 16:59:42 +00004669
4670 // Force declaration of implicit members so they can inherit the attribute.
4671 S.ForceDeclarationOfImplicitMembers(Class);
4672
4673 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4674 // seem to be true in practice?
4675
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004676 TemplateSpecializationKind TSK =
4677 Class->getTemplateSpecializationKind();
4678
Hans Wennborg853ae942014-05-30 16:59:42 +00004679 for (Decl *Member : Class->decls()) {
Hans Wennborge8ad3832014-06-11 22:44:39 +00004680 VarDecl *VD = dyn_cast<VarDecl>(Member);
4681 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4682
4683 // Only methods and static fields inherit the attributes.
4684 if (!VD && !MD)
Hans Wennborg853ae942014-05-30 16:59:42 +00004685 continue;
Hans Wennborge8ad3832014-06-11 22:44:39 +00004686
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004687 if (MD) {
4688 // Don't process deleted methods.
4689 if (MD->isDeleted())
4690 continue;
Hans Wennborg853ae942014-05-30 16:59:42 +00004691
Hans Wennborg606bd6d2014-11-03 14:24:45 +00004692 if (MD->isMoveAssignmentOperator() && ClassImported && MD->isInlined()) {
4693 // Current MSVC versions don't export the move assignment operators, so
4694 // don't attempt to import them if we have a definition.
4695 continue;
4696 }
4697
4698 if (MD->isInlined() && ClassImported &&
4699 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4700 // MinGW does not import inline functions.
4701 continue;
4702 }
Hans Wennborge8ad3832014-06-11 22:44:39 +00004703 }
4704
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00004705 if (!getDLLAttr(Member)) {
Hans Wennborg496524b2014-05-31 02:08:49 +00004706 auto *NewAttr =
4707 cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
4708 NewAttr->setInherited(true);
4709 Member->addAttr(NewAttr);
4710 }
Hans Wennborg853ae942014-05-30 16:59:42 +00004711
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004712 if (MD && ClassExported) {
4713 if (MD->isUserProvided()) {
4714 // Instantiate non-default methods..
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004715
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004716 // .. except for certain kinds of template specializations.
4717 if (TSK == TSK_ExplicitInstantiationDeclaration)
4718 continue;
4719 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4720 continue;
Hans Wennborg334e4ff2014-08-21 01:14:01 +00004721
Hans Wennborg2f9e2932014-08-23 21:10:39 +00004722 S.MarkFunctionReferenced(Class->getLocation(), MD);
4723 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4724 MD->isCopyAssignmentOperator() ||
4725 MD->isMoveAssignmentOperator()) {
4726 // Instantiate non-trivial or explicitly defaulted methods, and the
4727 // copy assignment / move assignment operators.
4728 S.MarkFunctionReferenced(Class->getLocation(), MD);
4729 // Resolve its exception specification; CodeGen needs it.
4730 auto *FPT = MD->getType()->getAs<FunctionProtoType>();
4731 S.ResolveExceptionSpec(Class->getLocation(), FPT);
4732 S.ActOnFinishInlineMethodDef(MD);
Hans Wennborg853ae942014-05-30 16:59:42 +00004733 }
4734 }
4735 }
4736}
4737
Douglas Gregorc99f1552009-12-03 18:33:45 +00004738/// \brief Perform semantic checks on a class definition that has been
4739/// completing, introducing implicitly-declared members, checking for
4740/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004741void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00004742 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00004743 return;
4744
John McCall02db245d2010-08-18 09:41:07 +00004745 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4746 AbstractUsageInfo Info(*this, Record);
4747 CheckAbstractClassUsage(Info, Record);
4748 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00004749
4750 // If this is not an aggregate type and has no user-declared constructor,
4751 // complain about any non-static data members of reference or const scalar
4752 // type, since they will never get initializers.
4753 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00004754 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4755 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004756 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004757 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004758 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004759 continue;
4760
Douglas Gregor454a5b62010-04-15 00:00:53 +00004761 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00004762 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00004763 if (!Complained) {
4764 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4765 << Record->getTagKind() << Record;
4766 Complained = true;
4767 }
4768
4769 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4770 << F->getType()->isReferenceType()
4771 << F->getDeclName();
4772 }
4773 }
4774 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004775
Anders Carlssone771e762011-01-25 18:08:22 +00004776 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00004777 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00004778
4779 if (Record->getIdentifier()) {
4780 // C++ [class.mem]p13:
4781 // If T is the name of a class, then each of the following shall have a
4782 // name different from T:
4783 // - every member of every anonymous union that is a member of class T.
4784 //
4785 // C++ [class.mem]p14:
4786 // In addition, if class T has a user-declared constructor (12.1), every
4787 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00004788 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4789 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4790 ++I) {
4791 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00004792 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4793 isa<IndirectFieldDecl>(D)) {
4794 Diag(D->getLocation(), diag::err_member_name_of_class)
4795 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00004796 break;
4797 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00004798 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00004799 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004800
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00004801 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00004802 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004803 CXXDestructorDecl *dtor = Record->getDestructor();
David Blaikie04e2e662014-05-09 22:02:28 +00004804 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4805 !Record->hasAttr<FinalAttr>())
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00004806 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4807 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4808 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004809
David Majnemera5433082013-10-18 00:33:31 +00004810 if (Record->isAbstract()) {
4811 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4812 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4813 << FA->isSpelledAsSealed();
4814 DiagnoseAbstractType(Record);
4815 }
David Blaikie348df502012-09-21 03:21:07 +00004816 }
4817
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004818 bool HasMethodWithOverrideControl = false,
4819 HasOverridingMethodWithoutOverrideControl = false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004820 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004821 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00004822 // See if a method overloads virtual methods in a base
4823 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00004824 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004825 DiagnoseHiddenVirtualMethods(M);
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004826 if (M->hasAttr<OverrideAttr>())
4827 HasMethodWithOverrideControl = true;
4828 else if (M->size_overridden_methods() > 0)
4829 HasOverridingMethodWithoutOverrideControl = true;
Richard Smithbd305122012-12-11 01:14:52 +00004830 // Check whether the explicitly-defaulted special members are valid.
4831 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00004832 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004833
4834 // For an explicitly defaulted or deleted special member, we defer
4835 // determining triviality until the class is complete. That time is now!
4836 if (!M->isImplicit() && !M->isUserProvided()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004837 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004838 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004839 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00004840
4841 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00004842 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00004843 }
4844 }
4845 }
4846 }
4847
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00004848 if (HasMethodWithOverrideControl &&
4849 HasOverridingMethodWithoutOverrideControl) {
4850 // At least one method has the 'override' control declared.
4851 // Diagnose all other overridden methods which do not have 'override' specified on them.
4852 for (auto *M : Record->methods())
4853 DiagnoseAbsenceOfOverrideControl(M);
4854 }
Richard Smithbd305122012-12-11 01:14:52 +00004855 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4856 // function that is not a constructor declares that member function to be
4857 // const. [...] The class of which that function is a member shall be
4858 // a literal type.
4859 //
4860 // If the class has virtual bases, any constexpr members will already have
4861 // been diagnosed by the checks performed on the member declaration, so
4862 // suppress this (less useful) diagnostic.
4863 //
4864 // We delay this until we know whether an explicitly-defaulted (or deleted)
4865 // destructor for the class is trivial.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004866 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smithbd305122012-12-11 01:14:52 +00004867 !Record->isLiteral() && !Record->getNumVBases()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00004868 for (const auto *M : Record->methods()) {
4869 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) {
Richard Smithbd305122012-12-11 01:14:52 +00004870 switch (Record->getTemplateSpecializationKind()) {
4871 case TSK_ImplicitInstantiation:
4872 case TSK_ExplicitInstantiationDeclaration:
4873 case TSK_ExplicitInstantiationDefinition:
4874 // If a template instantiates to a non-literal type, but its members
4875 // instantiate to constexpr functions, the template is technically
4876 // ill-formed, but we allow it for sanity.
4877 continue;
4878
4879 case TSK_Undeclared:
4880 case TSK_ExplicitSpecialization:
4881 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4882 diag::err_constexpr_method_non_literal);
4883 break;
4884 }
4885
4886 // Only produce one error per class.
4887 break;
4888 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004889 }
4890 }
Sebastian Redl08905022011-02-05 19:23:19 +00004891
John McCall95833f32014-02-27 20:30:49 +00004892 // ms_struct is a request to use the same ABI rules as MSVC. Check
4893 // whether this class uses any C++ features that are implemented
4894 // completely differently in MSVC, and if so, emit a diagnostic.
4895 // That diagnostic defaults to an error, but we allow projects to
4896 // map it down to a warning (or ignore it). It's a fairly common
4897 // practice among users of the ms_struct pragma to mass-annotate
4898 // headers, sweeping up a bunch of types that the project doesn't
4899 // really rely on MSVC-compatible layout for. We must therefore
4900 // support "ms_struct except for C++ stuff" as a secondary ABI.
4901 if (Record->isMsStruct(Context) &&
4902 (Record->isPolymorphic() || Record->getNumBases())) {
4903 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00004904 }
4905
Richard Smithc2bc61b2013-03-18 21:12:30 +00004906 // Declare inheriting constructors. We do this eagerly here because:
4907 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redl08905022011-02-05 19:23:19 +00004908 // constructors from different classes.
4909 // - The lazy declaration of the other implicit constructors is so as to not
4910 // waste space and performance on classes that are not meant to be
4911 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smithc2bc61b2013-03-18 21:12:30 +00004912 // have inheriting constructors.
4913 DeclareInheritingConstructors(Record);
Hans Wennborg853ae942014-05-30 16:59:42 +00004914
4915 checkDLLAttribute(*this, Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00004916}
4917
Richard Smith41c35d62013-11-27 03:39:20 +00004918/// Look up the special member function that would be called by a special
4919/// member function for a subobject of class type.
4920///
4921/// \param Class The class type of the subobject.
4922/// \param CSM The kind of special member function.
4923/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4924/// \param ConstRHS True if this is a copy operation with a const object
4925/// on its RHS, that is, if the argument to the outer special member
4926/// function is 'const' and this is not a field marked 'mutable'.
4927static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4928 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4929 unsigned FieldQuals, bool ConstRHS) {
4930 unsigned LHSQuals = 0;
4931 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4932 LHSQuals = FieldQuals;
4933
4934 unsigned RHSQuals = FieldQuals;
4935 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4936 RHSQuals = 0;
4937 else if (ConstRHS)
4938 RHSQuals |= Qualifiers::Const;
4939
4940 return S.LookupSpecialMember(Class, CSM,
4941 RHSQuals & Qualifiers::Const,
4942 RHSQuals & Qualifiers::Volatile,
4943 false,
4944 LHSQuals & Qualifiers::Const,
4945 LHSQuals & Qualifiers::Volatile);
4946}
4947
Richard Smithb5800092012-06-10 05:43:50 +00004948/// Is the special member function which would be selected to perform the
4949/// specified operation on the specified class type a constexpr constructor?
4950static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4951 Sema::CXXSpecialMember CSM,
Richard Smith41c35d62013-11-27 03:39:20 +00004952 unsigned Quals, bool ConstRHS) {
Richard Smithb5800092012-06-10 05:43:50 +00004953 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00004954 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00004955 if (!SMOR || !SMOR->getMethod())
4956 // A constructor we wouldn't select can't be "involved in initializing"
4957 // anything.
4958 return true;
4959 return SMOR->getMethod()->isConstexpr();
4960}
4961
4962/// Determine whether the specified special member function would be constexpr
4963/// if it were implicitly defined.
4964static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4965 Sema::CXXSpecialMember CSM,
4966 bool ConstArg) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004967 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00004968 return false;
4969
4970 // C++11 [dcl.constexpr]p4:
4971 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00004972 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00004973 switch (CSM) {
4974 case Sema::CXXDefaultConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004975 // Since default constructor lookup is essentially trivial (and cannot
4976 // involve, for instance, template instantiation), we compute whether a
4977 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4978 //
4979 // This is important for performance; we need to know whether the default
4980 // constructor is constexpr to determine whether the type is a literal type.
4981 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4982
Richard Smithb5800092012-06-10 05:43:50 +00004983 case Sema::CXXCopyConstructor:
4984 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00004985 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00004986 break;
4987
4988 case Sema::CXXCopyAssignment:
4989 case Sema::CXXMoveAssignment:
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004990 if (!S.getLangOpts().CPlusPlus14)
Richard Smith99005e62013-05-07 03:19:20 +00004991 return false;
4992 // In C++1y, we need to perform overload resolution.
4993 Ctor = false;
4994 break;
4995
Richard Smithb5800092012-06-10 05:43:50 +00004996 case Sema::CXXDestructor:
4997 case Sema::CXXInvalid:
4998 return false;
4999 }
5000
5001 // -- if the class is a non-empty union, or for each non-empty anonymous
5002 // union member of a non-union class, exactly one non-static data member
5003 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00005004 //
5005 // If we squint, this is guaranteed, since exactly one non-static data member
5006 // will be initialized (if the constructor isn't deleted), we just don't know
5007 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00005008 if (Ctor && ClassDecl->isUnion())
Richard Smith4086a132012-06-10 07:07:24 +00005009 return true;
Richard Smithb5800092012-06-10 05:43:50 +00005010
5011 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00005012 if (Ctor && ClassDecl->getNumVBases())
5013 return false;
5014
5015 // C++1y [class.copy]p26:
5016 // -- [the class] is a literal type, and
5017 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00005018 return false;
5019
5020 // -- every constructor involved in initializing [...] base class
5021 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00005022 // -- the assignment operator selected to copy/move each direct base
5023 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00005024 for (const auto &B : ClassDecl->bases()) {
5025 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00005026 if (!BaseType) continue;
5027
5028 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00005029 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smithb5800092012-06-10 05:43:50 +00005030 return false;
5031 }
5032
5033 // -- every constructor involved in initializing non-static data members
5034 // [...] shall be a constexpr constructor;
5035 // -- every non-static data member and base class sub-object shall be
5036 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00005037 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00005038 // thereof), the assignment operator selected to copy/move that member is
5039 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005040 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00005041 if (F->isInvalidDecl())
5042 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00005043 QualType BaseType = S.Context.getBaseElementType(F->getType());
5044 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00005045 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00005046 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
5047 BaseType.getCVRQualifiers(),
5048 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00005049 return false;
Richard Smithb5800092012-06-10 05:43:50 +00005050 }
5051 }
5052
5053 // All OK, it's constexpr!
5054 return true;
5055}
5056
Richard Smithd3b5c9082012-07-27 04:22:15 +00005057static Sema::ImplicitExceptionSpecification
5058computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
5059 switch (S.getSpecialMember(MD)) {
5060 case Sema::CXXDefaultConstructor:
5061 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
5062 case Sema::CXXCopyConstructor:
5063 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
5064 case Sema::CXXCopyAssignment:
5065 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
5066 case Sema::CXXMoveConstructor:
5067 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
5068 case Sema::CXXMoveAssignment:
5069 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
5070 case Sema::CXXDestructor:
5071 return S.ComputeDefaultedDtorExceptionSpec(MD);
5072 case Sema::CXXInvalid:
5073 break;
5074 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00005075 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
5076 "only special members have implicit exception specs");
5077 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00005078}
5079
Reid Kleckner78af0702013-08-27 23:08:25 +00005080static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
5081 CXXMethodDecl *MD) {
5082 FunctionProtoType::ExtProtoInfo EPI;
5083
5084 // Build an exception specification pointing back at this member.
Richard Smith8acb4282014-07-31 21:57:55 +00005085 EPI.ExceptionSpec.Type = EST_Unevaluated;
5086 EPI.ExceptionSpec.SourceDecl = MD;
Reid Kleckner78af0702013-08-27 23:08:25 +00005087
5088 // Set the calling convention to the default for C++ instance methods.
5089 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
5090 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5091 /*IsCXXMethod=*/true));
5092 return EPI;
5093}
5094
Richard Smithd3b5c9082012-07-27 04:22:15 +00005095void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
5096 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
5097 if (FPT->getExceptionSpecType() != EST_Unevaluated)
5098 return;
5099
Richard Smith7f782272012-07-30 23:48:14 +00005100 // Evaluate the exception specification.
Richard Smith8acb4282014-07-31 21:57:55 +00005101 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
Richard Smith564417a2014-03-20 21:47:22 +00005102
Richard Smith7f782272012-07-30 23:48:14 +00005103 // Update the type of the special member to use it.
Richard Smith8acb4282014-07-31 21:57:55 +00005104 UpdateExceptionSpec(MD, ESI);
Richard Smith7f782272012-07-30 23:48:14 +00005105
5106 // A user-provided destructor can be defined outside the class. When that
5107 // happens, be sure to update the exception specification on both
5108 // declarations.
5109 const FunctionProtoType *CanonicalFPT =
5110 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
5111 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smith8acb4282014-07-31 21:57:55 +00005112 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00005113}
5114
Richard Smithb9e90b12012-05-15 04:39:51 +00005115void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
5116 CXXRecordDecl *RD = MD->getParent();
5117 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005118
Richard Smithb9e90b12012-05-15 04:39:51 +00005119 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
5120 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00005121
5122 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00005123 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00005124 bool First = MD == MD->getCanonicalDecl();
5125
5126 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00005127
5128 // C++11 [dcl.fct.def.default]p1:
5129 // A function that is explicitly defaulted shall
5130 // -- be a special member function (checked elsewhere),
5131 // -- have the same type (except for ref-qualifiers, and except that a
5132 // copy operation can take a non-const reference) as an implicit
5133 // declaration, and
5134 // -- not have default arguments.
5135 unsigned ExpectedParams = 1;
5136 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
5137 ExpectedParams = 0;
5138 if (MD->getNumParams() != ExpectedParams) {
5139 // This also checks for default arguments: a copy or move constructor with a
5140 // default argument is classified as a default constructor, and assignment
5141 // operations and destructors can't have default arguments.
5142 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
5143 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00005144 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00005145 } else if (MD->isVariadic()) {
5146 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
5147 << CSM << MD->getSourceRange();
5148 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00005149 }
5150
Richard Smithb9e90b12012-05-15 04:39:51 +00005151 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00005152
Richard Smithb5800092012-06-10 05:43:50 +00005153 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00005154 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00005155 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00005156 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00005157 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00005158
Richard Smithb9e90b12012-05-15 04:39:51 +00005159 QualType ReturnType = Context.VoidTy;
5160 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
5161 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00005162 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00005163 QualType ExpectedReturnType =
5164 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
5165 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
5166 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
5167 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
5168 HadError = true;
5169 }
5170
5171 // A defaulted special member cannot have cv-qualifiers.
5172 if (Type->getTypeQuals()) {
5173 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005174 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
Richard Smithb9e90b12012-05-15 04:39:51 +00005175 HadError = true;
5176 }
5177 }
5178
5179 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00005180 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00005181 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00005182 if (ExpectedParams && ArgType->isReferenceType()) {
5183 // Argument must be reference to possibly-const T.
5184 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00005185 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00005186
5187 if (ReferentType.isVolatileQualified()) {
5188 Diag(MD->getLocation(),
5189 diag::err_defaulted_special_member_volatile_param) << CSM;
5190 HadError = true;
5191 }
5192
Richard Smithb5800092012-06-10 05:43:50 +00005193 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00005194 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
5195 Diag(MD->getLocation(),
5196 diag::err_defaulted_special_member_copy_const_param)
5197 << (CSM == CXXCopyAssignment);
5198 // FIXME: Explain why this special member can't be const.
5199 } else {
5200 Diag(MD->getLocation(),
5201 diag::err_defaulted_special_member_move_const_param)
5202 << (CSM == CXXMoveAssignment);
5203 }
5204 HadError = true;
5205 }
Richard Smithb9e90b12012-05-15 04:39:51 +00005206 } else if (ExpectedParams) {
5207 // A copy assignment operator can take its argument by value, but a
5208 // defaulted one cannot.
5209 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00005210 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00005211 HadError = true;
5212 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00005213
Richard Smithcc36f692011-12-22 02:22:31 +00005214 // C++11 [dcl.fct.def.default]p2:
5215 // An explicitly-defaulted function may be declared constexpr only if it
5216 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00005217 // Do not apply this rule to members of class templates, since core issue 1358
5218 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00005219 // functions which cannot be constexpr (for non-constructors in C++11 and for
5220 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00005221 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5222 HasConstParam);
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005223 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
Richard Smith99005e62013-05-07 03:19:20 +00005224 : isa<CXXConstructorDecl>(MD)) &&
5225 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00005226 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5227 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00005228 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00005229 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00005230 }
Richard Smithbd305122012-12-11 01:14:52 +00005231
Richard Smithcc36f692011-12-22 02:22:31 +00005232 // and may have an explicit exception-specification only if it is compatible
5233 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00005234 if (Type->hasExceptionSpec()) {
5235 // Delay the check if this is the first declaration of the special member,
5236 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00005237 if (First) {
5238 // If the exception specification needs to be instantiated, do so now,
5239 // before we clobber it with an EST_Unevaluated specification below.
5240 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5241 InstantiateExceptionSpec(MD->getLocStart(), MD);
5242 Type = MD->getType()->getAs<FunctionProtoType>();
5243 }
Richard Smithbd305122012-12-11 01:14:52 +00005244 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00005245 } else
Richard Smithbd305122012-12-11 01:14:52 +00005246 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5247 }
Richard Smithcc36f692011-12-22 02:22:31 +00005248
5249 // If a function is explicitly defaulted on its first declaration,
5250 if (First) {
5251 // -- it is implicitly considered to be constexpr if the implicit
5252 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00005253 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00005254
Richard Smithb9e90b12012-05-15 04:39:51 +00005255 // -- it is implicitly considered to have the same exception-specification
5256 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00005257 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00005258 EPI.ExceptionSpec.Type = EST_Unevaluated;
5259 EPI.ExceptionSpec.SourceDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00005260 MD->setType(Context.getFunctionType(ReturnType,
Craig Topper5fc8fc22014-08-27 06:28:36 +00005261 llvm::makeArrayRef(&ArgType,
Jordan Rose5c382722013-03-08 21:51:21 +00005262 ExpectedParams),
5263 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00005264 }
5265
Richard Smithb9e90b12012-05-15 04:39:51 +00005266 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00005267 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00005268 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00005269 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00005270 // C++11 [dcl.fct.def.default]p4:
5271 // [For a] user-provided explicitly-defaulted function [...] if such a
5272 // function is implicitly defined as deleted, the program is ill-formed.
5273 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith566184a2014-01-22 20:09:10 +00005274 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00005275 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00005276 }
5277 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00005278
Richard Smithb9e90b12012-05-15 04:39:51 +00005279 if (HadError)
5280 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00005281}
5282
Richard Smithbd305122012-12-11 01:14:52 +00005283/// Check whether the exception specification provided for an
5284/// explicitly-defaulted special member matches the exception specification
5285/// that would have been generated for an implicit special member, per
5286/// C++11 [dcl.fct.def.default]p2.
5287void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5288 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
5289 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00005290 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5291 /*IsCXXMethod=*/true);
5292 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smith8acb4282014-07-31 21:57:55 +00005293 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5294 .getExceptionSpec();
Richard Smithbd305122012-12-11 01:14:52 +00005295 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005296 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00005297
5298 // Ensure that it matches.
5299 CheckEquivalentExceptionSpec(
5300 PDiag(diag::err_incorrect_defaulted_exception_spec)
5301 << getSpecialMember(MD), PDiag(),
5302 ImplicitType, SourceLocation(),
5303 SpecifiedType, MD->getLocation());
5304}
5305
Alp Tokerae3a9442013-10-18 05:54:19 +00005306void Sema::CheckDelayedMemberExceptionSpecs() {
5307 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
5308 2> Checks;
5309 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
Richard Smithbd305122012-12-11 01:14:52 +00005310
Alp Tokerae3a9442013-10-18 05:54:19 +00005311 std::swap(Checks, DelayedDestructorExceptionSpecChecks);
5312 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5313
5314 // Perform any deferred checking of exception specifications for virtual
5315 // destructors.
5316 for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
5317 const CXXDestructorDecl *Dtor = Checks[i].first;
5318 assert(!Dtor->getParent()->isDependentType() &&
5319 "Should not ever add destructors of templates into the list.");
5320 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
5321 }
5322
5323 // Check that any explicitly-defaulted methods have exception specifications
5324 // compatible with their implicit exception specifications.
5325 for (unsigned I = 0, N = Specs.size(); I != N; ++I)
5326 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
5327 Specs[I].second);
Richard Smithbd305122012-12-11 01:14:52 +00005328}
5329
Richard Smithd951a1d2012-02-18 02:02:13 +00005330namespace {
5331struct SpecialMemberDeletionInfo {
5332 Sema &S;
5333 CXXMethodDecl *MD;
5334 Sema::CXXSpecialMember CSM;
Richard Smith852265f2012-03-30 20:53:28 +00005335 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00005336
5337 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00005338 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00005339 SourceLocation Loc;
5340
5341 bool AllFieldsAreConst;
5342
5343 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith852265f2012-03-30 20:53:28 +00005344 Sema::CXXSpecialMember CSM, bool Diagnose)
5345 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smithd951a1d2012-02-18 02:02:13 +00005346 IsConstructor(false), IsAssignment(false), IsMove(false),
Richard Smith41c35d62013-11-27 03:39:20 +00005347 ConstArg(false), Loc(MD->getLocation()),
Richard Smithd951a1d2012-02-18 02:02:13 +00005348 AllFieldsAreConst(true) {
5349 switch (CSM) {
5350 case Sema::CXXDefaultConstructor:
5351 case Sema::CXXCopyConstructor:
5352 IsConstructor = true;
5353 break;
5354 case Sema::CXXMoveConstructor:
5355 IsConstructor = true;
5356 IsMove = true;
5357 break;
5358 case Sema::CXXCopyAssignment:
5359 IsAssignment = true;
5360 break;
5361 case Sema::CXXMoveAssignment:
5362 IsAssignment = true;
5363 IsMove = true;
5364 break;
5365 case Sema::CXXDestructor:
5366 break;
5367 case Sema::CXXInvalid:
5368 llvm_unreachable("invalid special member kind");
5369 }
5370
5371 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00005372 if (const ReferenceType *RT =
5373 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5374 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00005375 }
5376 }
5377
5378 bool inUnion() const { return MD->getParent()->isUnion(); }
5379
5380 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00005381 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00005382 unsigned Quals, bool IsMutable) {
5383 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5384 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00005385 }
5386
Richard Smith852265f2012-03-30 20:53:28 +00005387 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00005388
Richard Smith852265f2012-03-30 20:53:28 +00005389 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00005390 bool shouldDeleteForField(FieldDecl *FD);
5391 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00005392
Richard Smithaf136f82012-07-18 03:51:16 +00005393 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5394 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00005395 bool shouldDeleteForSubobjectCall(Subobject Subobj,
5396 Sema::SpecialMemberOverloadResult *SMOR,
5397 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00005398
5399 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00005400};
5401}
5402
John McCalld4274212012-04-09 20:53:23 +00005403/// Is the given special member inaccessible when used on the given
5404/// sub-object.
5405bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5406 CXXMethodDecl *target) {
5407 /// If we're operating on a base class, the object type is the
5408 /// type of this special member.
5409 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005410 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00005411 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5412 objectTy = S.Context.getTypeDeclType(MD->getParent());
5413 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5414
5415 // If we're operating on a field, the object type is the type of the field.
5416 } else {
5417 objectTy = S.Context.getTypeDeclType(target->getParent());
5418 }
5419
5420 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5421}
5422
Richard Smith852265f2012-03-30 20:53:28 +00005423/// Check whether we should delete a special member due to the implicit
5424/// definition containing a call to a special member of a subobject.
5425bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5426 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5427 bool IsDtorCallInCtor) {
5428 CXXMethodDecl *Decl = SMOR->getMethod();
5429 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5430
5431 int DiagKind = -1;
5432
5433 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5434 DiagKind = !Decl ? 0 : 1;
5435 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5436 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00005437 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00005438 DiagKind = 3;
5439 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5440 !Decl->isTrivial()) {
5441 // A member of a union must have a trivial corresponding special member.
5442 // As a weird special case, a destructor call from a union's constructor
5443 // must be accessible and non-deleted, but need not be trivial. Such a
5444 // destructor is never actually called, but is semantically checked as
5445 // if it were.
5446 DiagKind = 4;
5447 }
5448
5449 if (DiagKind == -1)
5450 return false;
5451
5452 if (Diagnose) {
5453 if (Field) {
5454 S.Diag(Field->getLocation(),
5455 diag::note_deleted_special_member_class_subobject)
5456 << CSM << MD->getParent() << /*IsField*/true
5457 << Field << DiagKind << IsDtorCallInCtor;
5458 } else {
5459 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5460 S.Diag(Base->getLocStart(),
5461 diag::note_deleted_special_member_class_subobject)
5462 << CSM << MD->getParent() << /*IsField*/false
5463 << Base->getType() << DiagKind << IsDtorCallInCtor;
5464 }
5465
5466 if (DiagKind == 1)
5467 S.NoteDeletedFunction(Decl);
5468 // FIXME: Explain inaccessibility if DiagKind == 3.
5469 }
5470
5471 return true;
5472}
5473
Richard Smith921bd202012-02-26 09:11:52 +00005474/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00005475/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00005476bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00005477 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00005478 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00005479 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00005480
5481 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00005482 // -- any direct or virtual base class, or non-static data member with no
5483 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00005484 // either M has no default constructor or overload resolution as applied
5485 // to M's default constructor results in an ambiguity or in a function
5486 // that is deleted or inaccessible
5487 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5488 // -- a direct or virtual base class B that cannot be copied/moved because
5489 // overload resolution, as applied to B's corresponding special member,
5490 // results in an ambiguity or a function that is deleted or inaccessible
5491 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00005492 // C++11 [class.dtor]p5:
5493 // -- any direct or virtual base class [...] has a type with a destructor
5494 // that is deleted or inaccessible
5495 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005496 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00005497 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5498 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005499 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005500
Richard Smith852265f2012-03-30 20:53:28 +00005501 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5502 // -- any direct or virtual base class or non-static data member has a
5503 // type with a destructor that is deleted or inaccessible
5504 if (IsConstructor) {
5505 Sema::SpecialMemberOverloadResult *SMOR =
5506 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5507 false, false, false, false, false);
5508 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5509 return true;
5510 }
5511
Richard Smith921bd202012-02-26 09:11:52 +00005512 return false;
5513}
5514
5515/// Check whether we should delete a special member function due to the class
5516/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00005517bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005518 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smithaf136f82012-07-18 03:51:16 +00005519 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00005520}
5521
5522/// Check whether we should delete a special member function due to the class
5523/// having a particular non-static data member.
5524bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5525 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5526 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5527
5528 if (CSM == Sema::CXXDefaultConstructor) {
5529 // For a default constructor, all references must be initialized in-class
5530 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00005531 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5532 if (Diagnose)
5533 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5534 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005535 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005536 }
Richard Smith619ecdc2012-02-27 06:07:25 +00005537 // C++11 [class.ctor]p5: any non-variant non-static data member of
5538 // const-qualified type (or array thereof) with no
5539 // brace-or-equal-initializer does not have a user-provided default
5540 // constructor.
5541 if (!inUnion() && FieldType.isConstQualified() &&
5542 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00005543 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5544 if (Diagnose)
5545 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005546 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00005547 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005548 }
5549
5550 if (inUnion() && !FieldType.isConstQualified())
5551 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005552 } else if (CSM == Sema::CXXCopyConstructor) {
5553 // For a copy constructor, data members must not be of rvalue reference
5554 // type.
Richard Smith852265f2012-03-30 20:53:28 +00005555 if (FieldType->isRValueReferenceType()) {
5556 if (Diagnose)
5557 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5558 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00005559 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005560 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005561 } else if (IsAssignment) {
5562 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00005563 if (FieldType->isReferenceType()) {
5564 if (Diagnose)
5565 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5566 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00005567 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005568 }
5569 if (!FieldRecord && FieldType.isConstQualified()) {
5570 // C++11 [class.copy]p23:
5571 // -- a non-static data member of const non-class type (or array thereof)
5572 if (Diagnose)
5573 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00005574 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00005575 return true;
5576 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005577 }
5578
5579 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005580 // Some additional restrictions exist on the variant members.
5581 if (!inUnion() && FieldRecord->isUnion() &&
5582 FieldRecord->isAnonymousStructOrUnion()) {
5583 bool AllVariantFieldsAreConst = true;
5584
Richard Smith5704fe82012-03-29 19:00:10 +00005585 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005586 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00005587 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00005588
5589 if (!UnionFieldType.isConstQualified())
5590 AllVariantFieldsAreConst = false;
5591
Richard Smith921bd202012-02-26 09:11:52 +00005592 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5593 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005594 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00005595 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00005596 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005597 }
5598
5599 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00005600 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005601 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005602 if (Diagnose)
5603 S.Diag(FieldRecord->getLocation(),
5604 diag::note_deleted_default_ctor_all_const)
5605 << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00005606 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005607 }
Richard Smithd951a1d2012-02-18 02:02:13 +00005608
Richard Smith5704fe82012-03-29 19:00:10 +00005609 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00005610 // This is technically non-conformant, but sanity demands it.
5611 return false;
5612 }
5613
Richard Smithaf136f82012-07-18 03:51:16 +00005614 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5615 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00005616 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00005617 }
5618
5619 return false;
5620}
5621
5622/// C++11 [class.ctor] p5:
5623/// A defaulted default constructor for a class X is defined as deleted if
5624/// X is a union and all of its variant members are of const-qualified type.
5625bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00005626 // This is a silly definition, because it gives an empty union a deleted
5627 // default constructor. Don't do that.
Richard Smith852265f2012-03-30 20:53:28 +00005628 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005629 !MD->getParent()->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00005630 if (Diagnose)
5631 S.Diag(MD->getParent()->getLocation(),
5632 diag::note_deleted_default_ctor_all_const)
5633 << MD->getParent() << /*not anonymous union*/0;
5634 return true;
5635 }
5636 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00005637}
5638
5639/// Determine whether a defaulted special member function should be defined as
5640/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5641/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00005642bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5643 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00005644 if (MD->isInvalidDecl())
5645 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00005646 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00005647 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005648 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00005649 return false;
5650
Richard Smithd951a1d2012-02-18 02:02:13 +00005651 // C++11 [expr.lambda.prim]p19:
5652 // The closure type associated with a lambda-expression has a
5653 // deleted (8.4.3) default constructor and a deleted copy
5654 // assignment operator.
5655 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00005656 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5657 if (Diagnose)
5658 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00005659 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005660 }
5661
Richard Smith6f1e2c62012-04-02 20:59:25 +00005662 // For an anonymous struct or union, the copy and assignment special members
5663 // will never be used, so skip the check. For an anonymous union declared at
5664 // namespace scope, the constructor and destructor are used.
5665 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5666 RD->isAnonymousStructOrUnion())
5667 return false;
5668
Richard Smith852265f2012-03-30 20:53:28 +00005669 // C++11 [class.copy]p7, p18:
5670 // If the class definition declares a move constructor or move assignment
5671 // operator, an implicitly declared copy constructor or copy assignment
5672 // operator is defined as deleted.
5673 if (MD->isImplicit() &&
5674 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005675 CXXMethodDecl *UserDeclaredMove = nullptr;
Richard Smith852265f2012-03-30 20:53:28 +00005676
5677 // In Microsoft mode, a user-declared move only causes the deletion of the
5678 // corresponding copy operation, not both copy operations.
5679 if (RD->hasUserDeclaredMoveConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005680 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00005681 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005682
5683 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005684 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005685 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005686 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005687 break;
5688 }
5689 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005690 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005691 } else if (RD->hasUserDeclaredMoveAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00005692 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00005693 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00005694
5695 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005696 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00005697 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005698 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00005699 break;
5700 }
5701 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00005702 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00005703 }
5704
5705 if (UserDeclaredMove) {
5706 Diag(UserDeclaredMove->getLocation(),
5707 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00005708 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00005709 << UserDeclaredMove->isMoveAssignmentOperator();
5710 return true;
5711 }
5712 }
Alexis Huntd6da8762011-10-10 06:18:57 +00005713
Richard Smith6f1e2c62012-04-02 20:59:25 +00005714 // Do access control from the special member function
5715 ContextRAII MethodContext(*this, MD);
5716
Richard Smith921bd202012-02-26 09:11:52 +00005717 // C++11 [class.dtor]p5:
5718 // -- for a virtual destructor, lookup of the non-array deallocation function
5719 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00005720 if (CSM == CXXDestructor && MD->isVirtual()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005721 FunctionDecl *OperatorDelete = nullptr;
Richard Smith921bd202012-02-26 09:11:52 +00005722 DeclarationName Name =
5723 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5724 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith852265f2012-03-30 20:53:28 +00005725 OperatorDelete, false)) {
5726 if (Diagnose)
5727 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00005728 return true;
Richard Smith852265f2012-03-30 20:53:28 +00005729 }
Richard Smith921bd202012-02-26 09:11:52 +00005730 }
5731
Richard Smith852265f2012-03-30 20:53:28 +00005732 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00005733
Aaron Ballman574705e2014-03-13 15:41:46 +00005734 for (auto &BI : RD->bases())
5735 if (!BI.isVirtual() &&
5736 SMI.shouldDeleteForBase(&BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00005737 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005738
Richard Smithd1627032013-07-22 18:06:23 +00005739 // Per DR1611, do not consider virtual bases of constructors of abstract
5740 // classes, since we are not going to construct them.
Richard Smithbc46e432013-07-22 02:56:56 +00005741 if (!RD->isAbstract() || !SMI.IsConstructor) {
Aaron Ballman445a9392014-03-13 16:15:17 +00005742 for (auto &BI : RD->vbases())
5743 if (SMI.shouldDeleteForBase(&BI))
Richard Smithbc46e432013-07-22 02:56:56 +00005744 return true;
5745 }
Alexis Huntea6f0322011-05-11 22:34:38 +00005746
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005747 for (auto *FI : RD->fields())
Richard Smithd951a1d2012-02-18 02:02:13 +00005748 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005749 SMI.shouldDeleteForField(FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00005750 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00005751
Richard Smithd951a1d2012-02-18 02:02:13 +00005752 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00005753 return true;
5754
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005755 if (getLangOpts().CUDA) {
5756 // We should delete the special member in CUDA mode if target inference
5757 // failed.
5758 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
5759 Diagnose);
5760 }
5761
Alexis Huntea6f0322011-05-11 22:34:38 +00005762 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005763}
5764
Richard Smith92f241f2012-12-08 02:53:02 +00005765/// Perform lookup for a special member of the specified kind, and determine
5766/// whether it is trivial. If the triviality can be determined without the
5767/// lookup, skip it. This is intended for use when determining whether a
5768/// special member of a containing object is trivial, and thus does not ever
5769/// perform overload resolution for default constructors.
5770///
5771/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5772/// member that was most likely to be intended to be trivial, if any.
5773static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5774 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00005775 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00005776 if (Selected)
Craig Topperc3ec1492014-05-26 06:22:03 +00005777 *Selected = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005778
5779 switch (CSM) {
5780 case Sema::CXXInvalid:
5781 llvm_unreachable("not a special member");
5782
5783 case Sema::CXXDefaultConstructor:
5784 // C++11 [class.ctor]p5:
5785 // A default constructor is trivial if:
5786 // - all the [direct subobjects] have trivial default constructors
5787 //
5788 // Note, no overload resolution is performed in this case.
5789 if (RD->hasTrivialDefaultConstructor())
5790 return true;
5791
5792 if (Selected) {
5793 // If there's a default constructor which could have been trivial, dig it
5794 // out. Otherwise, if there's any user-provided default constructor, point
5795 // to that as an example of why there's not a trivial one.
Craig Topperc3ec1492014-05-26 06:22:03 +00005796 CXXConstructorDecl *DefCtor = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005797 if (RD->needsImplicitDefaultConstructor())
5798 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005799 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005800 if (!CI->isDefaultConstructor())
5801 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005802 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005803 if (!DefCtor->isUserProvided())
5804 break;
5805 }
5806
5807 *Selected = DefCtor;
5808 }
5809
5810 return false;
5811
5812 case Sema::CXXDestructor:
5813 // C++11 [class.dtor]p5:
5814 // A destructor is trivial if:
5815 // - all the direct [subobjects] have trivial destructors
5816 if (RD->hasTrivialDestructor())
5817 return true;
5818
5819 if (Selected) {
5820 if (RD->needsImplicitDestructor())
5821 S.DeclareImplicitDestructor(RD);
5822 *Selected = RD->getDestructor();
5823 }
5824
5825 return false;
5826
5827 case Sema::CXXCopyConstructor:
5828 // C++11 [class.copy]p12:
5829 // A copy constructor is trivial if:
5830 // - the constructor selected to copy each direct [subobject] is trivial
5831 if (RD->hasTrivialCopyConstructor()) {
5832 if (Quals == Qualifiers::Const)
5833 // We must either select the trivial copy constructor or reach an
5834 // ambiguity; no need to actually perform overload resolution.
5835 return true;
5836 } else if (!Selected) {
5837 return false;
5838 }
5839 // In C++98, we are not supposed to perform overload resolution here, but we
5840 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5841 // cases like B as having a non-trivial copy constructor:
5842 // struct A { template<typename T> A(T&); };
5843 // struct B { mutable A a; };
5844 goto NeedOverloadResolution;
5845
5846 case Sema::CXXCopyAssignment:
5847 // C++11 [class.copy]p25:
5848 // A copy assignment operator is trivial if:
5849 // - the assignment operator selected to copy each direct [subobject] is
5850 // trivial
5851 if (RD->hasTrivialCopyAssignment()) {
5852 if (Quals == Qualifiers::Const)
5853 return true;
5854 } else if (!Selected) {
5855 return false;
5856 }
5857 // In C++98, we are not supposed to perform overload resolution here, but we
5858 // treat that as a language defect.
5859 goto NeedOverloadResolution;
5860
5861 case Sema::CXXMoveConstructor:
5862 case Sema::CXXMoveAssignment:
5863 NeedOverloadResolution:
5864 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005865 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00005866
5867 // The standard doesn't describe how to behave if the lookup is ambiguous.
5868 // We treat it as not making the member non-trivial, just like the standard
5869 // mandates for the default constructor. This should rarely matter, because
5870 // the member will also be deleted.
5871 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5872 return true;
5873
5874 if (!SMOR->getMethod()) {
5875 assert(SMOR->getKind() ==
5876 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5877 return false;
5878 }
5879
5880 // We deliberately don't check if we found a deleted special member. We're
5881 // not supposed to!
5882 if (Selected)
5883 *Selected = SMOR->getMethod();
5884 return SMOR->getMethod()->isTrivial();
5885 }
5886
5887 llvm_unreachable("unknown special method kind");
5888}
5889
Benjamin Kramer3e350262013-02-15 12:30:38 +00005890static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005891 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00005892 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00005893 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00005894
5895 // Look for constructor templates.
5896 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5897 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5898 if (CXXConstructorDecl *CD =
5899 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5900 return CD;
5901 }
5902
Craig Topperc3ec1492014-05-26 06:22:03 +00005903 return nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00005904}
5905
5906/// The kind of subobject we are checking for triviality. The values of this
5907/// enumeration are used in diagnostics.
5908enum TrivialSubobjectKind {
5909 /// The subobject is a base class.
5910 TSK_BaseClass,
5911 /// The subobject is a non-static data member.
5912 TSK_Field,
5913 /// The object is actually the complete object.
5914 TSK_CompleteObject
5915};
5916
5917/// Check whether the special member selected for a given type would be trivial.
5918static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00005919 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00005920 Sema::CXXSpecialMember CSM,
5921 TrivialSubobjectKind Kind,
5922 bool Diagnose) {
5923 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5924 if (!SubRD)
5925 return true;
5926
5927 CXXMethodDecl *Selected;
5928 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005929 ConstRHS, Diagnose ? &Selected : nullptr))
Richard Smith92f241f2012-12-08 02:53:02 +00005930 return true;
5931
5932 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00005933 if (ConstRHS)
5934 SubType.addConst();
5935
Richard Smith92f241f2012-12-08 02:53:02 +00005936 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5937 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5938 << Kind << SubType.getUnqualifiedType();
5939 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5940 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5941 } else if (!Selected)
5942 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5943 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5944 else if (Selected->isUserProvided()) {
5945 if (Kind == TSK_CompleteObject)
5946 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5947 << Kind << SubType.getUnqualifiedType() << CSM;
5948 else {
5949 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5950 << Kind << SubType.getUnqualifiedType() << CSM;
5951 S.Diag(Selected->getLocation(), diag::note_declared_at);
5952 }
5953 } else {
5954 if (Kind != TSK_CompleteObject)
5955 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5956 << Kind << SubType.getUnqualifiedType() << CSM;
5957
5958 // Explain why the defaulted or deleted special member isn't trivial.
5959 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5960 }
5961 }
5962
5963 return false;
5964}
5965
5966/// Check whether the members of a class type allow a special member to be
5967/// trivial.
5968static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5969 Sema::CXXSpecialMember CSM,
5970 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005971 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00005972 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5973 continue;
5974
5975 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5976
5977 // Pretend anonymous struct or union members are members of this class.
5978 if (FI->isAnonymousStructOrUnion()) {
5979 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5980 CSM, ConstArg, Diagnose))
5981 return false;
5982 continue;
5983 }
5984
5985 // C++11 [class.ctor]p5:
5986 // A default constructor is trivial if [...]
5987 // -- no non-static data member of its class has a
5988 // brace-or-equal-initializer
5989 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5990 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005991 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00005992 return false;
5993 }
5994
5995 // Objective C ARC 4.3.5:
5996 // [...] nontrivally ownership-qualified types are [...] not trivially
5997 // default constructible, copy constructible, move constructible, copy
5998 // assignable, move assignable, or destructible [...]
5999 if (S.getLangOpts().ObjCAutoRefCount &&
6000 FieldType.hasNonTrivialObjCLifetime()) {
6001 if (Diagnose)
6002 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
6003 << RD << FieldType.getObjCLifetime();
6004 return false;
6005 }
6006
Richard Smith41c35d62013-11-27 03:39:20 +00006007 bool ConstRHS = ConstArg && !FI->isMutable();
6008 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
6009 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00006010 return false;
6011 }
6012
6013 return true;
6014}
6015
6016/// Diagnose why the specified class does not have a trivial special member of
6017/// the given kind.
6018void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
6019 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00006020
Richard Smith41c35d62013-11-27 03:39:20 +00006021 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
6022 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00006023 TSK_CompleteObject, /*Diagnose*/true);
6024}
6025
6026/// Determine whether a defaulted or deleted special member function is trivial,
6027/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6028/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6029bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
6030 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00006031 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
6032
6033 CXXRecordDecl *RD = MD->getParent();
6034
6035 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00006036
Richard Smith2002bfe2013-11-04 02:02:27 +00006037 // C++11 [class.copy]p12, p25: [DR1593]
6038 // A [special member] is trivial if [...] its parameter-type-list is
6039 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00006040 switch (CSM) {
6041 case CXXDefaultConstructor:
6042 case CXXDestructor:
6043 // Trivial default constructors and destructors cannot have parameters.
6044 break;
6045
6046 case CXXCopyConstructor:
6047 case CXXCopyAssignment: {
6048 // Trivial copy operations always have const, non-volatile parameter types.
6049 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00006050 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00006051 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
6052 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
6053 if (Diagnose)
6054 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6055 << Param0->getSourceRange() << Param0->getType()
6056 << Context.getLValueReferenceType(
6057 Context.getRecordType(RD).withConst());
6058 return false;
6059 }
6060 break;
6061 }
6062
6063 case CXXMoveConstructor:
6064 case CXXMoveAssignment: {
6065 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00006066 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00006067 const RValueReferenceType *RT =
6068 Param0->getType()->getAs<RValueReferenceType>();
6069 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
6070 if (Diagnose)
6071 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6072 << Param0->getSourceRange() << Param0->getType()
6073 << Context.getRValueReferenceType(Context.getRecordType(RD));
6074 return false;
6075 }
6076 break;
6077 }
6078
6079 case CXXInvalid:
6080 llvm_unreachable("not a special member");
6081 }
6082
Richard Smith92f241f2012-12-08 02:53:02 +00006083 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
6084 if (Diagnose)
6085 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
6086 diag::note_nontrivial_default_arg)
6087 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
6088 return false;
6089 }
6090 if (MD->isVariadic()) {
6091 if (Diagnose)
6092 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
6093 return false;
6094 }
6095
6096 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6097 // A copy/move [constructor or assignment operator] is trivial if
6098 // -- the [member] selected to copy/move each direct base class subobject
6099 // is trivial
6100 //
6101 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6102 // A [default constructor or destructor] is trivial if
6103 // -- all the direct base classes have trivial [default constructors or
6104 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00006105 for (const auto &BI : RD->bases())
6106 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00006107 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00006108 return false;
6109
6110 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6111 // A copy/move [constructor or assignment operator] for a class X is
6112 // trivial if
6113 // -- for each non-static data member of X that is of class type (or array
6114 // thereof), the constructor selected to copy/move that member is
6115 // trivial
6116 //
6117 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6118 // A [default constructor or destructor] is trivial if
6119 // -- for all of the non-static data members of its class that are of class
6120 // type (or array thereof), each such class has a trivial [default
6121 // constructor or destructor]
6122 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
6123 return false;
6124
6125 // C++11 [class.dtor]p5:
6126 // A destructor is trivial if [...]
6127 // -- the destructor is not virtual
6128 if (CSM == CXXDestructor && MD->isVirtual()) {
6129 if (Diagnose)
6130 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
6131 return false;
6132 }
6133
6134 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
6135 // A [special member] for class X is trivial if [...]
6136 // -- class X has no virtual functions and no virtual base classes
6137 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
6138 if (!Diagnose)
6139 return false;
6140
6141 if (RD->getNumVBases()) {
6142 // Check for virtual bases. We already know that the corresponding
6143 // member in all bases is trivial, so vbases must all be direct.
6144 CXXBaseSpecifier &BS = *RD->vbases_begin();
6145 assert(BS.isVirtual());
6146 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
6147 return false;
6148 }
6149
6150 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00006151 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00006152 if (MI->isVirtual()) {
6153 SourceLocation MLoc = MI->getLocStart();
6154 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
6155 return false;
6156 }
6157 }
6158
6159 llvm_unreachable("dynamic class with no vbases and no virtual functions");
6160 }
6161
6162 // Looks like it's trivial!
6163 return true;
6164}
6165
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006166/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00006167namespace {
6168 struct FindHiddenVirtualMethodData {
6169 Sema *S;
6170 CXXMethodDecl *Method;
6171 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006172 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00006173 };
6174}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006175
David Blaikie282c92a2012-10-19 00:53:08 +00006176/// \brief Check whether any most overriden method from MD in Methods
6177static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00006178 const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00006179 if (MD->size_overridden_methods() == 0)
6180 return Methods.count(MD->getCanonicalDecl());
6181 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6182 E = MD->end_overridden_methods();
6183 I != E; ++I)
6184 if (CheckMostOverridenMethods(*I, Methods))
6185 return true;
6186 return false;
6187}
6188
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006189/// \brief Member lookup function that determines whether a given C++
6190/// method overloads virtual methods in a base class without overriding any,
6191/// to be used with CXXRecordDecl::lookupInBases().
6192static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
6193 CXXBasePath &Path,
6194 void *UserData) {
6195 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
6196
6197 FindHiddenVirtualMethodData &Data
6198 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
6199
6200 DeclarationName Name = Data.Method->getDeclName();
6201 assert(Name.getNameKind() == DeclarationName::Identifier);
6202
6203 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006204 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006205 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikieff7d47a2012-12-19 00:45:41 +00006206 !Path.Decls.empty();
6207 Path.Decls = Path.Decls.slice(1)) {
6208 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006209 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00006210 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006211 foundSameNameMethod = true;
6212 // Interested only in hidden virtual methods.
6213 if (!MD->isVirtual())
6214 continue;
6215 // If the method we are checking overrides a method from its base
Aaron Ballman04559a72014-07-30 23:50:53 +00006216 // don't warn about the other overloaded methods. Clang deviates from GCC
6217 // by only diagnosing overloads of inherited virtual functions that do not
6218 // override any other virtual functions in the base. GCC's
6219 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6220 // function from a base class. These cases may be better served by a
6221 // warning (not specific to virtual functions) on call sites when the call
6222 // would select a different function from the base class, were it visible.
6223 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006224 if (!Data.S->IsOverload(Data.Method, MD, false))
6225 return true;
6226 // Collect the overload only if its hidden.
David Blaikie282c92a2012-10-19 00:53:08 +00006227 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006228 overloadedMethods.push_back(MD);
6229 }
6230 }
6231
6232 if (foundSameNameMethod)
6233 Data.OverloadedMethods.append(overloadedMethods.begin(),
6234 overloadedMethods.end());
6235 return foundSameNameMethod;
6236}
6237
David Blaikie282c92a2012-10-19 00:53:08 +00006238/// \brief Add the most overriden methods from MD to Methods
6239static void AddMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00006240 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00006241 if (MD->size_overridden_methods() == 0)
6242 Methods.insert(MD->getCanonicalDecl());
6243 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6244 E = MD->end_overridden_methods();
6245 I != E; ++I)
6246 AddMostOverridenMethods(*I, Methods);
6247}
6248
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006249/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006250/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006251void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6252 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00006253 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006254 return;
6255
6256 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6257 /*bool RecordPaths=*/false,
6258 /*bool DetectVirtual=*/false);
6259 FindHiddenVirtualMethodData Data;
6260 Data.Method = MD;
6261 Data.S = this;
6262
6263 // Keep the base methods that were overriden or introduced in the subclass
6264 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006265 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00006266 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6267 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6268 NamedDecl *ND = *I;
6269 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00006270 ND = shad->getTargetDecl();
6271 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6272 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006273 }
6274
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006275 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
6276 OverloadedMethods = Data.OverloadedMethods;
6277}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006278
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006279void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6280 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6281 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6282 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6283 PartialDiagnostic PD = PDiag(
6284 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6285 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6286 Diag(overloadedMD->getLocation(), PD);
6287 }
6288}
6289
6290/// \brief Diagnose methods which overload virtual methods in a base class
6291/// without overriding any.
6292void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6293 if (MD->isInvalidDecl())
6294 return;
6295
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006296 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
Eli Friedmanaf65120b2013-09-05 23:51:03 +00006297 return;
6298
6299 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6300 FindHiddenVirtualMethods(MD, OverloadedMethods);
6301 if (!OverloadedMethods.empty()) {
6302 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6303 << MD << (OverloadedMethods.size() > 1);
6304
6305 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006306 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00006307}
6308
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006309void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00006310 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006311 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00006312 SourceLocation RBrac,
6313 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006314 if (!TagDecl)
6315 return;
Mike Stump11289f42009-09-09 15:08:12 +00006316
Douglas Gregorc9f9b862009-05-11 19:58:34 +00006317 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00006318
Rafael Espindola06e1b132012-07-12 04:32:30 +00006319 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6320 if (l->getKind() != AttributeList::AT_Visibility)
6321 continue;
6322 l->setInvalid();
6323 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6324 l->getName();
6325 }
6326
David Blaikie751c5582011-09-22 02:58:26 +00006327 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00006328 // strict aliasing violation!
6329 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00006330 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00006331
Douglas Gregor0be31a22010-07-02 17:43:08 +00006332 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00006333 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00006334}
6335
Douglas Gregor05379422008-11-03 17:51:48 +00006336/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6337/// special functions, such as the default constructor, copy
6338/// constructor, or destructor, to the given C++ class (C++
6339/// [special]p1). This routine can only be executed just before the
6340/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00006341void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00006342 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00006343 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006344
Richard Smith6b02d462012-12-08 08:32:28 +00006345 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00006346 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00006347
Richard Smith6b02d462012-12-08 08:32:28 +00006348 // If the properties or semantics of the copy constructor couldn't be
6349 // determined while the class was being declared, force a declaration
6350 // of it now.
6351 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6352 DeclareImplicitCopyConstructor(ClassDecl);
6353 }
6354
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006355 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006356 ++ASTContext::NumImplicitMoveConstructors;
6357
Richard Smith6b02d462012-12-08 08:32:28 +00006358 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6359 DeclareImplicitMoveConstructor(ClassDecl);
6360 }
6361
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006362 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6363 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00006364
6365 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006366 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00006367 // it shows up in the right place in the vtable and that we diagnose
6368 // problems with the implicit exception specification.
6369 if (ClassDecl->isDynamicClass() ||
6370 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00006371 DeclareImplicitCopyAssignment(ClassDecl);
6372 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006373
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006374 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00006375 ++ASTContext::NumImplicitMoveAssignmentOperators;
6376
6377 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00006378 if (ClassDecl->isDynamicClass() ||
6379 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00006380 DeclareImplicitMoveAssignment(ClassDecl);
6381 }
6382
Douglas Gregor7454c562010-07-02 20:37:36 +00006383 if (!ClassDecl->hasUserDeclaredDestructor()) {
6384 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00006385
6386 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00006387 // have to declare the destructor immediately. This ensures that, e.g., it
6388 // shows up in the right place in the vtable and that we diagnose problems
6389 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00006390 if (ClassDecl->isDynamicClass() ||
6391 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00006392 DeclareImplicitDestructor(ClassDecl);
6393 }
Douglas Gregor05379422008-11-03 17:51:48 +00006394}
6395
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006396unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Francois Pichet1c229c02011-04-22 22:18:13 +00006397 if (!D)
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006398 return 0;
Francois Pichet1c229c02011-04-22 22:18:13 +00006399
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006400 // The order of template parameters is not important here. All names
6401 // get added to the same scope.
6402 SmallVector<TemplateParameterList *, 4> ParameterLists;
6403
6404 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6405 D = TD->getTemplatedDecl();
6406
6407 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6408 ParameterLists.push_back(PSD->getTemplateParameters());
6409
6410 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6411 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6412 ParameterLists.push_back(DD->getTemplateParameterList(i));
6413
6414 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6415 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6416 ParameterLists.push_back(FTD->getTemplateParameters());
6417 }
6418 }
6419
6420 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6421 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6422 ParameterLists.push_back(TD->getTemplateParameterList(i));
6423
6424 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6425 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6426 ParameterLists.push_back(CTD->getTemplateParameters());
6427 }
6428 }
6429
6430 unsigned Count = 0;
6431 for (TemplateParameterList *Params : ParameterLists) {
6432 if (Params->size() > 0)
6433 // Ignore explicit specializations; they don't contribute to the template
6434 // depth.
6435 ++Count;
6436 for (NamedDecl *Param : *Params) {
6437 if (Param->getDeclName()) {
6438 S->AddDecl(Param);
6439 IdResolver.AddDecl(Param);
Francois Pichet1c229c02011-04-22 22:18:13 +00006440 }
6441 }
6442 }
Francois Pichet1c229c02011-04-22 22:18:13 +00006443
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00006444 return Count;
Douglas Gregore44a2ad2009-05-27 23:11:45 +00006445}
6446
John McCall48871652010-08-21 09:40:31 +00006447void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006448 if (!RecordD) return;
6449 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00006450 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00006451 PushDeclContext(S, Record);
6452}
6453
John McCall48871652010-08-21 09:40:31 +00006454void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00006455 if (!RecordD) return;
6456 PopDeclContext();
6457}
6458
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006459/// This is used to implement the constant expression evaluation part of the
6460/// attribute enable_if extension. There is nothing in standard C++ which would
6461/// require reentering parameters.
6462void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6463 if (!Param)
6464 return;
6465
6466 S->AddDecl(Param);
6467 if (Param->getDeclName())
6468 IdResolver.AddDecl(Param);
6469}
6470
Douglas Gregor4d87df52008-12-16 21:30:33 +00006471/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6472/// parsing a top-level (non-nested) C++ class, and we are now
6473/// parsing those parts of the given Method declaration that could
6474/// not be parsed earlier (C++ [class.mem]p2), such as default
6475/// arguments. This action should enter the scope of the given
6476/// Method declaration as if we had just parsed the qualified method
6477/// name. However, it should not bring the parameters into scope;
6478/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00006479void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006480}
6481
6482/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6483/// C++ method declaration. We're (re-)introducing the given
6484/// function parameter into scope for use in parsing later parts of
6485/// the method declaration. For example, we could see an
6486/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00006487void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006488 if (!ParamD)
6489 return;
Mike Stump11289f42009-09-09 15:08:12 +00006490
John McCall48871652010-08-21 09:40:31 +00006491 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00006492
6493 // If this parameter has an unparsed default argument, clear it out
6494 // to make way for the parsed default argument.
6495 if (Param->hasUnparsedDefaultArg())
Craig Topperc3ec1492014-05-26 06:22:03 +00006496 Param->setDefaultArg(nullptr);
Douglas Gregor58354032008-12-24 00:01:03 +00006497
John McCall48871652010-08-21 09:40:31 +00006498 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006499 if (Param->getDeclName())
6500 IdResolver.AddDecl(Param);
6501}
6502
6503/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6504/// processing the delayed method declaration for Method. The method
6505/// declaration is now considered finished. There may be a separate
6506/// ActOnStartOfFunctionDef action later (not necessarily
6507/// immediately!) for this method, if it was also defined inside the
6508/// class body.
John McCall48871652010-08-21 09:40:31 +00006509void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00006510 if (!MethodD)
6511 return;
Mike Stump11289f42009-09-09 15:08:12 +00006512
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006513 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00006514
John McCall48871652010-08-21 09:40:31 +00006515 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006516
6517 // Now that we have our default arguments, check the constructor
6518 // again. It could produce additional diagnostics or affect whether
6519 // the class has implicitly-declared destructors, among other
6520 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006521 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6522 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00006523
6524 // Check the default arguments, which we may have added.
6525 if (!Method->isInvalidDecl())
6526 CheckCXXDefaultArguments(Method);
6527}
6528
Douglas Gregor831c93f2008-11-05 20:51:48 +00006529/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00006530/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00006531/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006532/// emit diagnostics and set the invalid bit to true. In any case, the type
6533/// will be updated to reflect a well-formed type for the constructor and
6534/// returned.
6535QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006536 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006537 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006538
6539 // C++ [class.ctor]p3:
6540 // A constructor shall not be virtual (10.3) or static (9.4). A
6541 // constructor can be invoked for a const, volatile or const
6542 // volatile object. A constructor shall not be declared const,
6543 // volatile, or const volatile (9.3.2).
6544 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006545 if (!D.isInvalidType())
6546 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6547 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6548 << SourceRange(D.getIdentifierLoc());
6549 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006550 }
John McCall8e7d6562010-08-26 03:08:43 +00006551 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006552 if (!D.isInvalidType())
6553 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6554 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6555 << SourceRange(D.getIdentifierLoc());
6556 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006557 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006558 }
Mike Stump11289f42009-09-09 15:08:12 +00006559
David Majnemer03f705f2014-07-08 18:18:04 +00006560 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6561 diagnoseIgnoredQualifiers(
6562 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6563 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6564 D.getDeclSpec().getRestrictSpecLoc(),
6565 D.getDeclSpec().getAtomicSpecLoc());
6566 D.setInvalidType();
6567 }
6568
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006569 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006570 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00006571 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006572 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6573 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006574 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006575 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6576 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006577 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006578 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6579 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00006580 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006581 }
Mike Stump11289f42009-09-09 15:08:12 +00006582
Douglas Gregordb9d6642011-01-26 05:01:58 +00006583 // C++0x [class.ctor]p4:
6584 // A constructor shall not be declared with a ref-qualifier.
6585 if (FTI.hasRefQualifier()) {
6586 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6587 << FTI.RefQualifierIsLValueRef
6588 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6589 D.setInvalidType();
6590 }
6591
Douglas Gregor831c93f2008-11-05 20:51:48 +00006592 // Rebuild the function type "R" without any type qualifiers (in
6593 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00006594 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00006595 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00006596 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00006597 return R;
6598
6599 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6600 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006601 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00006602
6603 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006604}
6605
Douglas Gregor4d87df52008-12-16 21:30:33 +00006606/// CheckConstructor - Checks a fully-formed constructor for
6607/// well-formedness, issuing any diagnostics required. Returns true if
6608/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006609void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00006610 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006611 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6612 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006613 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006614
6615 // C++ [class.copy]p3:
6616 // A declaration of a constructor for a class X is ill-formed if
6617 // its first parameter is of type (optionally cv-qualified) X and
6618 // either there are no other parameters or else all other
6619 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00006620 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00006621 ((Constructor->getNumParams() == 1) ||
6622 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00006623 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6624 Constructor->getTemplateSpecializationKind()
6625 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00006626 QualType ParamType = Constructor->getParamDecl(0)->getType();
6627 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6628 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00006629 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00006630 const char *ConstRef
6631 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6632 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00006633 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00006634 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00006635
6636 // FIXME: Rather that making the constructor invalid, we should endeavor
6637 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006638 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00006639 }
6640 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00006641}
6642
John McCalldeb646e2010-08-04 01:04:25 +00006643/// CheckDestructor - Checks a fully-formed destructor definition for
6644/// well-formedness, issuing any diagnostics required. Returns true
6645/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00006646bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006647 CXXRecordDecl *RD = Destructor->getParent();
6648
Peter Collingbourneb289fe62013-05-20 14:12:25 +00006649 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00006650 SourceLocation Loc;
6651
6652 if (!Destructor->isImplicit())
6653 Loc = Destructor->getLocation();
6654 else
6655 Loc = RD->getLocation();
6656
6657 // If we have a virtual destructor, look up the deallocation function
Craig Topperc3ec1492014-05-26 06:22:03 +00006658 FunctionDecl *OperatorDelete = nullptr;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006659 DeclarationName Name =
6660 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006661 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00006662 return true;
Richard Smithf03bd302013-12-05 08:30:59 +00006663 // If there's no class-specific operator delete, look up the global
6664 // non-array delete.
6665 if (!OperatorDelete)
6666 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall1e5d75d2010-07-03 18:33:00 +00006667
Eli Friedmanfa0df832012-02-02 03:46:19 +00006668 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00006669
6670 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00006671 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00006672
6673 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00006674}
6675
Douglas Gregor831c93f2008-11-05 20:51:48 +00006676/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6677/// the well-formednes of the destructor declarator @p D with type @p
6678/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00006679/// emit diagnostics and set the declarator to invalid. Even if this happens,
6680/// will be updated to reflect a well-formed type for the destructor and
6681/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00006682QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00006683 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006684 // C++ [class.dtor]p1:
6685 // [...] A typedef-name that names a class is a class-name
6686 // (7.1.3); however, a typedef-name that names a class shall not
6687 // be used as the identifier in the declarator for a destructor
6688 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00006689 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00006690 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00006691 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00006692 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00006693 else if (const TemplateSpecializationType *TST =
6694 DeclaratorType->getAs<TemplateSpecializationType>())
6695 if (TST->isTypeAlias())
6696 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6697 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006698
6699 // C++ [class.dtor]p2:
6700 // A destructor is used to destroy objects of its class type. A
6701 // destructor takes no parameters, and no return type can be
6702 // specified for it (not even void). The address of a destructor
6703 // shall not be taken. A destructor shall not be static. A
6704 // destructor can be invoked for a const, volatile or const
6705 // volatile object. A destructor shall not be declared const,
6706 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00006707 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00006708 if (!D.isInvalidType())
6709 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6710 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00006711 << SourceRange(D.getIdentifierLoc())
6712 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6713
John McCall8e7d6562010-08-26 03:08:43 +00006714 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00006715 }
David Majnemer03f705f2014-07-08 18:18:04 +00006716 if (!D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006717 // Destructors don't have return types, but the parser will
6718 // happily parse something like:
6719 //
6720 // class X {
6721 // float ~X();
6722 // };
6723 //
6724 // The return type will be eliminated later.
David Majnemer03f705f2014-07-08 18:18:04 +00006725 if (D.getDeclSpec().hasTypeSpecifier())
6726 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6727 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6728 << SourceRange(D.getIdentifierLoc());
6729 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6730 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6731 SourceLocation(),
6732 D.getDeclSpec().getConstSpecLoc(),
6733 D.getDeclSpec().getVolatileSpecLoc(),
6734 D.getDeclSpec().getRestrictSpecLoc(),
6735 D.getDeclSpec().getAtomicSpecLoc());
6736 D.setInvalidType();
6737 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006738 }
Mike Stump11289f42009-09-09 15:08:12 +00006739
Abramo Bagnara924a8f32010-12-10 16:29:40 +00006740 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00006741 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00006742 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00006743 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6744 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006745 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00006746 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6747 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00006748 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00006749 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6750 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00006751 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006752 }
6753
Douglas Gregordb9d6642011-01-26 05:01:58 +00006754 // C++0x [class.dtor]p2:
6755 // A destructor shall not be declared with a ref-qualifier.
6756 if (FTI.hasRefQualifier()) {
6757 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6758 << FTI.RefQualifierIsLValueRef
6759 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6760 D.setInvalidType();
6761 }
6762
Douglas Gregor831c93f2008-11-05 20:51:48 +00006763 // Make sure we don't have any parameters.
Alp Toker4284c6e2014-05-11 16:05:55 +00006764 if (FTIHasNonVoidParameters(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006765 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6766
6767 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006768 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00006769 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00006770 }
6771
Mike Stump11289f42009-09-09 15:08:12 +00006772 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00006773 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00006774 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00006775 D.setInvalidType();
6776 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00006777
6778 // Rebuild the function type "R" without any type qualifiers or
6779 // parameters (in case any of the errors above fired) and with
6780 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00006781 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00006782 if (!D.isInvalidType())
6783 return R;
6784
Douglas Gregor95755162010-07-01 05:10:53 +00006785 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00006786 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6787 EPI.Variadic = false;
6788 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00006789 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006790 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00006791}
6792
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006793/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6794/// well-formednes of the conversion function declarator @p D with
6795/// type @p R. If there are any errors in the declarator, this routine
6796/// will emit diagnostics and return true. Otherwise, it will return
6797/// false. Either way, the type @p R will be updated to reflect a
6798/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006799void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00006800 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006801 // C++ [class.conv.fct]p1:
6802 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00006803 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00006804 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00006805 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006806 if (!D.isInvalidType())
6807 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00006808 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6809 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006810 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00006811 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006812 }
John McCall212fa2e2010-04-13 00:04:31 +00006813
6814 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6815
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006816 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006817 // Conversion functions don't have return types, but the parser will
6818 // happily parse something like:
6819 //
6820 // class X {
6821 // float operator bool();
6822 // };
6823 //
6824 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00006825 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6826 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6827 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00006828 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006829 }
6830
John McCall212fa2e2010-04-13 00:04:31 +00006831 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6832
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006833 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00006834 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006835 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6836
6837 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00006838 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006839 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00006840 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006841 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006842 D.setInvalidType();
6843 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006844
John McCall212fa2e2010-04-13 00:04:31 +00006845 // Diagnose "&operator bool()" and other such nonsense. This
6846 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00006847 if (Proto->getReturnType() != ConvType) {
John McCall212fa2e2010-04-13 00:04:31 +00006848 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
Alp Toker314cc812014-01-25 16:55:45 +00006849 << Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006850 D.setInvalidType();
Alp Toker314cc812014-01-25 16:55:45 +00006851 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00006852 }
6853
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006854 // C++ [class.conv.fct]p4:
6855 // The conversion-type-id shall not represent a function type nor
6856 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006857 if (ConvType->isArrayType()) {
6858 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6859 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006860 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006861 } else if (ConvType->isFunctionType()) {
6862 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6863 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00006864 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006865 }
6866
6867 // Rebuild the function type "R" without any parameters (in case any
6868 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00006869 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00006870 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006871 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006872
Douglas Gregor5fb53972009-01-14 15:45:31 +00006873 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006874 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00006875 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006876 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00006877 diag::warn_cxx98_compat_explicit_conversion_functions :
6878 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00006879 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006880}
6881
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006882/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6883/// the declaration of the given C++ conversion function. This routine
6884/// is responsible for recording the conversion function in the C++
6885/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00006886Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006887 assert(Conversion && "Expected to receive a conversion function declaration");
6888
Douglas Gregor4287b372008-12-12 08:25:50 +00006889 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006890
6891 // Make sure we aren't redeclaring the conversion function.
6892 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006893
6894 // C++ [class.conv.fct]p1:
6895 // [...] A conversion function is never used to convert a
6896 // (possibly cv-qualified) object to the (possibly cv-qualified)
6897 // same object type (or a reference to it), to a (possibly
6898 // cv-qualified) base class of that type (or a reference to it),
6899 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00006900 // FIXME: Suppress this warning if the conversion function ends up being a
6901 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00006902 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006903 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006904 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006905 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006906 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6907 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00006908 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00006909 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006910 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6911 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006912 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006913 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006914 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006915 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006916 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006917 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00006918 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006919 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006920 }
6921
Douglas Gregor457104e2010-09-29 04:25:11 +00006922 if (FunctionTemplateDecl *ConversionTemplate
6923 = Conversion->getDescribedFunctionTemplate())
6924 return ConversionTemplate;
6925
John McCall48871652010-08-21 09:40:31 +00006926 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00006927}
6928
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006929//===----------------------------------------------------------------------===//
6930// Namespace Handling
6931//===----------------------------------------------------------------------===//
6932
Richard Smith45bb8852012-10-04 22:13:39 +00006933/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6934/// reopened.
6935static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6936 SourceLocation Loc,
6937 IdentifierInfo *II, bool *IsInline,
6938 NamespaceDecl *PrevNS) {
6939 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00006940
Richard Smithf501cc32012-10-05 01:46:25 +00006941 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6942 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6943 // inline namespaces, with the intention of bringing names into namespace std.
6944 //
6945 // We support this just well enough to get that case working; this is not
6946 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00006947 if (*IsInline && II && II->getName().startswith("__atomic") &&
6948 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00006949 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00006950 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6951 NS = NS->getPreviousDecl())
6952 NS->setInline(*IsInline);
6953 // Patch up the lookup table for the containing namespace. This isn't really
6954 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00006955 for (auto *I : PrevNS->decls())
6956 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00006957 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6958 return;
6959 }
6960
6961 if (PrevNS->isInline())
6962 // The user probably just forgot the 'inline', so suggest that it
6963 // be added back.
6964 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6965 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6966 else
Richard Smith5b5d21e2014-03-12 23:36:42 +00006967 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
Richard Smith45bb8852012-10-04 22:13:39 +00006968
6969 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6970 *IsInline = PrevNS->isInline();
6971}
John McCallb1be5232010-08-26 09:15:37 +00006972
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006973/// ActOnStartNamespaceDef - This is called at the start of a namespace
6974/// definition.
John McCall48871652010-08-21 09:40:31 +00006975Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00006976 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006977 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00006978 SourceLocation IdentLoc,
6979 IdentifierInfo *II,
6980 SourceLocation LBrace,
6981 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00006982 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6983 // For anonymous namespace, take the location of the left brace.
6984 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00006985 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00006986 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00006987 bool IsStd = false;
6988 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006989 Scope *DeclRegionScope = NamespcScope->getParent();
6990
Craig Topperc3ec1492014-05-26 06:22:03 +00006991 NamespaceDecl *PrevNS = nullptr;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00006992 if (II) {
6993 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00006994 // The identifier in an original-namespace-definition shall not
6995 // have been previously defined in the declarative region in
6996 // which the original-namespace-definition appears. The
6997 // identifier in an original-namespace-definition is the name of
6998 // the namespace. Subsequently in that declarative region, it is
6999 // treated as an original-namespace-name.
7000 //
7001 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00007002 // look through using directives, just look for any ordinary names.
7003
7004 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00007005 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
7006 Decl::IDNS_Namespace;
Craig Topperc3ec1492014-05-26 06:22:03 +00007007 NamedDecl *PrevDecl = nullptr;
David Blaikieff7d47a2012-12-19 00:45:41 +00007008 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
7009 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
7010 ++I) {
7011 if ((*I)->getIdentifierNamespace() & IDNS) {
7012 PrevDecl = *I;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00007013 break;
7014 }
7015 }
7016
Douglas Gregore57e7522012-01-07 09:11:48 +00007017 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
7018
7019 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00007020 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00007021 if (IsInline != PrevNS->isInline())
7022 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
7023 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00007024 } else if (PrevDecl) {
7025 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00007026 Diag(Loc, diag::err_redefinition_different_kind)
7027 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00007028 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00007029 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00007030 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00007031 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00007032 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00007033 // This is the first "real" definition of the namespace "std", so update
7034 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00007035 PrevNS = getStdNamespace();
7036 IsStd = true;
7037 AddToKnown = !IsInline;
7038 } else {
7039 // We've seen this namespace for the first time.
7040 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00007041 }
Douglas Gregor91f84212008-12-11 16:49:14 +00007042 } else {
John McCall4fa53422009-10-01 00:25:31 +00007043 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00007044
7045 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00007046 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00007047 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00007048 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00007049 } else {
7050 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00007051 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00007052 }
7053
Richard Smith45bb8852012-10-04 22:13:39 +00007054 if (PrevNS && IsInline != PrevNS->isInline())
7055 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
7056 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00007057 }
7058
7059 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
7060 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00007061 if (IsInvalid)
7062 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00007063
7064 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00007065
Douglas Gregore57e7522012-01-07 09:11:48 +00007066 // FIXME: Should we be merging attributes?
7067 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00007068 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00007069
7070 if (IsStd)
7071 StdNamespace = Namespc;
7072 if (AddToKnown)
7073 KnownNamespaces[Namespc] = false;
7074
7075 if (II) {
7076 PushOnScopeChains(Namespc, DeclRegionScope);
7077 } else {
7078 // Link the anonymous namespace into its parent.
7079 DeclContext *Parent = CurContext->getRedeclContext();
7080 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7081 TU->setAnonymousNamespace(Namespc);
7082 } else {
7083 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00007084 }
John McCall4fa53422009-10-01 00:25:31 +00007085
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00007086 CurContext->addDecl(Namespc);
7087
John McCall4fa53422009-10-01 00:25:31 +00007088 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
7089 // behaves as if it were replaced by
7090 // namespace unique { /* empty body */ }
7091 // using namespace unique;
7092 // namespace unique { namespace-body }
7093 // where all occurrences of 'unique' in a translation unit are
7094 // replaced by the same identifier and this identifier differs
7095 // from all other identifiers in the entire program.
7096
7097 // We just create the namespace with an empty name and then add an
7098 // implicit using declaration, just like the standard suggests.
7099 //
7100 // CodeGen enforces the "universally unique" aspect by giving all
7101 // declarations semantically contained within an anonymous
7102 // namespace internal linkage.
7103
Douglas Gregore57e7522012-01-07 09:11:48 +00007104 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00007105 UsingDirectiveDecl* UD
Nick Lewycky38115822012-11-04 20:21:54 +00007106 = UsingDirectiveDecl::Create(Context, Parent,
John McCall0db42252009-12-16 02:06:49 +00007107 /* 'using' */ LBrace,
7108 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00007109 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00007110 /* identifier */ SourceLocation(),
7111 Namespc,
Nick Lewycky38115822012-11-04 20:21:54 +00007112 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00007113 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00007114 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00007115 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007116 }
7117
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00007118 ActOnDocumentableDecl(Namespc);
7119
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007120 // Although we could have an invalid decl (i.e. the namespace name is a
7121 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00007122 // FIXME: We should be able to push Namespc here, so that the each DeclContext
7123 // for the namespace has the declarations that showed up in that particular
7124 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00007125 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00007126 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007127}
7128
Sebastian Redla6602e92009-11-23 15:34:23 +00007129/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
7130/// is a namespace alias, returns the namespace it points to.
7131static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
7132 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
7133 return AD->getNamespace();
7134 return dyn_cast_or_null<NamespaceDecl>(D);
7135}
7136
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007137/// ActOnFinishNamespaceDef - This callback is called after a namespace is
7138/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00007139void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007140 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
7141 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007142 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007143 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00007144 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00007145 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007146}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007147
John McCall28a0cf72010-08-25 07:42:41 +00007148CXXRecordDecl *Sema::getStdBadAlloc() const {
7149 return cast_or_null<CXXRecordDecl>(
7150 StdBadAlloc.get(Context.getExternalSource()));
7151}
7152
7153NamespaceDecl *Sema::getStdNamespace() const {
7154 return cast_or_null<NamespaceDecl>(
7155 StdNamespace.get(Context.getExternalSource()));
7156}
7157
Douglas Gregorcdf87022010-06-29 17:53:46 +00007158/// \brief Retrieve the special "std" namespace, which may require us to
7159/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007160NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00007161 if (!StdNamespace) {
7162 // The "std" namespace has not yet been defined, so build one implicitly.
7163 StdNamespace = NamespaceDecl::Create(Context,
7164 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00007165 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00007166 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00007167 &PP.getIdentifierTable().get("std"),
Craig Topperc3ec1492014-05-26 06:22:03 +00007168 /*PrevDecl=*/nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007169 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007170 }
Eli Bendersky9a220fc2014-09-29 20:38:29 +00007171
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00007172 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007173}
7174
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007175bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007176 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007177 "Looking for std::initializer_list outside of C++.");
7178
7179 // We're looking for implicit instantiations of
7180 // template <typename E> class std::initializer_list.
7181
7182 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
7183 return false;
7184
Craig Topperc3ec1492014-05-26 06:22:03 +00007185 ClassTemplateDecl *Template = nullptr;
7186 const TemplateArgument *Arguments = nullptr;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007187
Sebastian Redl43144e72012-01-17 22:49:58 +00007188 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007189
Sebastian Redl43144e72012-01-17 22:49:58 +00007190 ClassTemplateSpecializationDecl *Specialization =
7191 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
7192 if (!Specialization)
7193 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007194
Sebastian Redl43144e72012-01-17 22:49:58 +00007195 Template = Specialization->getSpecializedTemplate();
7196 Arguments = Specialization->getTemplateArgs().data();
7197 } else if (const TemplateSpecializationType *TST =
7198 Ty->getAs<TemplateSpecializationType>()) {
7199 Template = dyn_cast_or_null<ClassTemplateDecl>(
7200 TST->getTemplateName().getAsTemplateDecl());
7201 Arguments = TST->getArgs();
7202 }
7203 if (!Template)
7204 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007205
7206 if (!StdInitializerList) {
7207 // Haven't recognized std::initializer_list yet, maybe this is it.
7208 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
7209 if (TemplateClass->getIdentifier() !=
7210 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00007211 !getStdNamespace()->InEnclosingNamespaceSetOf(
7212 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007213 return false;
7214 // This is a template called std::initializer_list, but is it the right
7215 // template?
7216 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00007217 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007218 return false;
7219 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
7220 return false;
7221
7222 // It's the right template.
7223 StdInitializerList = Template;
7224 }
7225
7226 if (Template != StdInitializerList)
7227 return false;
7228
7229 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00007230 if (Element)
7231 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00007232 return true;
7233}
7234
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007235static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7236 NamespaceDecl *Std = S.getStdNamespace();
7237 if (!Std) {
7238 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00007239 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007240 }
7241
7242 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7243 Loc, Sema::LookupOrdinaryName);
7244 if (!S.LookupQualifiedName(Result, Std)) {
7245 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00007246 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007247 }
7248 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7249 if (!Template) {
7250 Result.suppressDiagnostics();
7251 // We found something weird. Complain about the first thing we found.
7252 NamedDecl *Found = *Result.begin();
7253 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00007254 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007255 }
7256
7257 // We found some template called std::initializer_list. Now verify that it's
7258 // correct.
7259 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00007260 if (Params->getMinRequiredArguments() != 1 ||
7261 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007262 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00007263 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00007264 }
7265
7266 return Template;
7267}
7268
7269QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7270 if (!StdInitializerList) {
7271 StdInitializerList = LookupStdInitializerList(*this, Loc);
7272 if (!StdInitializerList)
7273 return QualType();
7274 }
7275
7276 TemplateArgumentListInfo Args(Loc, Loc);
7277 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7278 Context.getTrivialTypeSourceInfo(Element,
7279 Loc)));
7280 return Context.getCanonicalType(
7281 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7282}
7283
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007284bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7285 // C++ [dcl.init.list]p2:
7286 // A constructor is an initializer-list constructor if its first parameter
7287 // is of type std::initializer_list<E> or reference to possibly cv-qualified
7288 // std::initializer_list<E> for some type E, and either there are no other
7289 // parameters or else all other parameters have default arguments.
7290 if (Ctor->getNumParams() < 1 ||
7291 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7292 return false;
7293
7294 QualType ArgType = Ctor->getParamDecl(0)->getType();
7295 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7296 ArgType = RT->getPointeeType().getUnqualifiedType();
7297
Craig Topperc3ec1492014-05-26 06:22:03 +00007298 return isStdInitializerList(ArgType, nullptr);
Sebastian Redlbe24ec22012-01-17 22:50:14 +00007299}
7300
Douglas Gregora172e082011-03-26 22:25:30 +00007301/// \brief Determine whether a using statement is in a context where it will be
7302/// apply in all contexts.
7303static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7304 switch (CurContext->getDeclKind()) {
7305 case Decl::TranslationUnit:
7306 return true;
7307 case Decl::LinkageSpec:
7308 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7309 default:
7310 return false;
7311 }
7312}
7313
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007314namespace {
7315
7316// Callback to only accept typo corrections that are namespaces.
7317class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007318public:
Craig Toppera798a9d2014-03-02 09:32:10 +00007319 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007320 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007321 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007322 return false;
7323 }
7324};
7325
7326}
7327
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007328static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7329 CXXScopeSpec &SS,
7330 SourceLocation IdentLoc,
7331 IdentifierInfo *Ident) {
7332 R.clear();
Kaelyn Takata89c881b2014-10-27 18:07:29 +00007333 if (TypoCorrection Corrected =
7334 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
7335 llvm::make_unique<NamespaceValidatorCCC>(),
7336 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007337 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00007338 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7339 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007340 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00007341 S.diagnoseTypo(Corrected,
7342 S.PDiag(diag::err_using_directive_member_suggest)
7343 << Ident << DC << DroppedSpecifier << SS.getRange(),
7344 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007345 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00007346 S.diagnoseTypo(Corrected,
7347 S.PDiag(diag::err_using_directive_suggest) << Ident,
7348 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00007349 }
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00007350 R.addDecl(Corrected.getCorrectionDecl());
7351 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007352 }
7353 return false;
7354}
7355
John McCall48871652010-08-21 09:40:31 +00007356Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00007357 SourceLocation UsingLoc,
7358 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007359 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00007360 SourceLocation IdentLoc,
7361 IdentifierInfo *NamespcName,
7362 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00007363 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7364 assert(NamespcName && "Invalid NamespcName.");
7365 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00007366
7367 // This can only happen along a recovery path.
7368 while (S->getFlags() & Scope::TemplateParamScope)
7369 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00007370 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00007371
Craig Topperc3ec1492014-05-26 06:22:03 +00007372 UsingDirectiveDecl *UDir = nullptr;
7373 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregorcdf87022010-06-29 17:53:46 +00007374 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00007375 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007376
Douglas Gregor34074322009-01-14 22:20:51 +00007377 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00007378 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7379 LookupParsedName(R, S, &SS);
7380 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00007381 return nullptr;
John McCall27b18f82009-11-17 02:14:36 +00007382
Douglas Gregorcdf87022010-06-29 17:53:46 +00007383 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007384 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00007385 // Allow "using namespace std;" or "using namespace ::std;" even if
7386 // "std" hasn't been defined yet, for GCC compatibility.
7387 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7388 NamespcName->isStr("std")) {
7389 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00007390 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00007391 R.resolveKind();
7392 }
7393 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00007394 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00007395 }
7396
John McCall9f3059a2009-10-09 21:13:30 +00007397 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00007398 NamedDecl *Named = R.getFoundDecl();
7399 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7400 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00007401 // C++ [namespace.udir]p1:
7402 // A using-directive specifies that the names in the nominated
7403 // namespace can be used in the scope in which the
7404 // using-directive appears after the using-directive. During
7405 // unqualified name lookup (3.4.1), the names appear as if they
7406 // were declared in the nearest enclosing namespace which
7407 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00007408 // namespace. [Note: in this context, "contains" means "contains
7409 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00007410
7411 // Find enclosing context containing both using-directive and
7412 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00007413 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007414 DeclContext *CommonAncestor = cast<DeclContext>(NS);
7415 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7416 CommonAncestor = CommonAncestor->getParent();
7417
Sebastian Redla6602e92009-11-23 15:34:23 +00007418 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00007419 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00007420 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007421
Douglas Gregora172e082011-03-26 22:25:30 +00007422 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00007423 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00007424 Diag(IdentLoc, diag::warn_using_directive_in_header);
7425 }
7426
Douglas Gregor889ceb72009-02-03 19:21:40 +00007427 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007428 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00007429 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00007430 }
7431
Richard Smith54ecd982013-02-20 19:22:51 +00007432 if (UDir)
7433 ProcessDeclAttributeList(S, UDir, AttrList);
7434
John McCall48871652010-08-21 09:40:31 +00007435 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00007436}
7437
7438void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00007439 // If the scope has an associated entity and the using directive is at
7440 // namespace or translation unit scope, add the UsingDirectiveDecl into
7441 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00007442 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00007443 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00007444 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00007445 else
Yaron Keren065da7c2014-05-20 18:23:05 +00007446 // Otherwise, it is at block scope. The using-directives will affect lookup
Richard Smith05afe5e2012-03-13 03:12:56 +00007447 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00007448 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00007449}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00007450
Douglas Gregorfec52632009-06-20 00:51:54 +00007451
John McCall48871652010-08-21 09:40:31 +00007452Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00007453 AccessSpecifier AS,
7454 bool HasUsingKeyword,
7455 SourceLocation UsingLoc,
7456 CXXScopeSpec &SS,
7457 UnqualifiedId &Name,
7458 AttributeList *AttrList,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007459 bool HasTypenameKeyword,
John McCall9b72f892010-11-10 02:40:36 +00007460 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00007461 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00007462
Douglas Gregor220f4272009-11-04 16:30:06 +00007463 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00007464 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00007465 case UnqualifiedId::IK_Identifier:
7466 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00007467 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00007468 case UnqualifiedId::IK_ConversionFunctionId:
7469 break;
7470
7471 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00007472 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00007473 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007474 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007475 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00007476 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00007477 diag::err_using_decl_constructor)
7478 << SS.getRange();
7479
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007480 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00007481
Craig Topperc3ec1492014-05-26 06:22:03 +00007482 return nullptr;
7483
Douglas Gregor220f4272009-11-04 16:30:06 +00007484 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007485 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00007486 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00007487 return nullptr;
7488
Douglas Gregor220f4272009-11-04 16:30:06 +00007489 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00007490 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00007491 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00007492 return nullptr;
Douglas Gregor220f4272009-11-04 16:30:06 +00007493 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007494
7495 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7496 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00007497 if (!TargetName)
Craig Topperc3ec1492014-05-26 06:22:03 +00007498 return nullptr;
John McCall3969e302009-12-08 07:46:18 +00007499
Richard Smithc2bc61b2013-03-18 21:12:30 +00007500 // Warn about access declarations.
John McCalla0097262009-12-11 02:10:03 +00007501 if (!HasUsingKeyword) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00007502 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00007503 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7504 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00007505 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00007506 }
7507
Douglas Gregorc4356532010-12-16 00:46:58 +00007508 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7509 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +00007510 return nullptr;
Douglas Gregorc4356532010-12-16 00:46:58 +00007511
John McCall3f746822009-11-17 05:59:44 +00007512 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007513 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007514 /* IsInstantiation */ false,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007515 HasTypenameKeyword, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00007516 if (UD)
7517 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00007518
John McCall48871652010-08-21 09:40:31 +00007519 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00007520}
7521
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007522/// \brief Determine whether a using declaration considers the given
7523/// declarations as "equivalent", e.g., if they are redeclarations of
7524/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00007525static bool
7526IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7527 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007528 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007529
Richard Smithdda56e42011-04-15 14:24:37 +00007530 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00007531 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007532 return Context.hasSameType(TD1->getUnderlyingType(),
7533 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00007534
7535 return false;
7536}
7537
7538
John McCall84d87672009-12-10 09:41:52 +00007539/// Determines whether to create a using shadow decl for a particular
7540/// decl, given the set of decls existing prior to this using lookup.
7541bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00007542 const LookupResult &Previous,
7543 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00007544 // Diagnose finding a decl which is not from a base class of the
7545 // current class. We do this now because there are cases where this
7546 // function will silently decide not to build a shadow decl, which
7547 // will pre-empt further diagnostics.
7548 //
7549 // We don't need to do this in C++0x because we do the check once on
7550 // the qualifier.
7551 //
7552 // FIXME: diagnose the following if we care enough:
7553 // struct A { int foo; };
7554 // struct B : A { using A::foo; };
7555 // template <class T> struct C : A {};
7556 // template <class T> struct D : C<T> { using B::foo; } // <---
7557 // This is invalid (during instantiation) in C++03 because B::foo
7558 // resolves to the using decl in B, which is not a base class of D<T>.
7559 // We can't diagnose it immediately because C<T> is an unknown
7560 // specialization. The UsingShadowDecl in D<T> then points directly
7561 // to A::foo, which will look well-formed when we instantiate.
7562 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007563 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00007564 DeclContext *OrigDC = Orig->getDeclContext();
7565
7566 // Handle enums and anonymous structs.
7567 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7568 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7569 while (OrigRec->isAnonymousStructOrUnion())
7570 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7571
7572 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7573 if (OrigDC == CurContext) {
7574 Diag(Using->getLocation(),
7575 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007576 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007577 Diag(Orig->getLocation(), diag::note_using_decl_target);
7578 return true;
7579 }
7580
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007581 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00007582 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007583 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00007584 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007585 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00007586 Diag(Orig->getLocation(), diag::note_using_decl_target);
7587 return true;
7588 }
7589 }
7590
7591 if (Previous.empty()) return false;
7592
7593 NamedDecl *Target = Orig;
7594 if (isa<UsingShadowDecl>(Target))
7595 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7596
John McCalla17e83e2009-12-11 02:33:26 +00007597 // If the target happens to be one of the previous declarations, we
7598 // don't have a conflict.
7599 //
7600 // FIXME: but we might be increasing its access, in which case we
7601 // should redeclare it.
Craig Topperc3ec1492014-05-26 06:22:03 +00007602 NamedDecl *NonTag = nullptr, *Tag = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00007603 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00007604 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7605 I != E; ++I) {
7606 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007607 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7608 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7609 PrevShadow = Shadow;
7610 FoundEquivalentDecl = true;
7611 }
John McCalla17e83e2009-12-11 02:33:26 +00007612
7613 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7614 }
7615
Richard Smithfd8634a2013-10-23 02:17:46 +00007616 if (FoundEquivalentDecl)
7617 return false;
7618
Alp Tokera2794f92014-01-22 07:29:52 +00007619 if (FunctionDecl *FD = Target->getAsFunction()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007620 NamedDecl *OldDecl = nullptr;
7621 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7622 /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00007623 case Ovl_Overload:
7624 return false;
7625
7626 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00007627 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007628 break;
Richard Smith18819302014-02-06 01:31:33 +00007629
John McCall84d87672009-12-10 09:41:52 +00007630 // We found a decl with the exact signature.
7631 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00007632 // If we're in a record, we want to hide the target, so we
7633 // return true (without a diagnostic) to tell the caller not to
7634 // build a shadow decl.
7635 if (CurContext->isRecord())
7636 return true;
7637
7638 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00007639 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007640 break;
7641 }
7642
7643 Diag(Target->getLocation(), diag::note_using_decl_target);
7644 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7645 return true;
7646 }
7647
7648 // Target is not a function.
7649
John McCall84d87672009-12-10 09:41:52 +00007650 if (isa<TagDecl>(Target)) {
7651 // No conflict between a tag and a non-tag.
7652 if (!Tag) return false;
7653
John McCalle29c5cd2009-12-10 19:51:03 +00007654 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007655 Diag(Target->getLocation(), diag::note_using_decl_target);
7656 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7657 return true;
7658 }
7659
7660 // No conflict between a tag and a non-tag.
7661 if (!NonTag) return false;
7662
John McCalle29c5cd2009-12-10 19:51:03 +00007663 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00007664 Diag(Target->getLocation(), diag::note_using_decl_target);
7665 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7666 return true;
7667}
7668
John McCall3f746822009-11-17 05:59:44 +00007669/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00007670UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00007671 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00007672 NamedDecl *Orig,
7673 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00007674
7675 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00007676 NamedDecl *Target = Orig;
7677 if (isa<UsingShadowDecl>(Target)) {
7678 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7679 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00007680 }
Richard Smithfd8634a2013-10-23 02:17:46 +00007681
John McCall3f746822009-11-17 05:59:44 +00007682 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00007683 = UsingShadowDecl::Create(Context, CurContext,
7684 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00007685 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00007686
Douglas Gregor457104e2010-09-29 04:25:11 +00007687 Shadow->setAccess(UD->getAccess());
7688 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7689 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00007690
7691 Shadow->setPreviousDecl(PrevDecl);
7692
John McCall3f746822009-11-17 05:59:44 +00007693 if (S)
John McCall3969e302009-12-08 07:46:18 +00007694 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00007695 else
John McCall3969e302009-12-08 07:46:18 +00007696 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00007697
John McCall3969e302009-12-08 07:46:18 +00007698
John McCall84d87672009-12-10 09:41:52 +00007699 return Shadow;
7700}
John McCall3969e302009-12-08 07:46:18 +00007701
John McCall84d87672009-12-10 09:41:52 +00007702/// Hides a using shadow declaration. This is required by the current
7703/// using-decl implementation when a resolvable using declaration in a
7704/// class is followed by a declaration which would hide or override
7705/// one or more of the using decl's targets; for example:
7706///
7707/// struct Base { void foo(int); };
7708/// struct Derived : Base {
7709/// using Base::foo;
7710/// void foo(int);
7711/// };
7712///
7713/// The governing language is C++03 [namespace.udecl]p12:
7714///
7715/// When a using-declaration brings names from a base class into a
7716/// derived class scope, member functions in the derived class
7717/// override and/or hide member functions with the same name and
7718/// parameter types in a base class (rather than conflicting).
7719///
7720/// There are two ways to implement this:
7721/// (1) optimistically create shadow decls when they're not hidden
7722/// by existing declarations, or
7723/// (2) don't create any shadow decls (or at least don't make them
7724/// visible) until we've fully parsed/instantiated the class.
7725/// The problem with (1) is that we might have to retroactively remove
7726/// a shadow decl, which requires several O(n) operations because the
7727/// decl structures are (very reasonably) not designed for removal.
7728/// (2) avoids this but is very fiddly and phase-dependent.
7729void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00007730 if (Shadow->getDeclName().getNameKind() ==
7731 DeclarationName::CXXConversionFunctionName)
7732 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7733
John McCall84d87672009-12-10 09:41:52 +00007734 // Remove it from the DeclContext...
7735 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007736
John McCall84d87672009-12-10 09:41:52 +00007737 // ...and the scope, if applicable...
7738 if (S) {
John McCall48871652010-08-21 09:40:31 +00007739 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00007740 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00007741 }
7742
John McCall84d87672009-12-10 09:41:52 +00007743 // ...and the using decl.
7744 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7745
7746 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00007747 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00007748}
7749
Richard Smith09d5b3a2014-05-01 00:35:04 +00007750/// Find the base specifier for a base class with the given type.
7751static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7752 QualType DesiredBase,
7753 bool &AnyDependentBases) {
7754 // Check whether the named type is a direct base class.
7755 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7756 for (auto &Base : Derived->bases()) {
7757 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7758 if (CanonicalDesiredBase == BaseType)
7759 return &Base;
7760 if (BaseType->isDependentType())
7761 AnyDependentBases = true;
7762 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007763 return nullptr;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007764}
7765
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007766namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007767class UsingValidatorCCC : public CorrectionCandidateCallback {
7768public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00007769 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007770 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007771 : HasTypenameKeyword(HasTypenameKeyword),
Richard Smith09d5b3a2014-05-01 00:35:04 +00007772 IsInstantiation(IsInstantiation), OldNNS(NNS),
7773 RequireMemberOf(RequireMemberOf) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007774
Craig Toppera798a9d2014-03-02 09:32:10 +00007775 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007776 NamedDecl *ND = Candidate.getCorrectionDecl();
7777
7778 // Keywords are not valid here.
7779 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007780 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007781
7782 // Completely unqualified names are invalid for a 'using' declaration.
7783 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7784 return false;
7785
Richard Smith09d5b3a2014-05-01 00:35:04 +00007786 if (RequireMemberOf) {
7787 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7788 if (FoundRecord && FoundRecord->isInjectedClassName()) {
7789 // No-one ever wants a using-declaration to name an injected-class-name
7790 // of a base class, unless they're declaring an inheriting constructor.
7791 ASTContext &Ctx = ND->getASTContext();
7792 if (!Ctx.getLangOpts().CPlusPlus11)
7793 return false;
7794 QualType FoundType = Ctx.getRecordType(FoundRecord);
7795
7796 // Check that the injected-class-name is named as a member of its own
7797 // type; we don't want to suggest 'using Derived::Base;', since that
7798 // means something else.
7799 NestedNameSpecifier *Specifier =
7800 Candidate.WillReplaceSpecifier()
7801 ? Candidate.getCorrectionSpecifier()
7802 : OldNNS;
7803 if (!Specifier->getAsType() ||
7804 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
7805 return false;
7806
7807 // Check that this inheriting constructor declaration actually names a
7808 // direct base class of the current class.
7809 bool AnyDependentBases = false;
7810 if (!findDirectBaseWithType(RequireMemberOf,
7811 Ctx.getRecordType(FoundRecord),
7812 AnyDependentBases) &&
7813 !AnyDependentBases)
7814 return false;
7815 } else {
7816 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
7817 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
7818 return false;
7819
7820 // FIXME: Check that the base class member is accessible?
7821 }
7822 }
7823
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007824 if (isa<TypeDecl>(ND))
7825 return HasTypenameKeyword || !IsInstantiation;
7826
7827 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007828 }
7829
7830private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007831 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007832 bool IsInstantiation;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007833 NestedNameSpecifier *OldNNS;
Richard Smith21866c32014-04-30 18:03:21 +00007834 CXXRecordDecl *RequireMemberOf;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007835};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00007836} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007837
John McCalle61f2ba2009-11-18 02:36:19 +00007838/// Builds a using declaration.
7839///
7840/// \param IsInstantiation - Whether this call arises from an
7841/// instantiation of an unresolved using declaration. We treat
7842/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00007843NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7844 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00007845 CXXScopeSpec &SS,
Richard Smith09d5b3a2014-05-01 00:35:04 +00007846 DeclarationNameInfo NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00007847 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00007848 bool IsInstantiation,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007849 bool HasTypenameKeyword,
John McCalle61f2ba2009-11-18 02:36:19 +00007850 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00007851 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007852 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00007853 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00007854
Anders Carlssonf038fc22009-08-28 05:49:21 +00007855 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00007856
Anders Carlsson59140b32009-08-28 03:16:11 +00007857 if (SS.isEmpty()) {
7858 Diag(IdentLoc, diag::err_using_requires_qualname);
Craig Topperc3ec1492014-05-26 06:22:03 +00007859 return nullptr;
Anders Carlsson59140b32009-08-28 03:16:11 +00007860 }
Mike Stump11289f42009-09-09 15:08:12 +00007861
John McCall84d87672009-12-10 09:41:52 +00007862 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007863 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00007864 ForRedeclaration);
7865 Previous.setHideTags(false);
7866 if (S) {
7867 LookupName(Previous, S);
7868
7869 // It is really dumb that we have to do this.
7870 LookupResult::Filter F = Previous.makeFilter();
7871 while (F.hasNext()) {
7872 NamedDecl *D = F.next();
7873 if (!isDeclInScope(D, CurContext, S))
7874 F.erase();
Richard Smith83e78f52014-04-11 01:03:38 +00007875 // If we found a local extern declaration that's not ordinarily visible,
7876 // and this declaration is being added to a non-block scope, ignore it.
7877 // We're only checking for scope conflicts here, not also for violations
7878 // of the linkage rules.
7879 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
7880 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
7881 F.erase();
John McCall84d87672009-12-10 09:41:52 +00007882 }
7883 F.done();
7884 } else {
7885 assert(IsInstantiation && "no scope in non-instantiation");
7886 assert(CurContext->isRecord() && "scope not record in instantiation");
7887 LookupQualifiedName(Previous, CurContext);
7888 }
7889
John McCall84d87672009-12-10 09:41:52 +00007890 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007891 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7892 SS, IdentLoc, Previous))
Craig Topperc3ec1492014-05-26 06:22:03 +00007893 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00007894
7895 // Check for bad qualifiers.
Richard Smith7ad0b882014-04-02 21:44:35 +00007896 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00007897 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00007898
John McCall84c16cf2009-11-12 03:15:40 +00007899 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00007900 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007901 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00007902 if (!LookupContext) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00007903 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00007904 // FIXME: not all declaration name kinds are legal here
7905 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7906 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007907 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007908 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00007909 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00007910 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7911 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00007912 }
Richard Smith09d5b3a2014-05-01 00:35:04 +00007913 D->setAccess(AS);
7914 CurContext->addDecl(D);
7915 return D;
Anders Carlssonf038fc22009-08-28 05:49:21 +00007916 }
John McCallb96ec562009-12-04 22:46:56 +00007917
Richard Smith09d5b3a2014-05-01 00:35:04 +00007918 auto Build = [&](bool Invalid) {
7919 UsingDecl *UD =
7920 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
7921 HasTypenameKeyword);
7922 UD->setAccess(AS);
7923 CurContext->addDecl(UD);
7924 UD->setInvalidDecl(Invalid);
John McCall3969e302009-12-08 07:46:18 +00007925 return UD;
Richard Smith09d5b3a2014-05-01 00:35:04 +00007926 };
7927 auto BuildInvalid = [&]{ return Build(true); };
7928 auto BuildValid = [&]{ return Build(false); };
7929
7930 if (RequireCompleteDeclContext(SS, LookupContext))
7931 return BuildInvalid();
Anders Carlsson59140b32009-08-28 03:16:11 +00007932
Richard Smith23d55872012-04-02 01:30:27 +00007933 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redl08905022011-02-05 19:23:19 +00007934 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smith09d5b3a2014-05-01 00:35:04 +00007935 UsingDecl *UD = BuildValid();
7936 CheckInheritingConstructorUsingDecl(UD);
Sebastian Redl08905022011-02-05 19:23:19 +00007937 return UD;
7938 }
7939
7940 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00007941
Abramo Bagnara8de74e92010-08-12 11:46:03 +00007942 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00007943
John McCall3969e302009-12-08 07:46:18 +00007944 // Unlike most lookups, we don't always want to hide tag
7945 // declarations: tag names are visible through the using declaration
7946 // even if hidden by ordinary names, *except* in a dependent context
7947 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00007948 if (!IsInstantiation)
7949 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00007950
John McCall5dadb652012-04-07 03:04:20 +00007951 // For the purposes of this lookup, we have a base object type
7952 // equal to that of the current context.
7953 if (CurContext->isRecord()) {
7954 R.setBaseObjectType(
7955 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7956 }
7957
John McCall27b18f82009-11-17 02:14:36 +00007958 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00007959
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007960 // Try to correct typos if possible.
John McCall9f3059a2009-10-09 21:13:30 +00007961 if (R.empty()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00007962 if (TypoCorrection Corrected = CorrectTypo(
7963 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
7964 llvm::make_unique<UsingValidatorCCC>(
7965 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
7966 dyn_cast<CXXRecordDecl>(CurContext)),
7967 CTK_ErrorRecovery)) {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007968 // We reject any correction for which ND would be NULL.
7969 NamedDecl *ND = Corrected.getCorrectionDecl();
Richard Smith09d5b3a2014-05-01 00:35:04 +00007970
Richard Smithf9b15102013-08-17 00:46:16 +00007971 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00007972 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00007973 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7974 << NameInfo.getName() << LookupContext << 0
7975 << SS.getRange());
Richard Smith09d5b3a2014-05-01 00:35:04 +00007976
7977 // If we corrected to an inheriting constructor, handle it as one.
7978 auto *RD = dyn_cast<CXXRecordDecl>(ND);
7979 if (RD && RD->isInjectedClassName()) {
7980 // Fix up the information we'll use to build the using declaration.
7981 if (Corrected.WillReplaceSpecifier()) {
7982 NestedNameSpecifierLocBuilder Builder;
7983 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
7984 QualifierLoc.getSourceRange());
7985 QualifierLoc = Builder.getWithLocInContext(Context);
7986 }
7987
7988 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
7989 Context.getCanonicalType(Context.getRecordType(RD))));
Craig Topperc3ec1492014-05-26 06:22:03 +00007990 NameInfo.setNamedTypeInfo(nullptr);
Richard Smith09d5b3a2014-05-01 00:35:04 +00007991
7992 // Build it and process it as an inheriting constructor.
7993 UsingDecl *UD = BuildValid();
7994 CheckInheritingConstructorUsingDecl(UD);
7995 return UD;
7996 }
7997
7998 // FIXME: Pick up all the declarations if we found an overloaded function.
7999 R.setLookupName(Corrected.getCorrection());
8000 R.addDecl(ND);
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008001 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00008002 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008003 << NameInfo.getName() << LookupContext << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008004 return BuildInvalid();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008005 }
Douglas Gregorfec52632009-06-20 00:51:54 +00008006 }
8007
Richard Smith09d5b3a2014-05-01 00:35:04 +00008008 if (R.isAmbiguous())
8009 return BuildInvalid();
Mike Stump11289f42009-09-09 15:08:12 +00008010
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008011 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00008012 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00008013 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00008014 Diag(IdentLoc, diag::err_using_typename_non_type);
8015 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8016 Diag((*I)->getUnderlyingDecl()->getLocation(),
8017 diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00008018 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00008019 }
8020 } else {
8021 // If we asked for a non-typename and we got a type, error out,
8022 // but only if this is an instantiation of an unresolved using
8023 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00008024 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00008025 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
8026 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00008027 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00008028 }
Anders Carlsson59140b32009-08-28 03:16:11 +00008029 }
8030
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008031 // C++0x N2914 [namespace.udecl]p6:
8032 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00008033 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008034 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
8035 << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00008036 return BuildInvalid();
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00008037 }
Mike Stump11289f42009-09-09 15:08:12 +00008038
Richard Smith09d5b3a2014-05-01 00:35:04 +00008039 UsingDecl *UD = BuildValid();
John McCall84d87672009-12-10 09:41:52 +00008040 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008041 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00008042 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
8043 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00008044 }
John McCall3f746822009-11-17 05:59:44 +00008045
8046 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00008047}
8048
Sebastian Redl08905022011-02-05 19:23:19 +00008049/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00008050bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008051 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00008052
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008053 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00008054 assert(SourceType &&
8055 "Using decl naming constructor doesn't have type in scope spec.");
8056 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
8057
8058 // Check whether the named type is a direct base class.
Richard Smith09d5b3a2014-05-01 00:35:04 +00008059 bool AnyDependentBases = false;
8060 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
8061 AnyDependentBases);
8062 if (!Base && !AnyDependentBases) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008063 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00008064 diag::err_using_decl_constructor_not_in_direct_base)
8065 << UD->getNameInfo().getSourceRange()
8066 << QualType(SourceType, 0) << TargetClass;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008067 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00008068 return true;
8069 }
8070
Richard Smith09d5b3a2014-05-01 00:35:04 +00008071 if (Base)
8072 Base->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00008073
8074 return false;
8075}
8076
John McCall84d87672009-12-10 09:41:52 +00008077/// Checks that the given using declaration is not an invalid
8078/// redeclaration. Note that this is checking only for the using decl
8079/// itself, not for any ill-formedness among the UsingShadowDecls.
8080bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008081 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00008082 const CXXScopeSpec &SS,
8083 SourceLocation NameLoc,
8084 const LookupResult &Prev) {
8085 // C++03 [namespace.udecl]p8:
8086 // C++0x [namespace.udecl]p10:
8087 // A using-declaration is a declaration and can therefore be used
8088 // repeatedly where (and only where) multiple declarations are
8089 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00008090 //
John McCall032092f2010-11-29 18:01:58 +00008091 // That's in non-member contexts.
8092 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00008093 return false;
8094
Aaron Ballman4a979672014-01-03 13:56:08 +00008095 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall84d87672009-12-10 09:41:52 +00008096
8097 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
8098 NamedDecl *D = *I;
8099
8100 bool DTypename;
8101 NestedNameSpecifier *DQual;
8102 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008103 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008104 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008105 } else if (UnresolvedUsingValueDecl *UD
8106 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
8107 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008108 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008109 } else if (UnresolvedUsingTypenameDecl *UD
8110 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
8111 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008112 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00008113 } else continue;
8114
8115 // using decls differ if one says 'typename' and the other doesn't.
8116 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008117 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00008118
8119 // using decls differ if they name different scopes (but note that
8120 // template instantiation can cause this check to trigger when it
8121 // didn't before instantiation).
8122 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
8123 Context.getCanonicalNestedNameSpecifier(DQual))
8124 continue;
8125
8126 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00008127 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00008128 return true;
8129 }
8130
8131 return false;
8132}
8133
John McCall3969e302009-12-08 07:46:18 +00008134
John McCallb96ec562009-12-04 22:46:56 +00008135/// Checks that the given nested-name qualifier used in a using decl
8136/// in the current context is appropriately related to the current
8137/// scope. If an error is found, diagnoses it and returns true.
8138bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
8139 const CXXScopeSpec &SS,
Richard Smith7ad0b882014-04-02 21:44:35 +00008140 const DeclarationNameInfo &NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00008141 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00008142 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00008143
John McCall3969e302009-12-08 07:46:18 +00008144 if (!CurContext->isRecord()) {
8145 // C++03 [namespace.udecl]p3:
8146 // C++0x [namespace.udecl]p8:
8147 // A using-declaration for a class member shall be a member-declaration.
8148
8149 // If we weren't able to compute a valid scope, it must be a
8150 // dependent class scope.
8151 if (!NamedContext || NamedContext->isRecord()) {
Richard Smith7ad0b882014-04-02 21:44:35 +00008152 auto *RD = dyn_cast<CXXRecordDecl>(NamedContext);
8153 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
Craig Topperc3ec1492014-05-26 06:22:03 +00008154 RD = nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00008155
John McCall3969e302009-12-08 07:46:18 +00008156 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
8157 << SS.getRange();
Richard Smith7ad0b882014-04-02 21:44:35 +00008158
8159 // If we have a complete, non-dependent source type, try to suggest a
8160 // way to get the same effect.
8161 if (!RD)
8162 return true;
8163
8164 // Find what this using-declaration was referring to.
8165 LookupResult R(*this, NameInfo, LookupOrdinaryName);
8166 R.setHideTags(false);
8167 R.suppressDiagnostics();
8168 LookupQualifiedName(R, RD);
8169
8170 if (R.getAsSingle<TypeDecl>()) {
8171 if (getLangOpts().CPlusPlus11) {
8172 // Convert 'using X::Y;' to 'using Y = X::Y;'.
8173 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
8174 << 0 // alias declaration
8175 << FixItHint::CreateInsertion(SS.getBeginLoc(),
8176 NameInfo.getName().getAsString() +
8177 " = ");
8178 } else {
8179 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
8180 SourceLocation InsertLoc =
8181 PP.getLocForEndOfToken(NameInfo.getLocEnd());
8182 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
8183 << 1 // typedef declaration
8184 << FixItHint::CreateReplacement(UsingLoc, "typedef")
8185 << FixItHint::CreateInsertion(
8186 InsertLoc, " " + NameInfo.getName().getAsString());
8187 }
8188 } else if (R.getAsSingle<VarDecl>()) {
8189 // Don't provide a fixit outside C++11 mode; we don't want to suggest
8190 // repeating the type of the static data member here.
8191 FixItHint FixIt;
8192 if (getLangOpts().CPlusPlus11) {
8193 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8194 FixIt = FixItHint::CreateReplacement(
8195 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
8196 }
8197
8198 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8199 << 2 // reference declaration
8200 << FixIt;
8201 }
John McCall3969e302009-12-08 07:46:18 +00008202 return true;
8203 }
8204
8205 // Otherwise, everything is known to be fine.
8206 return false;
8207 }
8208
8209 // The current scope is a record.
8210
8211 // If the named context is dependent, we can't decide much.
8212 if (!NamedContext) {
8213 // FIXME: in C++0x, we can diagnose if we can prove that the
8214 // nested-name-specifier does not refer to a base class, which is
8215 // still possible in some cases.
8216
8217 // Otherwise we have to conservatively report that things might be
8218 // okay.
8219 return false;
8220 }
8221
8222 if (!NamedContext->isRecord()) {
8223 // Ideally this would point at the last name in the specifier,
8224 // but we don't have that level of source info.
8225 Diag(SS.getRange().getBegin(),
8226 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00008227 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00008228 return true;
8229 }
8230
Douglas Gregor7c842292010-12-21 07:41:49 +00008231 if (!NamedContext->isDependentContext() &&
8232 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8233 return true;
8234
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008235 if (getLangOpts().CPlusPlus11) {
John McCall3969e302009-12-08 07:46:18 +00008236 // C++0x [namespace.udecl]p3:
8237 // In a using-declaration used as a member-declaration, the
8238 // nested-name-specifier shall name a base class of the class
8239 // being defined.
8240
8241 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8242 cast<CXXRecordDecl>(NamedContext))) {
8243 if (CurContext == NamedContext) {
8244 Diag(NameLoc,
8245 diag::err_using_decl_nested_name_specifier_is_current_class)
8246 << SS.getRange();
8247 return true;
8248 }
8249
8250 Diag(SS.getRange().getBegin(),
8251 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00008252 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00008253 << cast<CXXRecordDecl>(CurContext)
8254 << SS.getRange();
8255 return true;
8256 }
8257
8258 return false;
8259 }
8260
8261 // C++03 [namespace.udecl]p4:
8262 // A using-declaration used as a member-declaration shall refer
8263 // to a member of a base class of the class being defined [etc.].
8264
8265 // Salient point: SS doesn't have to name a base class as long as
8266 // lookup only finds members from base classes. Therefore we can
8267 // diagnose here only if we can prove that that can't happen,
8268 // i.e. if the class hierarchies provably don't intersect.
8269
8270 // TODO: it would be nice if "definitely valid" results were cached
8271 // in the UsingDecl and UsingShadowDecl so that these checks didn't
8272 // need to be repeated.
8273
8274 struct UserData {
Benjamin Kramer3adbe1c2012-02-23 16:06:01 +00008275 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall3969e302009-12-08 07:46:18 +00008276
8277 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
8278 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8279 Data->Bases.insert(Base);
8280 return true;
8281 }
8282
8283 bool hasDependentBases(const CXXRecordDecl *Class) {
8284 return !Class->forallBases(collect, this);
8285 }
8286
8287 /// Returns true if the base is dependent or is one of the
8288 /// accumulated base classes.
8289 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
8290 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8291 return !Data->Bases.count(Base);
8292 }
8293
8294 bool mightShareBases(const CXXRecordDecl *Class) {
8295 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
8296 }
8297 };
8298
8299 UserData Data;
8300
8301 // Returns false if we find a dependent base.
8302 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
8303 return false;
8304
8305 // Returns false if the class has a dependent base or if it or one
8306 // of its bases is present in the base set of the current context.
8307 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
8308 return false;
8309
8310 Diag(SS.getRange().getBegin(),
8311 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00008312 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00008313 << cast<CXXRecordDecl>(CurContext)
8314 << SS.getRange();
8315
8316 return true;
John McCallb96ec562009-12-04 22:46:56 +00008317}
8318
Richard Smithdda56e42011-04-15 14:24:37 +00008319Decl *Sema::ActOnAliasDeclaration(Scope *S,
8320 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008321 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00008322 SourceLocation UsingLoc,
8323 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00008324 AttributeList *AttrList,
Richard Smithdda56e42011-04-15 14:24:37 +00008325 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00008326 // Skip up to the relevant declaration scope.
8327 while (S->getFlags() & Scope::TemplateParamScope)
8328 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00008329 assert((S->getFlags() & Scope::DeclScope) &&
8330 "got alias-declaration outside of declaration scope");
8331
8332 if (Type.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00008333 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008334
8335 bool Invalid = false;
8336 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
Craig Topperc3ec1492014-05-26 06:22:03 +00008337 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky82e47802011-05-02 01:07:19 +00008338 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00008339
8340 if (DiagnoseClassNameShadow(CurContext, NameInfo))
Craig Topperc3ec1492014-05-26 06:22:03 +00008341 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00008342
8343 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00008344 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00008345 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008346 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8347 TInfo->getTypeLoc().getBeginLoc());
8348 }
Richard Smithdda56e42011-04-15 14:24:37 +00008349
8350 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8351 LookupName(Previous, S);
8352
8353 // Warn about shadowing the name of a template parameter.
8354 if (Previous.isSingleResult() &&
8355 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00008356 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00008357 Previous.clear();
8358 }
8359
8360 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8361 "name in alias declaration must be an identifier");
8362 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8363 Name.StartLocation,
8364 Name.Identifier, TInfo);
8365
8366 NewTD->setAccess(AS);
8367
8368 if (Invalid)
8369 NewTD->setInvalidDecl();
8370
Richard Smith54ecd982013-02-20 19:22:51 +00008371 ProcessDeclAttributeList(S, NewTD, AttrList);
8372
Richard Smith3f1b5d02011-05-05 21:57:07 +00008373 CheckTypedefForVariablyModifiedType(S, NewTD);
8374 Invalid |= NewTD->isInvalidDecl();
8375
Richard Smithdda56e42011-04-15 14:24:37 +00008376 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008377
8378 NamedDecl *NewND;
8379 if (TemplateParamLists.size()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008380 TypeAliasTemplateDecl *OldDecl = nullptr;
8381 TemplateParameterList *OldTemplateParams = nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008382
8383 if (TemplateParamLists.size() != 1) {
8384 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008385 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8386 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00008387 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00008388 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00008389
8390 // Only consider previous declarations in the same scope.
8391 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8392 /*ExplicitInstantiationOrSpecialization*/false);
8393 if (!Previous.empty()) {
8394 Redeclaration = true;
8395
8396 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8397 if (!OldDecl && !Invalid) {
8398 Diag(UsingLoc, diag::err_redefinition_different_kind)
8399 << Name.Identifier;
8400
8401 NamedDecl *OldD = Previous.getRepresentativeDecl();
8402 if (OldD->getLocation().isValid())
8403 Diag(OldD->getLocation(), diag::note_previous_definition);
8404
8405 Invalid = true;
8406 }
8407
8408 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8409 if (TemplateParameterListsAreEqual(TemplateParams,
8410 OldDecl->getTemplateParameters(),
8411 /*Complain=*/true,
8412 TPL_TemplateMatch))
8413 OldTemplateParams = OldDecl->getTemplateParameters();
8414 else
8415 Invalid = true;
8416
8417 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8418 if (!Invalid &&
8419 !Context.hasSameType(OldTD->getUnderlyingType(),
8420 NewTD->getUnderlyingType())) {
8421 // FIXME: The C++0x standard does not clearly say this is ill-formed,
8422 // but we can't reasonably accept it.
8423 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8424 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8425 if (OldTD->getLocation().isValid())
8426 Diag(OldTD->getLocation(), diag::note_previous_definition);
8427 Invalid = true;
8428 }
8429 }
8430 }
8431
8432 // Merge any previous default template arguments into our parameters,
8433 // and check the parameter list.
8434 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8435 TPC_TypeAliasTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +00008436 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00008437
8438 TypeAliasTemplateDecl *NewDecl =
8439 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8440 Name.Identifier, TemplateParams,
8441 NewTD);
Richard Smith43ccec8e2014-08-26 03:52:16 +00008442 NewTD->setDescribedAliasTemplate(NewDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008443
8444 NewDecl->setAccess(AS);
8445
8446 if (Invalid)
8447 NewDecl->setInvalidDecl();
8448 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00008449 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008450
8451 NewND = NewDecl;
8452 } else {
8453 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8454 NewND = NewTD;
8455 }
Richard Smithdda56e42011-04-15 14:24:37 +00008456
8457 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00008458 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00008459
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00008460 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00008461 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00008462}
8463
Richard Smithf4634362014-09-03 23:11:22 +00008464Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
8465 SourceLocation AliasLoc,
8466 IdentifierInfo *Alias, CXXScopeSpec &SS,
8467 SourceLocation IdentLoc,
8468 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00008469
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008470 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00008471 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8472 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00008473
John McCall27b18f82009-11-17 02:14:36 +00008474 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00008475 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008476
John McCall9f3059a2009-10-09 21:13:30 +00008477 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008478 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00008479 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00008480 return nullptr;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00008481 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00008482 }
Richard Smithf4634362014-09-03 23:11:22 +00008483 assert(!R.isAmbiguous() && !R.empty());
8484
8485 // Check if we have a previous declaration with the same name.
8486 NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8487 ForRedeclaration);
8488 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
8489 PrevDecl = nullptr;
8490
8491 if (PrevDecl) {
8492 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8493 // We already have an alias with the same name that points to the same
8494 // namespace; check that it matches.
8495 if (!AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) {
8496 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
8497 << Alias;
8498 Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias)
8499 << AD->getNamespace();
8500 return nullptr;
8501 }
8502 } else {
8503 unsigned DiagID = isa<NamespaceDecl>(PrevDecl)
8504 ? diag::err_redefinition
8505 : diag::err_redefinition_different_kind;
8506 Diag(AliasLoc, DiagID) << Alias;
8507 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8508 return nullptr;
8509 }
8510 }
Mike Stump11289f42009-09-09 15:08:12 +00008511
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008512 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00008513 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00008514 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00008515 IdentLoc, R.getFoundDecl());
Richard Smithf4634362014-09-03 23:11:22 +00008516 if (PrevDecl)
8517 AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl));
Mike Stump11289f42009-09-09 15:08:12 +00008518
John McCalld8d0d432010-02-16 06:53:13 +00008519 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00008520 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00008521}
8522
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008523Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00008524Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8525 CXXMethodDecl *MD) {
8526 CXXRecordDecl *ClassDecl = MD->getParent();
8527
Douglas Gregor6d880b12010-07-01 22:31:05 +00008528 // C++ [except.spec]p14:
8529 // An implicitly declared special member function (Clause 12) shall have an
8530 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00008531 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008532 if (ClassDecl->isInvalidDecl())
8533 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00008534
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008535 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008536 for (const auto &B : ClassDecl->bases()) {
8537 if (B.isVirtual()) // Handled below.
Douglas Gregor6d880b12010-07-01 22:31:05 +00008538 continue;
8539
Aaron Ballman574705e2014-03-13 15:41:46 +00008540 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008541 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008542 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8543 // If this is a deleted function, add it anyway. This might be conformant
8544 // with the standard. This might not. I'm not sure. It might not matter.
8545 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008546 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008547 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008548 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008549
8550 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008551 for (const auto &B : ClassDecl->vbases()) {
8552 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00008553 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00008554 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8555 // If this is a deleted function, add it anyway. This might be conformant
8556 // with the standard. This might not. I'm not sure. It might not matter.
8557 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008558 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008559 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008560 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008561
8562 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008563 for (const auto *F : ClassDecl->fields()) {
Richard Smith938f40b2011-06-11 17:19:42 +00008564 if (F->hasInClassInitializer()) {
8565 if (Expr *E = F->getInClassInitializer())
8566 ExceptSpec.CalledExpr(E);
8567 else if (!F->isInvalidDecl())
Richard Smithd3b5c9082012-07-27 04:22:15 +00008568 // DR1351:
8569 // If the brace-or-equal-initializer of a non-static data member
8570 // invokes a defaulted default constructor of its class or of an
8571 // enclosing class in a potentially evaluated subexpression, the
8572 // program is ill-formed.
8573 //
8574 // This resolution is unworkable: the exception specification of the
8575 // default constructor can be needed in an unevaluated context, in
8576 // particular, in the operand of a noexcept-expression, and we can be
8577 // unable to compute an exception specification for an enclosed class.
8578 //
8579 // We do not allow an in-class initializer to require the evaluation
8580 // of the exception specification for any in-class initializer whose
8581 // definition is not lexically complete.
8582 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith938f40b2011-06-11 17:19:42 +00008583 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00008584 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00008585 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8586 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8587 // If this is a deleted function, add it anyway. This might be conformant
8588 // with the standard. This might not. I'm not sure. It might not matter.
8589 // In particular, the problem is that this function never gets called. It
8590 // might just be ill-formed because this function attempts to refer to
8591 // a deleted function here.
8592 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00008593 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00008594 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00008595 }
John McCalldb40c7f2010-12-14 08:05:40 +00008596
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008597 return ExceptSpec;
8598}
8599
Richard Smithc2bc61b2013-03-18 21:12:30 +00008600Sema::ImplicitExceptionSpecification
Richard Smithb7151b92013-04-10 06:11:48 +00008601Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8602 CXXRecordDecl *ClassDecl = CD->getParent();
8603
8604 // C++ [except.spec]p14:
8605 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00008606 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00008607 if (ClassDecl->isInvalidDecl())
8608 return ExceptSpec;
8609
8610 // Inherited constructor.
8611 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8612 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8613 // FIXME: Copying or moving the parameters could add extra exceptions to the
8614 // set, as could the default arguments for the inherited constructor. This
8615 // will be addressed when we implement the resolution of core issue 1351.
8616 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8617
8618 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00008619 for (const auto &B : ClassDecl->bases()) {
8620 if (B.isVirtual()) // Handled below.
Richard Smithb7151b92013-04-10 06:11:48 +00008621 continue;
8622
Aaron Ballman574705e2014-03-13 15:41:46 +00008623 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008624 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8625 if (BaseClassDecl == InheritedDecl)
8626 continue;
8627 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8628 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00008629 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008630 }
8631 }
8632
8633 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00008634 for (const auto &B : ClassDecl->vbases()) {
8635 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008636 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8637 if (BaseClassDecl == InheritedDecl)
8638 continue;
8639 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8640 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00008641 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00008642 }
8643 }
8644
8645 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008646 for (const auto *F : ClassDecl->fields()) {
Richard Smithb7151b92013-04-10 06:11:48 +00008647 if (F->hasInClassInitializer()) {
8648 if (Expr *E = F->getInClassInitializer())
8649 ExceptSpec.CalledExpr(E);
8650 else if (!F->isInvalidDecl())
8651 Diag(CD->getLocation(),
8652 diag::err_in_class_initializer_references_def_ctor) << CD;
8653 } else if (const RecordType *RecordTy
8654 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8655 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8656 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8657 if (Constructor)
8658 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8659 }
8660 }
8661
Richard Smithc2bc61b2013-03-18 21:12:30 +00008662 return ExceptSpec;
8663}
8664
Richard Smith8bf22e52012-11-29 01:34:07 +00008665namespace {
8666/// RAII object to register a special member as being currently declared.
8667struct DeclaringSpecialMember {
8668 Sema &S;
8669 Sema::SpecialMemberDecl D;
8670 bool WasAlreadyBeingDeclared;
8671
8672 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8673 : S(S), D(RD, CSM) {
8674 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8675 if (WasAlreadyBeingDeclared)
8676 // This almost never happens, but if it does, ensure that our cache
8677 // doesn't contain a stale result.
8678 S.SpecialMemberCache.clear();
8679
8680 // FIXME: Register a note to be produced if we encounter an error while
8681 // declaring the special member.
8682 }
8683 ~DeclaringSpecialMember() {
8684 if (!WasAlreadyBeingDeclared)
8685 S.SpecialMembersBeingDeclared.erase(D);
8686 }
8687
8688 /// \brief Are we already trying to declare this special member?
8689 bool isAlreadyBeingDeclared() const {
8690 return WasAlreadyBeingDeclared;
8691 }
8692};
8693}
8694
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008695CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8696 CXXRecordDecl *ClassDecl) {
8697 // C++ [class.ctor]p5:
8698 // A default constructor for a class X is a constructor of class X
8699 // that can be called without an argument. If there is no
8700 // user-declared constructor for class X, a default constructor is
8701 // implicitly declared. An implicitly-declared default constructor
8702 // is an inline public member of its class.
Eli Bendersky9a220fc2014-09-29 20:38:29 +00008703 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00008704 "Should not build implicit default constructor!");
8705
Richard Smith8bf22e52012-11-29 01:34:07 +00008706 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8707 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00008708 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00008709
Richard Smithb5800092012-06-10 05:43:50 +00008710 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8711 CXXDefaultConstructor,
8712 false);
8713
Douglas Gregor6d880b12010-07-01 22:31:05 +00008714 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008715 CanQualType ClassType
8716 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008717 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008718 DeclarationName Name
8719 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00008720 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00008721 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00008722 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8723 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8724 /*isImplicitlyDeclared=*/true, Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008725 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00008726 DefaultCon->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +00008727
8728 if (getLangOpts().CUDA) {
8729 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
8730 DefaultCon,
8731 /* ConstRHS */ false,
8732 /* Diagnose */ false);
8733 }
Richard Smithd3b5c9082012-07-27 04:22:15 +00008734
8735 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00008736 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008737 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00008738
Richard Smith6b02d462012-12-08 08:32:28 +00008739 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8740 // constructors is easy to compute.
8741 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8742
8743 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00008744 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00008745
Douglas Gregor9672f922010-07-03 00:47:00 +00008746 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00008747 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00008748
Douglas Gregor0be31a22010-07-02 17:43:08 +00008749 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00008750 PushOnScopeChains(DefaultCon, S, false);
8751 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008752
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00008753 return DefaultCon;
8754}
8755
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008756void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8757 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00008758 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008759 !Constructor->doesThisDeclarationHaveABody() &&
8760 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00008761 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008762
Anders Carlsson423f5d82010-04-23 16:04:08 +00008763 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00008764 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00008765
Eli Friedmaneaf34142012-10-18 20:14:08 +00008766 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008767 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +00008768 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008769 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00008770 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00008771 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00008772 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00008773 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00008774 }
Douglas Gregor73193272010-09-20 16:48:21 +00008775
Ben Langmuir2f8e6b82014-09-25 20:55:00 +00008776 // The exception specification is needed because we are defining the
8777 // function.
8778 ResolveExceptionSpec(CurrentLocation,
8779 Constructor->getType()->castAs<FunctionProtoType>());
8780
Daniel Jasperb3b0b802014-06-20 08:44:22 +00008781 SourceLocation Loc = Constructor->getLocEnd().isValid()
8782 ? Constructor->getLocEnd()
8783 : Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00008784 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +00008785
Eli Friedman276dd182013-09-05 00:02:25 +00008786 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +00008787 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00008788
8789 if (ASTMutationListener *L = getASTMutationListener()) {
8790 L->CompletedImplicitDefinition(Constructor);
8791 }
Richard Trieuef64e942013-10-25 00:56:00 +00008792
8793 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00008794}
8795
Richard Smith938f40b2011-06-11 17:19:42 +00008796void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +00008797 // Perform any delayed checks on exception specifications.
8798 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +00008799}
8800
Richard Smith185be182013-04-10 05:48:59 +00008801namespace {
8802/// Information on inheriting constructors to declare.
8803class InheritingConstructorInfo {
8804public:
8805 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8806 : SemaRef(SemaRef), Derived(Derived) {
8807 // Mark the constructors that we already have in the derived class.
8808 //
8809 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8810 // unless there is a user-declared constructor with the same signature in
8811 // the class where the using-declaration appears.
8812 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8813 }
8814
8815 void inheritAll(CXXRecordDecl *RD) {
8816 visitAll(RD, &InheritingConstructorInfo::inherit);
8817 }
8818
8819private:
8820 /// Information about an inheriting constructor.
8821 struct InheritingConstructor {
8822 InheritingConstructor()
Craig Topperc3ec1492014-05-26 06:22:03 +00008823 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
Richard Smith185be182013-04-10 05:48:59 +00008824
8825 /// If \c true, a constructor with this signature is already declared
8826 /// in the derived class.
8827 bool DeclaredInDerived;
8828
8829 /// The constructor which is inherited.
8830 const CXXConstructorDecl *BaseCtor;
8831
8832 /// The derived constructor we declared.
8833 CXXConstructorDecl *DerivedCtor;
8834 };
8835
8836 /// Inheriting constructors with a given canonical type. There can be at
8837 /// most one such non-template constructor, and any number of templated
8838 /// constructors.
8839 struct InheritingConstructorsForType {
8840 InheritingConstructor NonTemplate;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008841 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8842 Templates;
Richard Smith185be182013-04-10 05:48:59 +00008843
8844 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8845 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8846 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8847 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8848 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8849 false, S.TPL_TemplateMatch))
8850 return Templates[I].second;
8851 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8852 return Templates.back().second;
Sebastian Redl08905022011-02-05 19:23:19 +00008853 }
Richard Smith185be182013-04-10 05:48:59 +00008854
8855 return NonTemplate;
8856 }
8857 };
8858
8859 /// Get or create the inheriting constructor record for a constructor.
8860 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8861 QualType CtorType) {
8862 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8863 .getEntry(SemaRef, Ctor);
8864 }
8865
8866 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8867
8868 /// Process all constructors for a class.
8869 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00008870 for (const auto *Ctor : RD->ctors())
8871 (this->*Callback)(Ctor);
Richard Smith185be182013-04-10 05:48:59 +00008872 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8873 I(RD->decls_begin()), E(RD->decls_end());
8874 I != E; ++I) {
8875 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8876 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8877 (this->*Callback)(CD);
Sebastian Redl08905022011-02-05 19:23:19 +00008878 }
8879 }
Richard Smith185be182013-04-10 05:48:59 +00008880
8881 /// Note that a constructor (or constructor template) was declared in Derived.
8882 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8883 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8884 }
8885
8886 /// Inherit a single constructor.
8887 void inherit(const CXXConstructorDecl *Ctor) {
8888 const FunctionProtoType *CtorType =
8889 Ctor->getType()->castAs<FunctionProtoType>();
Craig Topper5fc8fc22014-08-27 06:28:36 +00008890 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
Richard Smith185be182013-04-10 05:48:59 +00008891 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8892
8893 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8894
8895 // Core issue (no number yet): the ellipsis is always discarded.
8896 if (EPI.Variadic) {
8897 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8898 SemaRef.Diag(Ctor->getLocation(),
8899 diag::note_using_decl_constructor_ellipsis);
8900 EPI.Variadic = false;
8901 }
8902
8903 // Declare a constructor for each number of parameters.
8904 //
8905 // C++11 [class.inhctor]p1:
8906 // The candidate set of inherited constructors from the class X named in
8907 // the using-declaration consists of [... modulo defects ...] for each
8908 // constructor or constructor template of X, the set of constructors or
8909 // constructor templates that results from omitting any ellipsis parameter
8910 // specification and successively omitting parameters with a default
8911 // argument from the end of the parameter-type-list
Richard Smith3c626ed2013-04-17 19:00:52 +00008912 unsigned MinParams = minParamsToInherit(Ctor);
8913 unsigned Params = Ctor->getNumParams();
8914 if (Params >= MinParams) {
8915 do
8916 declareCtor(UsingLoc, Ctor,
8917 SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00008918 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
Richard Smith3c626ed2013-04-17 19:00:52 +00008919 while (Params > MinParams &&
8920 Ctor->getParamDecl(--Params)->hasDefaultArg());
8921 }
Richard Smith185be182013-04-10 05:48:59 +00008922 }
8923
8924 /// Find the using-declaration which specified that we should inherit the
8925 /// constructors of \p Base.
8926 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8927 // No fancy lookup required; just look for the base constructor name
8928 // directly within the derived class.
8929 ASTContext &Context = SemaRef.Context;
8930 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8931 Context.getCanonicalType(Context.getRecordType(Base)));
8932 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8933 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8934 }
8935
8936 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8937 // C++11 [class.inhctor]p3:
8938 // [F]or each constructor template in the candidate set of inherited
8939 // constructors, a constructor template is implicitly declared
8940 if (Ctor->getDescribedFunctionTemplate())
8941 return 0;
8942
8943 // For each non-template constructor in the candidate set of inherited
8944 // constructors other than a constructor having no parameters or a
8945 // copy/move constructor having a single parameter, a constructor is
8946 // implicitly declared [...]
8947 if (Ctor->getNumParams() == 0)
8948 return 1;
8949 if (Ctor->isCopyOrMoveConstructor())
8950 return 2;
8951
8952 // Per discussion on core reflector, never inherit a constructor which
8953 // would become a default, copy, or move constructor of Derived either.
8954 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8955 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8956 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8957 }
8958
8959 /// Declare a single inheriting constructor, inheriting the specified
8960 /// constructor, with the given type.
8961 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8962 QualType DerivedType) {
8963 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8964
8965 // C++11 [class.inhctor]p3:
8966 // ... a constructor is implicitly declared with the same constructor
8967 // characteristics unless there is a user-declared constructor with
8968 // the same signature in the class where the using-declaration appears
8969 if (Entry.DeclaredInDerived)
8970 return;
8971
8972 // C++11 [class.inhctor]p7:
8973 // If two using-declarations declare inheriting constructors with the
8974 // same signature, the program is ill-formed
8975 if (Entry.DerivedCtor) {
8976 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8977 // Only diagnose this once per constructor.
8978 if (Entry.DerivedCtor->isInvalidDecl())
8979 return;
8980 Entry.DerivedCtor->setInvalidDecl();
8981
8982 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8983 SemaRef.Diag(BaseCtor->getLocation(),
8984 diag::note_using_decl_constructor_conflict_current_ctor);
8985 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8986 diag::note_using_decl_constructor_conflict_previous_ctor);
8987 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8988 diag::note_using_decl_constructor_conflict_previous_using);
8989 } else {
8990 // Core issue (no number): if the same inheriting constructor is
8991 // produced by multiple base class constructors from the same base
8992 // class, the inheriting constructor is defined as deleted.
8993 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8994 }
8995
8996 return;
8997 }
8998
8999 ASTContext &Context = SemaRef.Context;
9000 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9001 Context.getCanonicalType(Context.getRecordType(Derived)));
9002 DeclarationNameInfo NameInfo(Name, UsingLoc);
9003
Craig Topperc3ec1492014-05-26 06:22:03 +00009004 TemplateParameterList *TemplateParams = nullptr;
Richard Smith185be182013-04-10 05:48:59 +00009005 if (const FunctionTemplateDecl *FTD =
9006 BaseCtor->getDescribedFunctionTemplate()) {
9007 TemplateParams = FTD->getTemplateParameters();
9008 // We're reusing template parameters from a different DeclContext. This
9009 // is questionable at best, but works out because the template depth in
9010 // both places is guaranteed to be 0.
9011 // FIXME: Rebuild the template parameters in the new context, and
9012 // transform the function type to refer to them.
9013 }
9014
9015 // Build type source info pointing at the using-declaration. This is
9016 // required by template instantiation.
9017 TypeSourceInfo *TInfo =
9018 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
9019 FunctionProtoTypeLoc ProtoLoc =
9020 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
9021
9022 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
9023 Context, Derived, UsingLoc, NameInfo, DerivedType,
9024 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
9025 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
9026
9027 // Build an unevaluated exception specification for this constructor.
9028 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
9029 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00009030 EPI.ExceptionSpec.Type = EST_Unevaluated;
9031 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
Alp Toker314cc812014-01-25 16:55:45 +00009032 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00009033 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +00009034
9035 // Build the parameter declarations.
9036 SmallVector<ParmVarDecl *, 16> ParamDecls;
Alp Toker9cacbab2014-01-20 20:26:09 +00009037 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +00009038 TypeSourceInfo *TInfo =
Alp Toker9cacbab2014-01-20 20:26:09 +00009039 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
Richard Smith185be182013-04-10 05:48:59 +00009040 ParmVarDecl *PD = ParmVarDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00009041 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
9042 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
Richard Smith185be182013-04-10 05:48:59 +00009043 PD->setScopeInfo(0, I);
9044 PD->setImplicit();
9045 ParamDecls.push_back(PD);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009046 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +00009047 }
9048
9049 // Set up the new constructor.
9050 DerivedCtor->setAccess(BaseCtor->getAccess());
9051 DerivedCtor->setParams(ParamDecls);
9052 DerivedCtor->setInheritedConstructor(BaseCtor);
9053 if (BaseCtor->isDeleted())
9054 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
9055
9056 // If this is a constructor template, build the template declaration.
9057 if (TemplateParams) {
9058 FunctionTemplateDecl *DerivedTemplate =
9059 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
9060 TemplateParams, DerivedCtor);
9061 DerivedTemplate->setAccess(BaseCtor->getAccess());
9062 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
9063 Derived->addDecl(DerivedTemplate);
9064 } else {
9065 Derived->addDecl(DerivedCtor);
9066 }
9067
9068 Entry.BaseCtor = BaseCtor;
9069 Entry.DerivedCtor = DerivedCtor;
9070 }
9071
9072 Sema &SemaRef;
9073 CXXRecordDecl *Derived;
9074 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
9075 MapType Map;
9076};
9077}
9078
9079void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
9080 // Defer declaring the inheriting constructors until the class is
9081 // instantiated.
9082 if (ClassDecl->isDependentContext())
Sebastian Redl08905022011-02-05 19:23:19 +00009083 return;
9084
Richard Smith185be182013-04-10 05:48:59 +00009085 // Find base classes from which we might inherit constructors.
9086 SmallVector<CXXRecordDecl*, 4> InheritedBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00009087 for (const auto &BaseIt : ClassDecl->bases())
9088 if (BaseIt.getInheritConstructors())
9089 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
Richard Smithc2bc61b2013-03-18 21:12:30 +00009090
Richard Smith185be182013-04-10 05:48:59 +00009091 // Go no further if we're not inheriting any constructors.
9092 if (InheritedBases.empty())
9093 return;
Sebastian Redl08905022011-02-05 19:23:19 +00009094
Richard Smith185be182013-04-10 05:48:59 +00009095 // Declare the inherited constructors.
9096 InheritingConstructorInfo ICI(*this, ClassDecl);
9097 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
9098 ICI.inheritAll(InheritedBases[I]);
Sebastian Redl08905022011-02-05 19:23:19 +00009099}
9100
Richard Smithc2bc61b2013-03-18 21:12:30 +00009101void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
9102 CXXConstructorDecl *Constructor) {
9103 CXXRecordDecl *ClassDecl = Constructor->getParent();
9104 assert(Constructor->getInheritedConstructor() &&
9105 !Constructor->doesThisDeclarationHaveABody() &&
9106 !Constructor->isDeleted());
9107
9108 SynthesizedFunctionScope Scope(*this, Constructor);
9109 DiagnosticErrorTrap Trap(Diags);
9110 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9111 Trap.hasErrorOccurred()) {
9112 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
9113 << Context.getTagDeclType(ClassDecl);
9114 Constructor->setInvalidDecl();
9115 return;
9116 }
9117
9118 SourceLocation Loc = Constructor->getLocation();
9119 Constructor->setBody(new (Context) CompoundStmt(Loc));
9120
Eli Friedman276dd182013-09-05 00:02:25 +00009121 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +00009122 MarkVTableUsed(CurrentLocation, ClassDecl);
9123
9124 if (ASTMutationListener *L = getASTMutationListener()) {
9125 L->CompletedImplicitDefinition(Constructor);
9126 }
9127}
9128
9129
Alexis Huntf91729462011-05-12 22:46:25 +00009130Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009131Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
9132 CXXRecordDecl *ClassDecl = MD->getParent();
9133
Douglas Gregorf1203042010-07-01 19:09:28 +00009134 // C++ [except.spec]p14:
9135 // An implicitly declared special member function (Clause 12) shall have
9136 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +00009137 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009138 if (ClassDecl->isInvalidDecl())
9139 return ExceptSpec;
9140
Douglas Gregorf1203042010-07-01 19:09:28 +00009141 // Direct base-class destructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00009142 for (const auto &B : ClassDecl->bases()) {
9143 if (B.isVirtual()) // Handled below.
Douglas Gregorf1203042010-07-01 19:09:28 +00009144 continue;
9145
Aaron Ballman574705e2014-03-13 15:41:46 +00009146 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9147 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009148 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009149 }
Sebastian Redl623ea822011-05-19 05:13:44 +00009150
Douglas Gregorf1203042010-07-01 19:09:28 +00009151 // Virtual base-class destructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00009152 for (const auto &B : ClassDecl->vbases()) {
9153 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9154 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009155 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009156 }
Sebastian Redl623ea822011-05-19 05:13:44 +00009157
Douglas Gregorf1203042010-07-01 19:09:28 +00009158 // Field destructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009159 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorf1203042010-07-01 19:09:28 +00009160 if (const RecordType *RecordTy
9161 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +00009162 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +00009163 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00009164 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009165
Alexis Huntf91729462011-05-12 22:46:25 +00009166 return ExceptSpec;
9167}
9168
9169CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
9170 // C++ [class.dtor]p2:
9171 // If a class has no user-declared destructor, a destructor is
9172 // declared implicitly. An implicitly-declared destructor is an
9173 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +00009174 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +00009175
Richard Smith8bf22e52012-11-29 01:34:07 +00009176 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
9177 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009178 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009179
Douglas Gregor7454c562010-07-02 20:37:36 +00009180 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00009181 CanQualType ClassType
9182 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00009183 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00009184 DeclarationName Name
9185 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009186 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00009187 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +00009188 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +00009189 QualType(), nullptr, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009190 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00009191 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00009192 Destructor->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009193
9194 if (getLangOpts().CUDA) {
9195 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
9196 Destructor,
9197 /* ConstRHS */ false,
9198 /* Diagnose */ false);
9199 }
Richard Smithd3b5c9082012-07-27 04:22:15 +00009200
9201 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00009202 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009203 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009204
Richard Smith6b02d462012-12-08 08:32:28 +00009205 AddOverriddenMethods(ClassDecl, Destructor);
9206
9207 // We don't need to use SpecialMemberIsTrivial here; triviality for
9208 // destructors is easy to compute.
9209 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
9210
9211 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smithb4d2a152013-04-02 19:38:47 +00009212 SetDeclDeleted(Destructor, ClassLoc);
Richard Smith6b02d462012-12-08 08:32:28 +00009213
Douglas Gregor7454c562010-07-02 20:37:36 +00009214 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00009215 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +00009216
Douglas Gregor7454c562010-07-02 20:37:36 +00009217 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00009218 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00009219 PushOnScopeChains(Destructor, S, false);
9220 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +00009221
Douglas Gregorf1203042010-07-01 19:09:28 +00009222 return Destructor;
9223}
9224
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009225void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00009226 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00009227 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +00009228 !Destructor->doesThisDeclarationHaveABody() &&
9229 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009230 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00009231 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009232 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009233
Douglas Gregor54818f02010-05-12 16:39:35 +00009234 if (Destructor->isInvalidDecl())
9235 return;
9236
Eli Friedmaneaf34142012-10-18 20:14:08 +00009237 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009238
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009239 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00009240 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9241 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00009242
Douglas Gregor54818f02010-05-12 16:39:35 +00009243 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00009244 Diag(CurrentLocation, diag::note_member_synthesized_at)
9245 << CXXDestructor << Context.getTagDeclType(ClassDecl);
9246
9247 Destructor->setInvalidDecl();
9248 return;
9249 }
9250
Ben Langmuir2f8e6b82014-09-25 20:55:00 +00009251 // The exception specification is needed because we are defining the
9252 // function.
9253 ResolveExceptionSpec(CurrentLocation,
9254 Destructor->getType()->castAs<FunctionProtoType>());
9255
Daniel Jasperb3b0b802014-06-20 08:44:22 +00009256 SourceLocation Loc = Destructor->getLocEnd().isValid()
9257 ? Destructor->getLocEnd()
9258 : Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +00009259 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +00009260 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009261 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00009262
9263 if (ASTMutationListener *L = getASTMutationListener()) {
9264 L->CompletedImplicitDefinition(Destructor);
9265 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009266}
9267
Richard Smith84973e52012-04-21 18:42:51 +00009268/// \brief Perform any semantic analysis which needs to be delayed until all
9269/// pending class member declarations have been parsed.
9270void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00009271 // If the context is an invalid C++ class, just suppress these checks.
9272 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9273 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +00009274 DelayedDefaultedMemberExceptionSpecs.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +00009275 DelayedDestructorExceptionSpecChecks.clear();
9276 return;
9277 }
9278 }
Richard Smith84973e52012-04-21 18:42:51 +00009279}
9280
Richard Smithd3b5c9082012-07-27 04:22:15 +00009281void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9282 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009283 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +00009284 "adjusting dtor exception specs was introduced in c++11");
9285
Sebastian Redl623ea822011-05-19 05:13:44 +00009286 // C++11 [class.dtor]p3:
9287 // A declaration of a destructor that does not have an exception-
9288 // specification is implicitly considered to have the same exception-
9289 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009290 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +00009291 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009292 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +00009293 return;
9294
Chandler Carruth9a797572011-09-20 04:55:26 +00009295 // Replace the destructor's type, building off the existing one. Fortunately,
9296 // the only thing of interest in the destructor type is its extended info.
9297 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009298 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00009299 EPI.ExceptionSpec.Type = EST_Unevaluated;
9300 EPI.ExceptionSpec.SourceDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009301 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +00009302
Sebastian Redl623ea822011-05-19 05:13:44 +00009303 // FIXME: If the destructor has a body that could throw, and the newly created
9304 // spec doesn't allow exceptions, we should emit a warning, because this
9305 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +00009306 // However, we don't have a body or an exception specification yet, so it
9307 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +00009308}
9309
Pavel Labath58934982013-08-30 08:52:28 +00009310namespace {
9311/// \brief An abstract base class for all helper classes used in building the
9312// copy/move operators. These classes serve as factory functions and help us
9313// avoid using the same Expr* in the AST twice.
9314class ExprBuilder {
9315 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9316 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9317
9318protected:
9319 static Expr *assertNotNull(Expr *E) {
9320 assert(E && "Expression construction must not fail.");
9321 return E;
9322 }
9323
9324public:
9325 ExprBuilder() {}
9326 virtual ~ExprBuilder() {}
9327
9328 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9329};
9330
9331class RefBuilder: public ExprBuilder {
9332 VarDecl *Var;
9333 QualType VarType;
9334
9335public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009336 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009337 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009338 }
9339
9340 RefBuilder(VarDecl *Var, QualType VarType)
9341 : Var(Var), VarType(VarType) {}
9342};
9343
9344class ThisBuilder: public ExprBuilder {
9345public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009346 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009347 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
Pavel Labath58934982013-08-30 08:52:28 +00009348 }
9349};
9350
9351class CastBuilder: public ExprBuilder {
9352 const ExprBuilder &Builder;
9353 QualType Type;
9354 ExprValueKind Kind;
9355 const CXXCastPath &Path;
9356
9357public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009358 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009359 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9360 CK_UncheckedDerivedToBase, Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009361 &Path).get());
Pavel Labath58934982013-08-30 08:52:28 +00009362 }
9363
9364 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9365 const CXXCastPath &Path)
9366 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9367};
9368
9369class DerefBuilder: public ExprBuilder {
9370 const ExprBuilder &Builder;
9371
9372public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009373 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009374 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009375 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009376 }
9377
9378 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9379};
9380
9381class MemberBuilder: public ExprBuilder {
9382 const ExprBuilder &Builder;
9383 QualType Type;
9384 CXXScopeSpec SS;
9385 bool IsArrow;
9386 LookupResult &MemberLookup;
9387
9388public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009389 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009390 return assertNotNull(S.BuildMemberReferenceExpr(
Craig Topperc3ec1492014-05-26 06:22:03 +00009391 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009392 nullptr, MemberLookup, nullptr).get());
Pavel Labath58934982013-08-30 08:52:28 +00009393 }
9394
9395 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9396 LookupResult &MemberLookup)
9397 : Builder(Builder), Type(Type), IsArrow(IsArrow),
9398 MemberLookup(MemberLookup) {}
9399};
9400
9401class MoveCastBuilder: public ExprBuilder {
9402 const ExprBuilder &Builder;
9403
9404public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009405 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009406 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9407 }
9408
9409 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9410};
9411
9412class LvalueConvBuilder: public ExprBuilder {
9413 const ExprBuilder &Builder;
9414
9415public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009416 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009417 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009418 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +00009419 }
9420
9421 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9422};
9423
9424class SubscriptBuilder: public ExprBuilder {
9425 const ExprBuilder &Base;
9426 const ExprBuilder &Index;
9427
9428public:
Craig Toppera798a9d2014-03-02 09:32:10 +00009429 virtual Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +00009430 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009431 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +00009432 }
9433
9434 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9435 : Base(Base), Index(Index) {}
9436};
9437
9438} // end anonymous namespace
9439
Richard Smith41ae3282012-11-14 00:50:40 +00009440/// When generating a defaulted copy or move assignment operator, if a field
9441/// should be copied with __builtin_memcpy rather than via explicit assignments,
9442/// do so. This optimization only applies for arrays of scalars, and for arrays
9443/// of class type where the selected copy/move-assignment operator is trivial.
9444static StmtResult
9445buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009446 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +00009447 // Compute the size of the memory buffer to be copied.
9448 QualType SizeType = S.Context.getSizeType();
9449 llvm::APInt Size(S.Context.getTypeSize(SizeType),
9450 S.Context.getTypeSizeInChars(T).getQuantity());
9451
9452 // Take the address of the field references for "from" and "to". We
9453 // directly construct UnaryOperators here because semantic analysis
9454 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +00009455 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009456 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9457 S.Context.getPointerType(From->getType()),
9458 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +00009459 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009460 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9461 S.Context.getPointerType(To->getType()),
9462 VK_RValue, OK_Ordinary, Loc);
9463
9464 const Type *E = T->getBaseElementTypeUnsafe();
9465 bool NeedsCollectableMemCpy =
9466 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9467
9468 // Create a reference to the __builtin_objc_memmove_collectable function
9469 StringRef MemCpyName = NeedsCollectableMemCpy ?
9470 "__builtin_objc_memmove_collectable" :
9471 "__builtin_memcpy";
9472 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9473 Sema::LookupOrdinaryName);
9474 S.LookupName(R, S.TUScope, true);
9475
9476 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9477 if (!MemCpy)
9478 // Something went horribly wrong earlier, and we will have complained
9479 // about it.
9480 return StmtError();
9481
9482 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
Craig Topperc3ec1492014-05-26 06:22:03 +00009483 VK_RValue, Loc, nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009484 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9485
9486 Expr *CallArgs[] = {
9487 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9488 };
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009489 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
Richard Smith41ae3282012-11-14 00:50:40 +00009490 Loc, CallArgs, Loc);
9491
9492 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009493 return Call.getAs<Stmt>();
Richard Smith41ae3282012-11-14 00:50:40 +00009494}
9495
Sebastian Redl22653ba2011-08-30 19:58:05 +00009496/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00009497/// \c To.
9498///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009499/// This routine is used to copy/move the members of a class with an
9500/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00009501/// copied are arrays, this routine builds for loops to copy them.
9502///
9503/// \param S The Sema object used for type-checking.
9504///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009505/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009506///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009507/// \param T The type of the expressions being copied/moved. Both expressions
9508/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009509///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009510/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009511///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009512/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00009513///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009514/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009515/// Otherwise, it's a non-static member subobject.
9516///
Sebastian Redl22653ba2011-08-30 19:58:05 +00009517/// \param Copying Whether we're copying or moving.
9518///
Douglas Gregorb139cd52010-05-01 20:49:11 +00009519/// \param Depth Internal parameter recording the depth of the recursion.
9520///
Richard Smith41ae3282012-11-14 00:50:40 +00009521/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9522/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +00009523static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +00009524buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009525 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009526 bool CopyingBaseSubobject, bool Copying,
9527 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +00009528 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00009529 // Each subobject is assigned in the manner appropriate to its type:
9530 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00009531 // - if the subobject is of class type, as if by a call to operator= with
9532 // the subobject as the object expression and the corresponding
9533 // subobject of x as a single function argument (as if by explicit
9534 // qualification; that is, ignoring any possible virtual overriding
9535 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +00009536 //
9537 // C++03 [class.copy]p13:
9538 // - if the subobject is of class type, the copy assignment operator for
9539 // the class is used (as if by explicit qualification; that is,
9540 // ignoring any possible virtual overriding functions in more derived
9541 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009542 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9543 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +00009544
Douglas Gregorb139cd52010-05-01 20:49:11 +00009545 // Look for operator=.
9546 DeclarationName Name
9547 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9548 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9549 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009550
Richard Smith52c0b582012-11-13 00:54:12 +00009551 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9552 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009553 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +00009554 LookupResult::Filter F = OpLookup.makeFilter();
9555 while (F.hasNext()) {
9556 NamedDecl *D = F.next();
9557 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9558 if (Method->isCopyAssignmentOperator() ||
9559 (!Copying && Method->isMoveAssignmentOperator()))
9560 continue;
9561
9562 F.erase();
9563 }
9564 F.done();
John McCallab8c2732010-03-16 06:11:48 +00009565 }
Richard Smith52c0b582012-11-13 00:54:12 +00009566
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009567 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +00009568 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009569 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +00009570 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +00009571 // ambiguities), we need to cast "this" to that subobject type; to
9572 // ensure that we don't go through the virtual call mechanism, we need
9573 // to qualify the operator= name with the base class (see below). However,
9574 // this means that if the base class has a protected copy assignment
9575 // operator, the protected member access check will fail. So, we
9576 // rewrite "protected" access to "public" access in this case, since we
9577 // know by construction that we're calling from a derived class.
9578 if (CopyingBaseSubobject) {
9579 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9580 L != LEnd; ++L) {
9581 if (L.getAccess() == AS_protected)
9582 L.setAccess(AS_public);
9583 }
9584 }
Richard Smith52c0b582012-11-13 00:54:12 +00009585
Douglas Gregorb139cd52010-05-01 20:49:11 +00009586 // Create the nested-name-specifier that will be used to qualify the
9587 // reference to operator=; this is required to suppress the virtual
9588 // call mechanism.
9589 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00009590 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +00009591 SS.MakeTrivial(S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +00009592 NestedNameSpecifier::Create(S.Context, nullptr, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00009593 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00009594 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +00009595
Douglas Gregorb139cd52010-05-01 20:49:11 +00009596 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00009597 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +00009598 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9599 SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009600 /*FirstQualifierInScope=*/nullptr,
Abramo Bagnara7945c982012-01-27 09:46:47 +00009601 OpLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +00009602 /*TemplateArgs=*/nullptr,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009603 /*SuppressQualifierCheck=*/true);
9604 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009605 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009606
Douglas Gregorb139cd52010-05-01 20:49:11 +00009607 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00009608
Pavel Labath58934982013-08-30 08:52:28 +00009609 Expr *FromInst = From.build(S, Loc);
Craig Topperc3ec1492014-05-26 06:22:03 +00009610 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009611 OpEqualRef.getAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +00009612 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009613 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009614 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +00009615
Richard Smith41ae3282012-11-14 00:50:40 +00009616 // If we built a call to a trivial 'operator=' while copying an array,
9617 // bail out. We'll replace the whole shebang with a memcpy.
9618 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9619 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
Craig Topperc3ec1492014-05-26 06:22:03 +00009620 return StmtResult((Stmt*)nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +00009621
Richard Smith52c0b582012-11-13 00:54:12 +00009622 // Convert to an expression-statement, and clean up any produced
9623 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +00009624 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009625 }
John McCallab8c2732010-03-16 06:11:48 +00009626
Richard Smith52c0b582012-11-13 00:54:12 +00009627 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +00009628 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +00009629 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009630 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +00009631 ExprResult Assignment = S.CreateBuiltinBinOp(
9632 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009633 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00009634 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +00009635 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009636 }
Richard Smith52c0b582012-11-13 00:54:12 +00009637
9638 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +00009639 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +00009640
Douglas Gregorb139cd52010-05-01 20:49:11 +00009641 // Construct a loop over the array bounds, e.g.,
9642 //
9643 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9644 //
9645 // that will copy each of the array elements.
9646 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +00009647
Douglas Gregorb139cd52010-05-01 20:49:11 +00009648 // Create the iteration variable.
Craig Topperc3ec1492014-05-26 06:22:03 +00009649 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009650 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009651 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009652 llvm::raw_svector_ostream OS(Str);
9653 OS << "__i" << Depth;
9654 IterationVarName = &S.Context.Idents.get(OS.str());
9655 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00009656 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009657 IterationVarName, SizeType,
9658 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00009659 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +00009660
Douglas Gregorb139cd52010-05-01 20:49:11 +00009661 // Initialize the iteration variable to zero.
9662 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009663 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00009664
Pavel Labath58934982013-08-30 08:52:28 +00009665 // Creates a reference to the iteration variable.
9666 RefBuilder IterationVarRef(IterationVar, SizeType);
9667 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +00009668
Douglas Gregorb139cd52010-05-01 20:49:11 +00009669 // Create the DeclStmt that holds the iteration variable.
9670 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009671
Douglas Gregorb139cd52010-05-01 20:49:11 +00009672 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +00009673 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9674 MoveCastBuilder FromIndexMove(FromIndexCopy);
9675 const ExprBuilder *FromIndex;
9676 if (Copying)
9677 FromIndex = &FromIndexCopy;
9678 else
9679 FromIndex = &FromIndexMove;
9680
9681 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +00009682
9683 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +00009684 StmtResult Copy =
9685 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +00009686 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +00009687 Copying, Depth + 1);
9688 // Bail out if copying fails or if we determined that we should use memcpy.
9689 if (Copy.isInvalid() || !Copy.get())
9690 return Copy;
9691
9692 // Create the comparison against the array bound.
9693 llvm::APInt Upper
9694 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9695 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +00009696 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +00009697 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9698 BO_NE, S.Context.BoolTy,
9699 VK_RValue, OK_Ordinary, Loc, false);
9700
9701 // Create the pre-increment of the iteration variable.
9702 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +00009703 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9704 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +00009705
Douglas Gregorb139cd52010-05-01 20:49:11 +00009706 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00009707 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00009708 S.MakeFullExpr(Comparison),
Craig Topperc3ec1492014-05-26 06:22:03 +00009709 nullptr, S.MakeFullDiscardedValueExpr(Increment),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009710 Loc, Copy.get());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009711}
9712
Richard Smith41ae3282012-11-14 00:50:40 +00009713static StmtResult
9714buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +00009715 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +00009716 bool CopyingBaseSubobject, bool Copying) {
9717 // Maybe we should use a memcpy?
9718 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9719 T.isTriviallyCopyableType(S.Context))
9720 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9721
9722 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9723 CopyingBaseSubobject,
9724 Copying, 0));
9725
9726 // If we ended up picking a trivial assignment operator for an array of a
9727 // non-trivially-copyable class type, just emit a memcpy.
9728 if (!Result.isInvalid() && !Result.get())
9729 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9730
9731 return Result;
9732}
9733
Richard Smithd3b5c9082012-07-27 04:22:15 +00009734Sema::ImplicitExceptionSpecification
9735Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9736 CXXRecordDecl *ClassDecl = MD->getParent();
9737
9738 ImplicitExceptionSpecification ExceptSpec(*this);
9739 if (ClassDecl->isInvalidDecl())
9740 return ExceptSpec;
9741
9742 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00009743 assert(T->getNumParams() == 1 && "not a copy assignment op");
9744 unsigned ArgQuals =
9745 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009746
Douglas Gregor68e11362010-07-01 17:48:08 +00009747 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +00009748 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +00009749 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00009750
9751 // It is unspecified whether or not an implicit copy assignment operator
9752 // attempts to deduplicate calls to assignment operators of virtual bases are
9753 // made. As such, this exception specification is effectively unspecified.
9754 // Based on a similar decision made for constness in C++0x, we're erring on
9755 // the side of assuming such calls to be made regardless of whether they
9756 // actually happen.
Aaron Ballman574705e2014-03-13 15:41:46 +00009757 for (const auto &Base : ClassDecl->bases()) {
9758 if (Base.isVirtual())
Alexis Hunt491ec602011-06-21 23:42:56 +00009759 continue;
9760
Douglas Gregor330b9cf2010-07-02 21:50:04 +00009761 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00009762 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009763 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9764 ArgQuals, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +00009765 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +00009766 }
Alexis Hunt491ec602011-06-21 23:42:56 +00009767
Aaron Ballman445a9392014-03-13 16:15:17 +00009768 for (const auto &Base : ClassDecl->vbases()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00009769 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +00009770 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00009771 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9772 ArgQuals, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +00009773 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +00009774 }
9775
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009776 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00009777 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00009778 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9779 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +00009780 LookupCopyingAssignment(FieldClassDecl,
9781 ArgQuals | FieldType.getCVRQualifiers(),
9782 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +00009783 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009784 }
Douglas Gregor68e11362010-07-01 17:48:08 +00009785 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009786
Richard Smithd3b5c9082012-07-27 04:22:15 +00009787 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +00009788}
9789
9790CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9791 // Note: The following rules are largely analoguous to the copy
9792 // constructor rules. Note that virtual bases are not taken into account
9793 // for determining the argument type of the operator. Note also that
9794 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +00009795 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +00009796
Richard Smith8bf22e52012-11-29 01:34:07 +00009797 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9798 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009799 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009800
Alexis Hunt119f3652011-05-14 05:23:20 +00009801 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9802 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +00009803 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9804 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +00009805 ArgType = ArgType.withConst();
9806 ArgType = Context.getLValueReferenceType(ArgType);
9807
Richard Smith99005e62013-05-07 03:19:20 +00009808 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9809 CXXCopyAssignment,
9810 Const);
9811
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009812 // An implicitly-declared copy assignment operator is an inline public
9813 // member of its class.
9814 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009815 SourceLocation ClassLoc = ClassDecl->getLocation();
9816 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +00009817 CXXMethodDecl *CopyAssignment =
9818 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00009819 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
9820 /*isInline=*/true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009821 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00009822 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009823 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +00009824
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009825 if (getLangOpts().CUDA) {
9826 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
9827 CopyAssignment,
9828 /* ConstRHS */ Const,
9829 /* Diagnose */ false);
9830 }
9831
Richard Smithd3b5c9082012-07-27 04:22:15 +00009832 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +00009833 FunctionProtoType::ExtProtoInfo EPI =
9834 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +00009835 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009836
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009837 // Add the parameter to the operator.
9838 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +00009839 ClassLoc, ClassLoc,
9840 /*Id=*/nullptr, ArgType,
9841 /*TInfo=*/nullptr, SC_None,
9842 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +00009843 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +00009844
Richard Smith6b02d462012-12-08 08:32:28 +00009845 AddOverriddenMethods(ClassDecl, CopyAssignment);
9846
9847 CopyAssignment->setTrivial(
9848 ClassDecl->needsOverloadResolutionForCopyAssignment()
9849 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9850 : ClassDecl->hasTrivialCopyAssignment());
9851
Richard Smith852265f2012-03-30 20:53:28 +00009852 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smithb4d2a152013-04-02 19:38:47 +00009853 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +00009854
Richard Smith6b02d462012-12-08 08:32:28 +00009855 // Note that we have added this copy-assignment operator.
9856 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9857
9858 if (Scope *S = getScopeForContext(ClassDecl))
9859 PushOnScopeChains(CopyAssignment, S, false);
9860 ClassDecl->addDecl(CopyAssignment);
9861
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00009862 return CopyAssignment;
9863}
9864
Richard Smithd577fbb2013-06-13 03:23:42 +00009865/// Diagnose an implicit copy operation for a class which is odr-used, but
9866/// which is deprecated because the class has a user-declared copy constructor,
9867/// copy assignment operator, or destructor.
9868static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9869 SourceLocation UseLoc) {
9870 assert(CopyOp->isImplicit());
9871
9872 CXXRecordDecl *RD = CopyOp->getParent();
Craig Topperc3ec1492014-05-26 06:22:03 +00009873 CXXMethodDecl *UserDeclaredOperation = nullptr;
Richard Smithd577fbb2013-06-13 03:23:42 +00009874
9875 // In Microsoft mode, assignment operations don't affect constructors and
9876 // vice versa.
9877 if (RD->hasUserDeclaredDestructor()) {
9878 UserDeclaredOperation = RD->getDestructor();
9879 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9880 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009881 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009882 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009883 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009884 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00009885 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009886 break;
9887 }
9888 }
9889 assert(UserDeclaredOperation);
9890 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9891 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +00009892 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009893 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00009894 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +00009895 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00009896 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +00009897 break;
9898 }
9899 }
9900 assert(UserDeclaredOperation);
9901 }
9902
9903 if (UserDeclaredOperation) {
9904 S.Diag(UserDeclaredOperation->getLocation(),
9905 diag::warn_deprecated_copy_operation)
9906 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9907 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9908 S.Diag(UseLoc, diag::note_member_synthesized_at)
9909 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9910 : Sema::CXXCopyAssignment)
9911 << RD;
9912 }
9913}
9914
Douglas Gregorb139cd52010-05-01 20:49:11 +00009915void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9916 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00009917 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009918 CopyAssignOperator->isOverloadedOperator() &&
9919 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +00009920 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9921 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00009922 "DefineImplicitCopyAssignment called for wrong function");
9923
9924 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9925
9926 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9927 CopyAssignOperator->setInvalidDecl();
9928 return;
9929 }
Richard Smithd577fbb2013-06-13 03:23:42 +00009930
9931 // C++11 [class.copy]p18:
9932 // The [definition of an implicitly declared copy assignment operator] is
9933 // deprecated if the class has a user-declared copy constructor or a
9934 // user-declared destructor.
9935 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9936 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9937
Eli Friedman276dd182013-09-05 00:02:25 +00009938 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009939
Eli Friedmaneaf34142012-10-18 20:14:08 +00009940 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00009941 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009942
9943 // C++0x [class.copy]p30:
9944 // The implicitly-defined or explicitly-defaulted copy assignment operator
9945 // for a non-union class X performs memberwise copy assignment of its
9946 // subobjects. The direct base classes of X are assigned first, in the
9947 // order of their declaration in the base-specifier-list, and then the
9948 // immediate non-static data members of X are assigned, in the order in
9949 // which they were declared in the class definition.
9950
9951 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +00009952 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009953
9954 // The parameter for the "other" object, which we are copying from.
9955 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9956 Qualifiers OtherQuals = Other->getType().getQualifiers();
9957 QualType OtherRefType = Other->getType();
9958 if (const LValueReferenceType *OtherRef
9959 = OtherRefType->getAs<LValueReferenceType>()) {
9960 OtherRefType = OtherRef->getPointeeType();
9961 OtherQuals = OtherRefType.getQualifiers();
9962 }
9963
9964 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +00009965 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
9966 ? CopyAssignOperator->getLocEnd()
9967 : CopyAssignOperator->getLocation();
9968
Pavel Labath58934982013-08-30 08:52:28 +00009969 // Builds a DeclRefExpr for the "other" object.
9970 RefBuilder OtherRef(Other, OtherRefType);
9971
9972 // Builds the "this" pointer.
9973 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +00009974
9975 // Assign base classes.
9976 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +00009977 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009978 // Form the assignment:
9979 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +00009980 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00009981 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00009982 Invalid = true;
9983 continue;
9984 }
9985
John McCallcf142162010-08-07 06:22:56 +00009986 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +00009987 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +00009988
Douglas Gregorb139cd52010-05-01 20:49:11 +00009989 // Construct the "from" expression, which is an implicit cast to the
9990 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +00009991 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9992 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00009993
9994 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +00009995 DerefBuilder DerefThis(This);
9996 CastBuilder To(DerefThis,
9997 Context.getCVRQualifiedType(
9998 BaseType, CopyAssignOperator->getTypeQualifiers()),
9999 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010000
10001 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +000010002 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000010003 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010004 /*CopyingBaseSubobject=*/true,
10005 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010006 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010007 Diag(CurrentLocation, diag::note_member_synthesized_at)
10008 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10009 CopyAssignOperator->setInvalidDecl();
10010 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010011 }
10012
10013 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010014 Statements.push_back(Copy.getAs<Expr>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010015 }
10016
Douglas Gregorb139cd52010-05-01 20:49:11 +000010017 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010018 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +000010019 if (Field->isUnnamedBitfield())
10020 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +000010021
10022 if (Field->isInvalidDecl()) {
10023 Invalid = true;
10024 continue;
10025 }
10026
Douglas Gregorb139cd52010-05-01 20:49:11 +000010027 // Check for members of reference type; we can't copy those.
10028 if (Field->getType()->isReferenceType()) {
10029 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10030 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10031 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010032 Diag(CurrentLocation, diag::note_member_synthesized_at)
10033 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010034 Invalid = true;
10035 continue;
10036 }
10037
10038 // Check for members of const-qualified, non-class type.
10039 QualType BaseType = Context.getBaseElementType(Field->getType());
10040 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10041 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10042 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10043 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010044 Diag(CurrentLocation, diag::note_member_synthesized_at)
10045 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010046 Invalid = true;
10047 continue;
10048 }
John McCall1b1a1db2011-06-17 00:18:42 +000010049
10050 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000010051 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10052 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010053
10054 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000010055 if (FieldType->isIncompleteArrayType()) {
10056 assert(ClassDecl->hasFlexibleArrayMember() &&
10057 "Incomplete array type is not valid");
10058 continue;
10059 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000010060
10061 // Build references to the field in the object we're copying from and to.
10062 CXXScopeSpec SS; // Intentionally empty
10063 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10064 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010065 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010066 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000010067
10068 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
10069
10070 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010071
Douglas Gregorb139cd52010-05-01 20:49:11 +000010072 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000010073 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010074 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010075 /*CopyingBaseSubobject=*/false,
10076 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010077 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000010078 Diag(CurrentLocation, diag::note_member_synthesized_at)
10079 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10080 CopyAssignOperator->setInvalidDecl();
10081 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010082 }
10083
10084 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010085 Statements.push_back(Copy.getAs<Stmt>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010086 }
10087
10088 if (!Invalid) {
10089 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +000010090 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000010091
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010092 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +000010093 if (Return.isInvalid())
10094 Invalid = true;
10095 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010096 Statements.push_back(Return.getAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +000010097
10098 if (Trap.hasErrorOccurred()) {
10099 Diag(CurrentLocation, diag::note_member_synthesized_at)
10100 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10101 Invalid = true;
10102 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000010103 }
10104 }
10105
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010106 // The exception specification is needed because we are defining the
10107 // function.
10108 ResolveExceptionSpec(CurrentLocation,
10109 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
10110
Douglas Gregorb139cd52010-05-01 20:49:11 +000010111 if (Invalid) {
10112 CopyAssignOperator->setInvalidDecl();
10113 return;
10114 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010115
10116 StmtResult Body;
10117 {
10118 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010119 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010120 /*isStmtExpr=*/false);
10121 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10122 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010123 CopyAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +000010124
10125 if (ASTMutationListener *L = getASTMutationListener()) {
10126 L->CompletedImplicitDefinition(CopyAssignOperator);
10127 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010128}
10129
Sebastian Redl22653ba2011-08-30 19:58:05 +000010130Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010131Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
10132 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010133
Richard Smithd3b5c9082012-07-27 04:22:15 +000010134 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010135 if (ClassDecl->isInvalidDecl())
10136 return ExceptSpec;
10137
10138 // C++0x [except.spec]p14:
10139 // An implicitly declared special member function (Clause 12) shall have an
10140 // exception-specification. [...]
10141
10142 // It is unspecified whether or not an implicit move assignment operator
10143 // attempts to deduplicate calls to assignment operators of virtual bases are
10144 // made. As such, this exception specification is effectively unspecified.
10145 // Based on a similar decision made for constness in C++0x, we're erring on
10146 // the side of assuming such calls to be made regardless of whether they
10147 // actually happen.
10148 // Note that a move constructor is not implicitly declared when there are
10149 // virtual bases, but it can still be user-declared and explicitly defaulted.
Aaron Ballman574705e2014-03-13 15:41:46 +000010150 for (const auto &Base : ClassDecl->bases()) {
10151 if (Base.isVirtual())
Sebastian Redl22653ba2011-08-30 19:58:05 +000010152 continue;
10153
10154 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010155 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010156 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000010157 0, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +000010158 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010159 }
10160
Aaron Ballman445a9392014-03-13 16:15:17 +000010161 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010162 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010163 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010164 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000010165 0, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +000010166 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010167 }
10168
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010169 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010170 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010171 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010172 if (CXXMethodDecl *MoveAssign =
10173 LookupMovingAssignment(FieldClassDecl,
10174 FieldType.getCVRQualifiers(),
10175 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +000010176 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010177 }
10178 }
10179
10180 return ExceptSpec;
10181}
10182
10183CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010184 assert(ClassDecl->needsImplicitMoveAssignment());
10185
Richard Smith8bf22e52012-11-29 01:34:07 +000010186 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
10187 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010188 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010189
Sebastian Redl22653ba2011-08-30 19:58:05 +000010190 // Note: The following rules are largely analoguous to the move
10191 // constructor rules.
10192
Sebastian Redl22653ba2011-08-30 19:58:05 +000010193 QualType ArgType = Context.getTypeDeclType(ClassDecl);
10194 QualType RetType = Context.getLValueReferenceType(ArgType);
10195 ArgType = Context.getRValueReferenceType(ArgType);
10196
Richard Smith99005e62013-05-07 03:19:20 +000010197 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10198 CXXMoveAssignment,
10199 false);
10200
Sebastian Redl22653ba2011-08-30 19:58:05 +000010201 // An implicitly-declared move assignment operator is an inline public
10202 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010203 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10204 SourceLocation ClassLoc = ClassDecl->getLocation();
10205 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000010206 CXXMethodDecl *MoveAssignment =
10207 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000010208 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
Richard Smith99005e62013-05-07 03:19:20 +000010209 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010210 MoveAssignment->setAccess(AS_public);
10211 MoveAssignment->setDefaulted();
10212 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010213
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010214 if (getLangOpts().CUDA) {
10215 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
10216 MoveAssignment,
10217 /* ConstRHS */ false,
10218 /* Diagnose */ false);
10219 }
10220
Richard Smithd3b5c9082012-07-27 04:22:15 +000010221 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010222 FunctionProtoType::ExtProtoInfo EPI =
10223 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000010224 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010225
Sebastian Redl22653ba2011-08-30 19:58:05 +000010226 // Add the parameter to the operator.
10227 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000010228 ClassLoc, ClassLoc,
10229 /*Id=*/nullptr, ArgType,
10230 /*TInfo=*/nullptr, SC_None,
10231 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010232 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010233
Richard Smith6b02d462012-12-08 08:32:28 +000010234 AddOverriddenMethods(ClassDecl, MoveAssignment);
10235
10236 MoveAssignment->setTrivial(
10237 ClassDecl->needsOverloadResolutionForMoveAssignment()
10238 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
10239 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010240
Richard Smithd951a1d2012-02-18 02:02:13 +000010241 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010242 ClassDecl->setImplicitMoveAssignmentIsDeleted();
10243 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010244 }
10245
Richard Smith6b02d462012-12-08 08:32:28 +000010246 // Note that we have added this copy-assignment operator.
10247 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
10248
Sebastian Redl22653ba2011-08-30 19:58:05 +000010249 if (Scope *S = getScopeForContext(ClassDecl))
10250 PushOnScopeChains(MoveAssignment, S, false);
10251 ClassDecl->addDecl(MoveAssignment);
10252
Sebastian Redl22653ba2011-08-30 19:58:05 +000010253 return MoveAssignment;
10254}
10255
Richard Smithb2504bd2013-11-04 04:26:14 +000010256/// Check if we're implicitly defining a move assignment operator for a class
10257/// with virtual bases. Such a move assignment might move-assign the virtual
10258/// base multiple times.
10259static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
10260 SourceLocation CurrentLocation) {
10261 assert(!Class->isDependentContext() && "should not define dependent move");
10262
10263 // Only a virtual base could get implicitly move-assigned multiple times.
10264 // Only a non-trivial move assignment can observe this. We only want to
10265 // diagnose if we implicitly define an assignment operator that assigns
10266 // two base classes, both of which move-assign the same virtual base.
10267 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10268 Class->getNumBases() < 2)
10269 return;
10270
10271 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10272 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10273 VBaseMap VBases;
10274
Aaron Ballman574705e2014-03-13 15:41:46 +000010275 for (auto &BI : Class->bases()) {
10276 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000010277 while (!Worklist.empty()) {
10278 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10279 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10280
10281 // If the base has no non-trivial move assignment operators,
10282 // we don't care about moves from it.
10283 if (!Base->hasNonTrivialMoveAssignment())
10284 continue;
10285
10286 // If there's nothing virtual here, skip it.
10287 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10288 continue;
10289
10290 // If we're not actually going to call a move assignment for this base,
10291 // or the selected move assignment is trivial, skip it.
10292 Sema::SpecialMemberOverloadResult *SMOR =
10293 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10294 /*ConstArg*/false, /*VolatileArg*/false,
10295 /*RValueThis*/true, /*ConstThis*/false,
10296 /*VolatileThis*/false);
10297 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10298 !SMOR->getMethod()->isMoveAssignmentOperator())
10299 continue;
10300
10301 if (BaseSpec->isVirtual()) {
10302 // We're going to move-assign this virtual base, and its move
10303 // assignment operator is not trivial. If this can happen for
10304 // multiple distinct direct bases of Class, diagnose it. (If it
10305 // only happens in one base, we'll diagnose it when synthesizing
10306 // that base class's move assignment operator.)
10307 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +000010308 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +000010309 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +000010310 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010311 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10312 << Class << Base;
10313 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10314 << (Base->getCanonicalDecl() ==
10315 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10316 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +000010317 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +000010318 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +000010319 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10320 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +000010321
10322 // Only diagnose each vbase once.
Craig Topperc3ec1492014-05-26 06:22:03 +000010323 Existing = nullptr;
Richard Smithb2504bd2013-11-04 04:26:14 +000010324 }
10325 } else {
10326 // Only walk over bases that have defaulted move assignment operators.
10327 // We assume that any user-provided move assignment operator handles
10328 // the multiple-moves-of-vbase case itself somehow.
10329 if (!SMOR->getMethod()->isDefaulted())
10330 continue;
10331
10332 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +000010333 for (auto &BI : Base->bases())
10334 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000010335 }
10336 }
10337 }
10338}
10339
Sebastian Redl22653ba2011-08-30 19:58:05 +000010340void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10341 CXXMethodDecl *MoveAssignOperator) {
10342 assert((MoveAssignOperator->isDefaulted() &&
10343 MoveAssignOperator->isOverloadedOperator() &&
10344 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000010345 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10346 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010347 "DefineImplicitMoveAssignment called for wrong function");
10348
10349 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10350
10351 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10352 MoveAssignOperator->setInvalidDecl();
10353 return;
10354 }
10355
Eli Friedman276dd182013-09-05 00:02:25 +000010356 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010357
Eli Friedmaneaf34142012-10-18 20:14:08 +000010358 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010359 DiagnosticErrorTrap Trap(Diags);
10360
10361 // C++0x [class.copy]p28:
10362 // The implicitly-defined or move assignment operator for a non-union class
10363 // X performs memberwise move assignment of its subobjects. The direct base
10364 // classes of X are assigned first, in the order of their declaration in the
10365 // base-specifier-list, and then the immediate non-static data members of X
10366 // are assigned, in the order in which they were declared in the class
10367 // definition.
10368
Richard Smithb2504bd2013-11-04 04:26:14 +000010369 // Issue a warning if our implicit move assignment operator will move
10370 // from a virtual base more than once.
10371 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +000010372
Sebastian Redl22653ba2011-08-30 19:58:05 +000010373 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000010374 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010375
10376 // The parameter for the "other" object, which we are move from.
10377 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10378 QualType OtherRefType = Other->getType()->
10379 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +000010380 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010381 "Bad argument type of defaulted move assignment");
10382
10383 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010384 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10385 ? MoveAssignOperator->getLocEnd()
10386 : MoveAssignOperator->getLocation();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010387
Pavel Labath58934982013-08-30 08:52:28 +000010388 // Builds a reference to the "other" object.
10389 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010390 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +000010391 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010392
Pavel Labath58934982013-08-30 08:52:28 +000010393 // Builds the "this" pointer.
10394 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010395
Sebastian Redl22653ba2011-08-30 19:58:05 +000010396 // Assign base classes.
10397 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000010398 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +000010399 // C++11 [class.copy]p28:
10400 // It is unspecified whether subobjects representing virtual base classes
10401 // are assigned more than once by the implicitly-defined copy assignment
10402 // operator.
10403 // FIXME: Do not assign to a vbase that will be assigned by some other base
10404 // class. For a move-assignment, this can result in the vbase being moved
10405 // multiple times.
10406
Sebastian Redl22653ba2011-08-30 19:58:05 +000010407 // Form the assignment:
10408 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000010409 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +000010410 if (!BaseType->isRecordType()) {
10411 Invalid = true;
10412 continue;
10413 }
10414
10415 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000010416 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010417
10418 // Construct the "from" expression, which is an implicit cast to the
10419 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010420 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010421
10422 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000010423 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010424
10425 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000010426 CastBuilder To(DerefThis,
10427 Context.getCVRQualifiedType(
10428 BaseType, MoveAssignOperator->getTypeQualifiers()),
10429 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010430
10431 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +000010432 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000010433 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010434 /*CopyingBaseSubobject=*/true,
10435 /*Copying=*/false);
10436 if (Move.isInvalid()) {
10437 Diag(CurrentLocation, diag::note_member_synthesized_at)
10438 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10439 MoveAssignOperator->setInvalidDecl();
10440 return;
10441 }
10442
10443 // Success! Record the move.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010444 Statements.push_back(Move.getAs<Expr>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010445 }
10446
Sebastian Redl22653ba2011-08-30 19:58:05 +000010447 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010448 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +000010449 if (Field->isUnnamedBitfield())
10450 continue;
10451
Eli Friedmanc9817fd2013-06-07 01:48:56 +000010452 if (Field->isInvalidDecl()) {
10453 Invalid = true;
10454 continue;
10455 }
10456
Sebastian Redl22653ba2011-08-30 19:58:05 +000010457 // Check for members of reference type; we can't move those.
10458 if (Field->getType()->isReferenceType()) {
10459 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10460 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10461 Diag(Field->getLocation(), diag::note_declared_at);
10462 Diag(CurrentLocation, diag::note_member_synthesized_at)
10463 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10464 Invalid = true;
10465 continue;
10466 }
10467
10468 // Check for members of const-qualified, non-class type.
10469 QualType BaseType = Context.getBaseElementType(Field->getType());
10470 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10471 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10472 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10473 Diag(Field->getLocation(), diag::note_declared_at);
10474 Diag(CurrentLocation, diag::note_member_synthesized_at)
10475 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10476 Invalid = true;
10477 continue;
10478 }
10479
10480 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000010481 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10482 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010483
10484 QualType FieldType = Field->getType().getNonReferenceType();
10485 if (FieldType->isIncompleteArrayType()) {
10486 assert(ClassDecl->hasFlexibleArrayMember() &&
10487 "Incomplete array type is not valid");
10488 continue;
10489 }
10490
10491 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010492 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10493 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010494 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010495 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000010496 MemberBuilder From(MoveOther, OtherRefType,
10497 /*IsArrow=*/false, MemberLookup);
10498 MemberBuilder To(This, getCurrentThisType(),
10499 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010500
Pavel Labath58934982013-08-30 08:52:28 +000010501 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +000010502 "Member reference with rvalue base must be rvalue except for reference "
10503 "members, which aren't allowed for move assignment.");
10504
Sebastian Redl22653ba2011-08-30 19:58:05 +000010505 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000010506 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000010507 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000010508 /*CopyingBaseSubobject=*/false,
10509 /*Copying=*/false);
10510 if (Move.isInvalid()) {
10511 Diag(CurrentLocation, diag::note_member_synthesized_at)
10512 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10513 MoveAssignOperator->setInvalidDecl();
10514 return;
10515 }
Richard Smith11d19592012-11-12 23:33:00 +000010516
Sebastian Redl22653ba2011-08-30 19:58:05 +000010517 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010518 Statements.push_back(Move.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010519 }
10520
10521 if (!Invalid) {
10522 // Add a "return *this;"
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010523 ExprResult ThisObj =
10524 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10525
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000010526 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010527 if (Return.isInvalid())
10528 Invalid = true;
10529 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010530 Statements.push_back(Return.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010531
10532 if (Trap.hasErrorOccurred()) {
10533 Diag(CurrentLocation, diag::note_member_synthesized_at)
10534 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10535 Invalid = true;
10536 }
10537 }
10538 }
10539
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010540 // The exception specification is needed because we are defining the
10541 // function.
10542 ResolveExceptionSpec(CurrentLocation,
10543 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
10544
Sebastian Redl22653ba2011-08-30 19:58:05 +000010545 if (Invalid) {
10546 MoveAssignOperator->setInvalidDecl();
10547 return;
10548 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010549
10550 StmtResult Body;
10551 {
10552 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010553 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010554 /*isStmtExpr=*/false);
10555 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10556 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010557 MoveAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010558
10559 if (ASTMutationListener *L = getASTMutationListener()) {
10560 L->CompletedImplicitDefinition(MoveAssignOperator);
10561 }
10562}
10563
Richard Smithd3b5c9082012-07-27 04:22:15 +000010564Sema::ImplicitExceptionSpecification
10565Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10566 CXXRecordDecl *ClassDecl = MD->getParent();
10567
10568 ImplicitExceptionSpecification ExceptSpec(*this);
10569 if (ClassDecl->isInvalidDecl())
10570 return ExceptSpec;
10571
10572 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000010573 assert(T->getNumParams() >= 1 && "not a copy ctor");
10574 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010575
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010576 // C++ [except.spec]p14:
10577 // An implicitly declared special member function (Clause 12) shall have an
10578 // exception-specification. [...]
Aaron Ballman574705e2014-03-13 15:41:46 +000010579 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010580 // Virtual bases are handled below.
Aaron Ballman574705e2014-03-13 15:41:46 +000010581 if (Base.isVirtual())
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010582 continue;
10583
Douglas Gregora6d69502010-07-02 23:41:54 +000010584 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010585 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010586 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010587 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman574705e2014-03-13 15:41:46 +000010588 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010589 }
Aaron Ballman445a9392014-03-13 16:15:17 +000010590 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregora6d69502010-07-02 23:41:54 +000010591 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010592 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000010593 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000010594 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman445a9392014-03-13 16:15:17 +000010595 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010596 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010597 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010598 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000010599 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10600 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000010601 LookupCopyingConstructor(FieldClassDecl,
10602 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000010603 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000010604 }
10605 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010606
Richard Smithd3b5c9082012-07-27 04:22:15 +000010607 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000010608}
10609
10610CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10611 CXXRecordDecl *ClassDecl) {
10612 // C++ [class.copy]p4:
10613 // If the class definition does not explicitly declare a copy
10614 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000010615 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000010616
Richard Smith8bf22e52012-11-29 01:34:07 +000010617 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10618 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010619 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010620
Alexis Hunt913820d2011-05-13 06:10:58 +000010621 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10622 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000010623 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000010624 if (Const)
10625 ArgType = ArgType.withConst();
10626 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000010627
Richard Smithb5800092012-06-10 05:43:50 +000010628 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10629 CXXCopyConstructor,
10630 Const);
10631
Douglas Gregor54be3392010-07-01 17:57:27 +000010632 DeclarationName Name
10633 = Context.DeclarationNames.getCXXConstructorName(
10634 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010635 SourceLocation ClassLoc = ClassDecl->getLocation();
10636 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000010637
10638 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010639 // member of its class.
10640 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010641 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000010642 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010643 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000010644 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000010645 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010646
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010647 if (getLangOpts().CUDA) {
10648 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
10649 CopyConstructor,
10650 /* ConstRHS */ Const,
10651 /* Diagnose */ false);
10652 }
10653
Richard Smithd3b5c9082012-07-27 04:22:15 +000010654 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010655 FunctionProtoType::ExtProtoInfo EPI =
10656 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010657 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010658 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010659
Douglas Gregor54be3392010-07-01 17:57:27 +000010660 // Add the parameter to the constructor.
10661 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000010662 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010663 /*IdentifierInfo=*/nullptr,
10664 ArgType, /*TInfo=*/nullptr,
10665 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010666 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000010667
Richard Smith6b02d462012-12-08 08:32:28 +000010668 CopyConstructor->setTrivial(
10669 ClassDecl->needsOverloadResolutionForCopyConstructor()
10670 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10671 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000010672
Richard Smith852265f2012-03-30 20:53:28 +000010673 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smithb4d2a152013-04-02 19:38:47 +000010674 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith852265f2012-03-30 20:53:28 +000010675
Richard Smith6b02d462012-12-08 08:32:28 +000010676 // Note that we have declared this constructor.
10677 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10678
10679 if (Scope *S = getScopeForContext(ClassDecl))
10680 PushOnScopeChains(CopyConstructor, S, false);
10681 ClassDecl->addDecl(CopyConstructor);
10682
Douglas Gregor54be3392010-07-01 17:57:27 +000010683 return CopyConstructor;
10684}
10685
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010686void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000010687 CXXConstructorDecl *CopyConstructor) {
10688 assert((CopyConstructor->isDefaulted() &&
10689 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010690 !CopyConstructor->doesThisDeclarationHaveABody() &&
10691 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010692 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010693
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000010694 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010695 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010696
Richard Smithd577fbb2013-06-13 03:23:42 +000010697 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000010698 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000010699 // deprecated if the class has a user-declared copy assignment operator
10700 // or a user-declared destructor.
10701 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10702 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10703
Eli Friedmaneaf34142012-10-18 20:14:08 +000010704 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010705 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010706
David Blaikie3fc2f912013-01-17 05:26:25 +000010707 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010708 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000010709 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000010710 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000010711 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000010712 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010713 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10714 ? CopyConstructor->getLocEnd()
10715 : CopyConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010716 Sema::CompoundScopeRAII CompoundScope(*this);
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010717 CopyConstructor->setBody(
10718 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000010719 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010720
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010721 // The exception specification is needed because we are defining the
10722 // function.
10723 ResolveExceptionSpec(CurrentLocation,
10724 CopyConstructor->getType()->castAs<FunctionProtoType>());
10725
Eli Friedman276dd182013-09-05 00:02:25 +000010726 CopyConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000010727 MarkVTableUsed(CurrentLocation, ClassDecl);
10728
Sebastian Redlab238a72011-04-24 16:28:06 +000010729 if (ASTMutationListener *L = getASTMutationListener()) {
10730 L->CompletedImplicitDefinition(CopyConstructor);
10731 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010732}
10733
Sebastian Redl22653ba2011-08-30 19:58:05 +000010734Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010735Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10736 CXXRecordDecl *ClassDecl = MD->getParent();
10737
Sebastian Redl22653ba2011-08-30 19:58:05 +000010738 // C++ [except.spec]p14:
10739 // An implicitly declared special member function (Clause 12) shall have an
10740 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000010741 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010742 if (ClassDecl->isInvalidDecl())
10743 return ExceptSpec;
10744
10745 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000010746 for (const auto &B : ClassDecl->bases()) {
10747 if (B.isVirtual()) // Handled below.
Sebastian Redl22653ba2011-08-30 19:58:05 +000010748 continue;
10749
Aaron Ballman574705e2014-03-13 15:41:46 +000010750 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010751 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010752 CXXConstructorDecl *Constructor =
10753 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010754 // If this is a deleted function, add it anyway. This might be conformant
10755 // with the standard. This might not. I'm not sure. It might not matter.
10756 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +000010757 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010758 }
10759 }
10760
10761 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000010762 for (const auto &B : ClassDecl->vbases()) {
10763 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010764 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000010765 CXXConstructorDecl *Constructor =
10766 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010767 // If this is a deleted function, add it anyway. This might be conformant
10768 // with the standard. This might not. I'm not sure. It might not matter.
10769 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000010770 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010771 }
10772 }
10773
10774 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010775 for (const auto *F : ClassDecl->fields()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000010776 QualType FieldType = Context.getBaseElementType(F->getType());
10777 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10778 CXXConstructorDecl *Constructor =
10779 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010780 // If this is a deleted function, add it anyway. This might be conformant
10781 // with the standard. This might not. I'm not sure. It might not matter.
10782 // In particular, the problem is that this function never gets called. It
10783 // might just be ill-formed because this function attempts to refer to
10784 // a deleted function here.
10785 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010786 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010787 }
10788 }
10789
10790 return ExceptSpec;
10791}
10792
10793CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10794 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000010795 assert(ClassDecl->needsImplicitMoveConstructor());
10796
Richard Smith8bf22e52012-11-29 01:34:07 +000010797 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10798 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010799 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010800
Sebastian Redl22653ba2011-08-30 19:58:05 +000010801 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10802 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010803
Richard Smithb5800092012-06-10 05:43:50 +000010804 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10805 CXXMoveConstructor,
10806 false);
10807
Sebastian Redl22653ba2011-08-30 19:58:05 +000010808 DeclarationName Name
10809 = Context.DeclarationNames.getCXXConstructorName(
10810 Context.getCanonicalType(ClassType));
10811 SourceLocation ClassLoc = ClassDecl->getLocation();
10812 DeclarationNameInfo NameInfo(Name, ClassLoc);
10813
Richard Smith99005e62013-05-07 03:19:20 +000010814 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000010815 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000010816 // member of its class.
10817 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010818 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000010819 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000010820 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010821 MoveConstructor->setAccess(AS_public);
10822 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000010823
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010824 if (getLangOpts().CUDA) {
10825 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
10826 MoveConstructor,
10827 /* ConstRHS */ false,
10828 /* Diagnose */ false);
10829 }
10830
Richard Smithd3b5c9082012-07-27 04:22:15 +000010831 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010832 FunctionProtoType::ExtProtoInfo EPI =
10833 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000010834 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000010835 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010836
Sebastian Redl22653ba2011-08-30 19:58:05 +000010837 // Add the parameter to the constructor.
10838 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10839 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000010840 /*IdentifierInfo=*/nullptr,
10841 ArgType, /*TInfo=*/nullptr,
10842 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010843 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010844
Richard Smith6b02d462012-12-08 08:32:28 +000010845 MoveConstructor->setTrivial(
10846 ClassDecl->needsOverloadResolutionForMoveConstructor()
10847 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10848 : ClassDecl->hasTrivialMoveConstructor());
10849
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000010850 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000010851 ClassDecl->setImplicitMoveConstructorIsDeleted();
10852 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010853 }
10854
10855 // Note that we have declared this constructor.
10856 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10857
10858 if (Scope *S = getScopeForContext(ClassDecl))
10859 PushOnScopeChains(MoveConstructor, S, false);
10860 ClassDecl->addDecl(MoveConstructor);
10861
10862 return MoveConstructor;
10863}
10864
10865void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10866 CXXConstructorDecl *MoveConstructor) {
10867 assert((MoveConstructor->isDefaulted() &&
10868 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010869 !MoveConstructor->doesThisDeclarationHaveABody() &&
10870 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000010871 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10872
10873 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10874 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10875
Eli Friedmaneaf34142012-10-18 20:14:08 +000010876 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010877 DiagnosticErrorTrap Trap(Diags);
10878
David Blaikie3fc2f912013-01-17 05:26:25 +000010879 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000010880 Trap.hasErrorOccurred()) {
10881 Diag(CurrentLocation, diag::note_member_synthesized_at)
10882 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10883 MoveConstructor->setInvalidDecl();
10884 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010885 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
10886 ? MoveConstructor->getLocEnd()
10887 : MoveConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000010888 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000010889 MoveConstructor->setBody(ActOnCompoundStmt(
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010890 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000010891 }
10892
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010893 // The exception specification is needed because we are defining the
10894 // function.
10895 ResolveExceptionSpec(CurrentLocation,
10896 MoveConstructor->getType()->castAs<FunctionProtoType>());
10897
Eli Friedman276dd182013-09-05 00:02:25 +000010898 MoveConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000010899 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010900
10901 if (ASTMutationListener *L = getASTMutationListener()) {
10902 L->CompletedImplicitDefinition(MoveConstructor);
10903 }
10904}
10905
Douglas Gregor74f7d502012-02-15 19:33:52 +000010906bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000010907 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000010908}
Douglas Gregord3b672c2012-02-16 01:06:16 +000010909
10910void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000010911 SourceLocation CurrentLocation,
10912 CXXConversionDecl *Conv) {
10913 CXXRecordDecl *Lambda = Conv->getParent();
10914 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10915 // If we are defining a specialization of a conversion to function-ptr
10916 // cache the deduced template arguments for this specialization
10917 // so that we can use them to retrieve the corresponding call-operator
10918 // and static-invoker.
Craig Topperc3ec1492014-05-26 06:22:03 +000010919 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
10920
Faisal Vali571df122013-09-29 08:45:24 +000010921 // Retrieve the corresponding call-operator specialization.
10922 if (Lambda->isGenericLambda()) {
10923 assert(Conv->isFunctionTemplateSpecialization());
10924 FunctionTemplateDecl *CallOpTemplate =
10925 CallOp->getDescribedFunctionTemplate();
10926 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
Craig Topperc3ec1492014-05-26 06:22:03 +000010927 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000010928 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000010929 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000010930 InsertPos);
10931 assert(CallOpSpec &&
10932 "Conversion operator must have a corresponding call operator");
10933 CallOp = cast<CXXMethodDecl>(CallOpSpec);
10934 }
10935 // Mark the call operator referenced (and add to pending instantiations
10936 // if necessary).
10937 // For both the conversion and static-invoker template specializations
10938 // we construct their body's in this function, so no need to add them
10939 // to the PendingInstantiations.
10940 MarkFunctionReferenced(CurrentLocation, CallOp);
10941
Eli Friedmaneaf34142012-10-18 20:14:08 +000010942 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010943 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000010944
Alp Tokerf6a24ce2013-12-05 16:25:25 +000010945 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000010946 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10947 // ... and get the corresponding specialization for a generic lambda.
10948 if (Lambda->isGenericLambda()) {
10949 assert(DeducedTemplateArgs &&
10950 "Must have deduced template arguments from Conversion Operator");
10951 FunctionTemplateDecl *InvokeTemplate =
10952 Invoker->getDescribedFunctionTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +000010953 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000010954 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000010955 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000010956 InsertPos);
10957 assert(InvokeSpec &&
10958 "Must have a corresponding static invoker specialization");
10959 Invoker = cast<CXXMethodDecl>(InvokeSpec);
10960 }
10961 // Construct the body of the conversion function { return __invoke; }.
10962 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010963 VK_LValue, Conv->getLocation()).get();
Faisal Vali571df122013-09-29 08:45:24 +000010964 assert(FunctionRef && "Can't refer to __invoke function?");
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010965 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
Faisal Vali571df122013-09-29 08:45:24 +000010966 Conv->setBody(new (Context) CompoundStmt(Context, Return,
10967 Conv->getLocation(),
10968 Conv->getLocation()));
10969
10970 Conv->markUsed(Context);
10971 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000010972
Faisal Vali571df122013-09-29 08:45:24 +000010973 // Fill in the __invoke function with a dummy implementation. IR generation
10974 // will fill in the actual details.
10975 Invoker->markUsed(Context);
10976 Invoker->setReferenced();
10977 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10978
Douglas Gregord3b672c2012-02-16 01:06:16 +000010979 if (ASTMutationListener *L = getASTMutationListener()) {
10980 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000010981 L->CompletedImplicitDefinition(Invoker);
10982 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000010983}
10984
Faisal Vali571df122013-09-29 08:45:24 +000010985
10986
Douglas Gregord3b672c2012-02-16 01:06:16 +000010987void Sema::DefineImplicitLambdaToBlockPointerConversion(
10988 SourceLocation CurrentLocation,
10989 CXXConversionDecl *Conv)
10990{
Faisal Vali850da1a2013-09-29 17:08:32 +000010991 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000010992
Eli Friedman276dd182013-09-05 00:02:25 +000010993 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010994
Eli Friedmaneaf34142012-10-18 20:14:08 +000010995 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010996 DiagnosticErrorTrap Trap(Diags);
10997
Douglas Gregored90df32012-02-22 05:02:47 +000010998 // Copy-initialize the lambda object as needed to capture it.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010999 Expr *This = ActOnCXXThis(CurrentLocation).get();
11000 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
Douglas Gregord3b672c2012-02-16 01:06:16 +000011001
Eli Friedman98b01ed2012-03-01 04:01:32 +000011002 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
11003 Conv->getLocation(),
11004 Conv, DerefThis);
11005
11006 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
11007 // behavior. Note that only the general conversion function does this
11008 // (since it's unusable otherwise); in the case where we inline the
11009 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011010 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000011011 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
11012 CK_CopyAndAutoreleaseBlockObject,
Craig Topperc3ec1492014-05-26 06:22:03 +000011013 BuildBlock.get(), nullptr, VK_RValue);
Eli Friedman98b01ed2012-03-01 04:01:32 +000011014
11015 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000011016 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000011017 Conv->setInvalidDecl();
11018 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000011019 }
Douglas Gregored90df32012-02-22 05:02:47 +000011020
Douglas Gregored90df32012-02-22 05:02:47 +000011021 // Create the return statement that returns the block from the conversion
11022 // function.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000011023 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000011024 if (Return.isInvalid()) {
11025 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11026 Conv->setInvalidDecl();
11027 return;
11028 }
11029
11030 // Set the body of the conversion function.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011031 Stmt *ReturnS = Return.get();
Nico Webera2a0eb92012-12-29 20:03:39 +000011032 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000011033 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000011034 Conv->getLocation()));
11035
Douglas Gregored90df32012-02-22 05:02:47 +000011036 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000011037 if (ASTMutationListener *L = getASTMutationListener()) {
11038 L->CompletedImplicitDefinition(Conv);
11039 }
11040}
11041
Douglas Gregord2f70072012-03-10 06:53:13 +000011042/// \brief Determine whether the given list arguments contains exactly one
11043/// "real" (non-default) argument.
11044static bool hasOneRealArgument(MultiExprArg Args) {
11045 switch (Args.size()) {
11046 case 0:
11047 return false;
11048
11049 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011050 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000011051 return false;
11052
11053 // fall through
11054 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011055 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000011056 }
11057
11058 return false;
11059}
11060
John McCalldadc5752010-08-24 06:29:42 +000011061ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000011062Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +000011063 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000011064 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011065 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000011066 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011067 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011068 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000011069 unsigned ConstructKind,
11070 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000011071 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000011072
Douglas Gregor45cf7e32010-04-02 18:24:57 +000011073 // C++0x [class.copy]p34:
11074 // When certain criteria are met, an implementation is allowed to
11075 // omit the copy/move construction of a class object, even if the
11076 // copy/move constructor and/or destructor for the object have
11077 // side effects. [...]
11078 // - when a temporary class object that has not been bound to a
11079 // reference (12.2) would be copied/moved to a class object
11080 // with the same cv-unqualified type, the copy/move operation
11081 // can be omitted by constructing the temporary object
11082 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +000011083 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregord2f70072012-03-10 06:53:13 +000011084 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011085 Expr *SubExpr = ExprArgs[0];
John McCall7a626f62010-09-15 10:14:12 +000011086 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +000011087 }
Mike Stump11289f42009-09-09 15:08:12 +000011088
11089 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011090 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011091 IsListInitialization,
11092 IsStdInitListInitialization, RequiresZeroInit,
Richard Smithd59b8322012-12-19 01:39:02 +000011093 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000011094}
11095
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000011096/// BuildCXXConstructExpr - Creates a complete call to a constructor,
11097/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +000011098ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000011099Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11100 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000011101 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011102 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000011103 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011104 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011105 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000011106 unsigned ConstructKind,
11107 SourceRange ParenRange) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000011108 MarkFunctionReferenced(ConstructLoc, Constructor);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011109 return CXXConstructExpr::Create(
11110 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
Richard Smithf8adcdc2014-07-17 05:12:35 +000011111 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
11112 RequiresZeroInit,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011113 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
11114 ParenRange);
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000011115}
11116
John McCall03c48482010-02-02 09:10:11 +000011117void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000011118 if (VD->isInvalidDecl()) return;
11119
John McCall03c48482010-02-02 09:10:11 +000011120 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000011121 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000011122 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000011123 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000011124
Chandler Carruth86d17d32011-03-27 21:26:48 +000011125 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000011126 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000011127 CheckDestructorAccess(VD->getLocation(), Destructor,
11128 PDiag(diag::err_access_dtor_var)
11129 << VD->getDeclName()
11130 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000011131 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000011132
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000011133 if (Destructor->isTrivial()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000011134 if (!VD->hasGlobalStorage()) return;
11135
11136 // Emit warning for non-trivial dtor in global scope (a real global,
11137 // class-static, function-static).
11138 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
11139
11140 // TODO: this should be re-enabled for static locals by !CXAAtExit
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000011141 if (!VD->isStaticLocal())
Chandler Carruth86d17d32011-03-27 21:26:48 +000011142 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000011143}
11144
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011145/// \brief Given a constructor and the set of arguments provided for the
11146/// constructor, convert the arguments and add any required default arguments
11147/// to form a proper call to this constructor.
11148///
11149/// \returns true if an error occurred, false otherwise.
11150bool
11151Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
11152 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000011153 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000011154 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000011155 bool AllowExplicit,
11156 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011157 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
11158 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000011159 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011160
11161 const FunctionProtoType *Proto
11162 = Constructor->getType()->getAs<FunctionProtoType>();
11163 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011164 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000011165
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011166 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011167 if (NumArgs < NumParams)
11168 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011169 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000011170 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011171
11172 VariadicCallType CallType =
11173 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011174 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011175 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011176 Proto, 0,
11177 llvm::makeArrayRef(Args, NumArgs),
11178 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000011179 CallType, AllowExplicit,
11180 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000011181 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000011182
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011183 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011184
Dmitri Gribenko765396f2013-01-13 20:46:02 +000011185 CheckConstructorCall(Constructor,
Craig Topper8c2a2a02014-08-30 16:55:39 +000011186 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000011187 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011188
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000011189 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000011190}
11191
Anders Carlssone363c8e2009-12-12 00:32:00 +000011192static inline bool
11193CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
11194 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000011195 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000011196 if (isa<NamespaceDecl>(DC)) {
11197 return SemaRef.Diag(FnDecl->getLocation(),
11198 diag::err_operator_new_delete_declared_in_namespace)
11199 << FnDecl->getDeclName();
11200 }
11201
11202 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000011203 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000011204 return SemaRef.Diag(FnDecl->getLocation(),
11205 diag::err_operator_new_delete_declared_static)
11206 << FnDecl->getDeclName();
11207 }
11208
Anders Carlsson60659a82009-12-12 02:43:16 +000011209 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000011210}
11211
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011212static inline bool
11213CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
11214 CanQualType ExpectedResultType,
11215 CanQualType ExpectedFirstParamType,
11216 unsigned DependentParamTypeDiag,
11217 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000011218 QualType ResultType =
11219 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011220
11221 // Check that the result type is not dependent.
11222 if (ResultType->isDependentType())
11223 return SemaRef.Diag(FnDecl->getLocation(),
11224 diag::err_operator_new_delete_dependent_result_type)
11225 << FnDecl->getDeclName() << ExpectedResultType;
11226
11227 // Check that the result type is what we expect.
11228 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
11229 return SemaRef.Diag(FnDecl->getLocation(),
11230 diag::err_operator_new_delete_invalid_result_type)
11231 << FnDecl->getDeclName() << ExpectedResultType;
11232
11233 // A function template must have at least 2 parameters.
11234 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
11235 return SemaRef.Diag(FnDecl->getLocation(),
11236 diag::err_operator_new_delete_template_too_few_parameters)
11237 << FnDecl->getDeclName();
11238
11239 // The function decl must have at least 1 parameter.
11240 if (FnDecl->getNumParams() == 0)
11241 return SemaRef.Diag(FnDecl->getLocation(),
11242 diag::err_operator_new_delete_too_few_parameters)
11243 << FnDecl->getDeclName();
11244
Sylvestre Ledru830885c2012-07-23 08:59:39 +000011245 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011246 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
11247 if (FirstParamType->isDependentType())
11248 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
11249 << FnDecl->getDeclName() << ExpectedFirstParamType;
11250
11251 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000011252 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011253 ExpectedFirstParamType)
11254 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
11255 << FnDecl->getDeclName() << ExpectedFirstParamType;
11256
11257 return false;
11258}
11259
Anders Carlsson12308f42009-12-11 23:23:22 +000011260static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011261CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000011262 // C++ [basic.stc.dynamic.allocation]p1:
11263 // A program is ill-formed if an allocation function is declared in a
11264 // namespace scope other than global scope or declared static in global
11265 // scope.
11266 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11267 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011268
11269 CanQualType SizeTy =
11270 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11271
11272 // C++ [basic.stc.dynamic.allocation]p1:
11273 // The return type shall be void*. The first parameter shall have type
11274 // std::size_t.
11275 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
11276 SizeTy,
11277 diag::err_operator_new_dependent_param_type,
11278 diag::err_operator_new_param_type))
11279 return true;
11280
11281 // C++ [basic.stc.dynamic.allocation]p1:
11282 // The first parameter shall not have an associated default argument.
11283 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000011284 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011285 diag::err_operator_new_default_arg)
11286 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11287
11288 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000011289}
11290
11291static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000011292CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000011293 // C++ [basic.stc.dynamic.deallocation]p1:
11294 // A program is ill-formed if deallocation functions are declared in a
11295 // namespace scope other than global scope or declared static in global
11296 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000011297 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11298 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000011299
11300 // C++ [basic.stc.dynamic.deallocation]p2:
11301 // Each deallocation function shall return void and its first parameter
11302 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000011303 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
11304 SemaRef.Context.VoidPtrTy,
11305 diag::err_operator_delete_dependent_param_type,
11306 diag::err_operator_delete_param_type))
11307 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000011308
Anders Carlsson12308f42009-12-11 23:23:22 +000011309 return false;
11310}
11311
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011312/// CheckOverloadedOperatorDeclaration - Check whether the declaration
11313/// of this overloaded operator is well-formed. If so, returns false;
11314/// otherwise, emits appropriate diagnostics and returns true.
11315bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000011316 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011317 "Expected an overloaded operator declaration");
11318
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011319 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11320
Mike Stump11289f42009-09-09 15:08:12 +000011321 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011322 // The allocation and deallocation functions, operator new,
11323 // operator new[], operator delete and operator delete[], are
11324 // described completely in 3.7.3. The attributes and restrictions
11325 // found in the rest of this subclause do not apply to them unless
11326 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000011327 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000011328 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000011329
Anders Carlsson22f443f2009-12-12 00:26:23 +000011330 if (Op == OO_New || Op == OO_Array_New)
11331 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011332
11333 // C++ [over.oper]p6:
11334 // An operator function shall either be a non-static member
11335 // function or be a non-member function and have at least one
11336 // parameter whose type is a class, a reference to a class, an
11337 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000011338 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11339 if (MethodDecl->isStatic())
11340 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011341 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011342 } else {
11343 bool ClassOrEnumParam = false;
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011344 for (auto Param : FnDecl->params()) {
11345 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000011346 if (ParamType->isDependentType() || ParamType->isRecordType() ||
11347 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011348 ClassOrEnumParam = true;
11349 break;
11350 }
11351 }
11352
Douglas Gregord69246b2008-11-17 16:14:12 +000011353 if (!ClassOrEnumParam)
11354 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011355 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011356 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011357 }
11358
11359 // C++ [over.oper]p8:
11360 // An operator function cannot have default arguments (8.3.6),
11361 // except where explicitly stated below.
11362 //
Mike Stump11289f42009-09-09 15:08:12 +000011363 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011364 // (C++ [over.call]p1).
11365 if (Op != OO_Call) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011366 for (auto Param : FnDecl->params()) {
11367 if (Param->hasDefaultArg())
11368 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000011369 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011370 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011371 }
11372 }
11373
Douglas Gregor6cf08062008-11-10 13:38:07 +000011374 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11375 { false, false, false }
11376#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11377 , { Unary, Binary, MemberOnly }
11378#include "clang/Basic/OperatorKinds.def"
11379 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011380
Douglas Gregor6cf08062008-11-10 13:38:07 +000011381 bool CanBeUnaryOperator = OperatorUses[Op][0];
11382 bool CanBeBinaryOperator = OperatorUses[Op][1];
11383 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011384
11385 // C++ [over.oper]p8:
11386 // [...] Operator functions cannot have more or fewer parameters
11387 // than the number required for the corresponding operator, as
11388 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000011389 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000011390 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011391 if (Op != OO_Call &&
11392 ((NumParams == 1 && !CanBeUnaryOperator) ||
11393 (NumParams == 2 && !CanBeBinaryOperator) ||
11394 (NumParams < 1) || (NumParams > 2))) {
11395 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011396 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000011397 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011398 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000011399 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011400 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011401 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000011402 assert(CanBeBinaryOperator &&
11403 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011404 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000011405 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011406
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000011407 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011408 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011409 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000011410
Douglas Gregord69246b2008-11-17 16:14:12 +000011411 // Overloaded operators other than operator() cannot be variadic.
11412 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000011413 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000011414 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011415 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011416 }
11417
11418 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000011419 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11420 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000011421 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000011422 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011423 }
11424
11425 // C++ [over.inc]p1:
11426 // The user-defined function called operator++ implements the
11427 // prefix and postfix ++ operator. If this function is a member
11428 // function with no parameters, or a non-member function with one
11429 // parameter of class or enumeration type, it defines the prefix
11430 // increment operator ++ for objects of that type. If the function
11431 // is a member function with one parameter (which shall be of type
11432 // int) or a non-member function with two parameters (the second
11433 // of which shall be of type int), it defines the postfix
11434 // increment operator ++ for objects of that type.
11435 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11436 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000011437 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011438
Richard Smith538b52a2014-01-30 22:24:05 +000011439 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11440 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000011441 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000011442 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000011443 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011444 }
11445
Douglas Gregord69246b2008-11-17 16:14:12 +000011446 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000011447}
Chris Lattner3b024a32008-12-17 07:09:26 +000011448
Alexis Huntc88db062010-01-13 09:01:02 +000011449/// CheckLiteralOperatorDeclaration - Check whether the declaration
11450/// of this literal operator function is well-formed. If so, returns
11451/// false; otherwise, emits appropriate diagnostics and returns true.
11452bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000011453 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000011454 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11455 << FnDecl->getDeclName();
11456 return true;
11457 }
11458
Richard Smith72eebee2012-03-04 09:41:16 +000011459 if (FnDecl->isExternC()) {
11460 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11461 return true;
11462 }
11463
Alexis Huntc88db062010-01-13 09:01:02 +000011464 bool Valid = false;
11465
Richard Smithbcc22fc2012-03-09 08:00:36 +000011466 // This might be the definition of a literal operator template.
11467 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11468 // This might be a specialization of a literal operator template.
11469 if (!TpDecl)
11470 TpDecl = FnDecl->getPrimaryTemplate();
11471
Richard Smithb8b41d32013-10-07 19:57:58 +000011472 // template <char...> type operator "" name() and
11473 // template <class T, T...> type operator "" name() are the only valid
11474 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000011475 if (TpDecl) {
Richard Smith72eebee2012-03-04 09:41:16 +000011476 if (FnDecl->param_size() == 0) {
Richard Smithb8b41d32013-10-07 19:57:58 +000011477 // Must have one or two template parameters
Alexis Hunt7dd26172010-04-07 23:11:06 +000011478 TemplateParameterList *Params = TpDecl->getTemplateParameters();
11479 if (Params->size() == 1) {
11480 NonTypeTemplateParmDecl *PmDecl =
Richard Smithed943022012-08-03 21:14:57 +000011481 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +000011482
Alexis Hunt7dd26172010-04-07 23:11:06 +000011483 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +000011484 if (PmDecl && PmDecl->isTemplateParameterPack() &&
11485 Context.hasSameType(PmDecl->getType(), Context.CharTy))
11486 Valid = true;
Richard Smithb8b41d32013-10-07 19:57:58 +000011487 } else if (Params->size() == 2) {
11488 TemplateTypeParmDecl *PmType =
11489 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11490 NonTypeTemplateParmDecl *PmArgs =
11491 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11492
11493 // The second template parameter must be a parameter pack with the
11494 // first template parameter as its type.
11495 if (PmType && PmArgs &&
11496 !PmType->isTemplateParameterPack() &&
11497 PmArgs->isTemplateParameterPack()) {
11498 const TemplateTypeParmType *TArgs =
11499 PmArgs->getType()->getAs<TemplateTypeParmType>();
11500 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11501 TArgs->getIndex() == PmType->getIndex()) {
11502 Valid = true;
11503 if (ActiveTemplateInstantiations.empty())
11504 Diag(FnDecl->getLocation(),
11505 diag::ext_string_literal_operator_template);
11506 }
11507 }
Alexis Hunt7dd26172010-04-07 23:11:06 +000011508 }
11509 }
Richard Smith72eebee2012-03-04 09:41:16 +000011510 } else if (FnDecl->param_size()) {
Alexis Huntc88db062010-01-13 09:01:02 +000011511 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +000011512 FunctionDecl::param_iterator Param = FnDecl->param_begin();
11513
Richard Smith72eebee2012-03-04 09:41:16 +000011514 QualType T = (*Param)->getType().getUnqualifiedType();
Alexis Huntc88db062010-01-13 09:01:02 +000011515
Alexis Hunt079a6f72010-04-07 22:57:35 +000011516 // unsigned long long int, long double, and any character type are allowed
11517 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +000011518 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11519 Context.hasSameType(T, Context.LongDoubleTy) ||
11520 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011521 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011522 Context.hasSameType(T, Context.Char16Ty) ||
11523 Context.hasSameType(T, Context.Char32Ty)) {
11524 if (++Param == FnDecl->param_end())
11525 Valid = true;
11526 goto FinishedParams;
11527 }
11528
Alexis Hunt079a6f72010-04-07 22:57:35 +000011529 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +000011530 const PointerType *PT = T->getAs<PointerType>();
11531 if (!PT)
11532 goto FinishedParams;
11533 T = PT->getPointeeType();
Richard Smith72eebee2012-03-04 09:41:16 +000011534 if (!T.isConstQualified() || T.isVolatileQualified())
Alexis Huntc88db062010-01-13 09:01:02 +000011535 goto FinishedParams;
11536 T = T.getUnqualifiedType();
11537
11538 // Move on to the second parameter;
11539 ++Param;
11540
11541 // If there is no second parameter, the first must be a const char *
11542 if (Param == FnDecl->param_end()) {
11543 if (Context.hasSameType(T, Context.CharTy))
11544 Valid = true;
11545 goto FinishedParams;
11546 }
11547
11548 // const char *, const wchar_t*, const char16_t*, and const char32_t*
11549 // are allowed as the first parameter to a two-parameter function
11550 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg0d81e012013-05-10 10:08:40 +000011551 Context.hasSameType(T, Context.WideCharTy) ||
Alexis Huntc88db062010-01-13 09:01:02 +000011552 Context.hasSameType(T, Context.Char16Ty) ||
11553 Context.hasSameType(T, Context.Char32Ty)))
11554 goto FinishedParams;
11555
11556 // The second and final parameter must be an std::size_t
11557 T = (*Param)->getType().getUnqualifiedType();
11558 if (Context.hasSameType(T, Context.getSizeType()) &&
11559 ++Param == FnDecl->param_end())
11560 Valid = true;
11561 }
11562
11563 // FIXME: This diagnostic is absolutely terrible.
11564FinishedParams:
11565 if (!Valid) {
11566 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11567 << FnDecl->getDeclName();
11568 return true;
11569 }
11570
Richard Smith768cecc2012-03-09 08:16:22 +000011571 // A parameter-declaration-clause containing a default argument is not
11572 // equivalent to any of the permitted forms.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011573 for (auto Param : FnDecl->params()) {
11574 if (Param->hasDefaultArg()) {
11575 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000011576 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000011577 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000011578 break;
11579 }
11580 }
11581
Richard Smith0df56f42012-03-08 02:39:21 +000011582 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000011583 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11584 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000011585 // C++11 [usrlit.suffix]p1:
11586 // Literal suffix identifiers that do not start with an underscore
11587 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000011588 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11589 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000011590 }
Richard Smith0df56f42012-03-08 02:39:21 +000011591
Alexis Huntc88db062010-01-13 09:01:02 +000011592 return false;
11593}
11594
Douglas Gregor07665a62009-01-05 19:45:36 +000011595/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11596/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000011597/// the '{'. ExternLoc is the location of the 'extern', Lang is the
11598/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000011599/// the '{' brace. Otherwise, this linkage specification does not
11600/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000011601Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000011602 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000011603 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011604 StringLiteral *Lit = cast<StringLiteral>(LangStr);
11605 if (!Lit->isAscii()) {
11606 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11607 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011608 return nullptr;
Richard Smith4ee696d2014-02-17 23:25:27 +000011609 }
11610
11611 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000011612 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000011613 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000011614 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000011615 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000011616 Language = LinkageSpecDecl::lang_cxx;
11617 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000011618 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11619 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000011620 return nullptr;
Chris Lattner438e5012008-12-17 07:13:27 +000011621 }
Mike Stump11289f42009-09-09 15:08:12 +000011622
Chris Lattner438e5012008-12-17 07:13:27 +000011623 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000011624
Richard Smith4ee696d2014-02-17 23:25:27 +000011625 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11626 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000011627 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011628 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000011629 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000011630 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000011631}
11632
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000011633/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000011634/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11635/// valid, it's the position of the closing '}' brace in a linkage
11636/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000011637Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011638 Decl *LinkageSpec,
11639 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000011640 if (RBraceLoc.isValid()) {
11641 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11642 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000011643 }
Richard Smith4ee696d2014-02-17 23:25:27 +000011644 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000011645 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000011646}
11647
Michael Han84324352013-02-22 17:15:32 +000011648Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11649 AttributeList *AttrList,
11650 SourceLocation SemiLoc) {
11651 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11652 // Attribute declarations appertain to empty declaration so we handle
11653 // them here.
11654 if (AttrList)
11655 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000011656
Michael Han84324352013-02-22 17:15:32 +000011657 CurContext->addDecl(ED);
11658 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000011659}
11660
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011661/// \brief Perform semantic analysis for the variable declaration that
11662/// occurs within a C++ catch clause, returning the newly-created
11663/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000011664VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000011665 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011666 SourceLocation StartLoc,
11667 SourceLocation Loc,
11668 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011669 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011670 QualType ExDeclType = TInfo->getType();
11671
Sebastian Redl54c04d42008-12-22 19:15:10 +000011672 // Arrays and functions decay.
11673 if (ExDeclType->isArrayType())
11674 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11675 else if (ExDeclType->isFunctionType())
11676 ExDeclType = Context.getPointerType(ExDeclType);
11677
11678 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11679 // The exception-declaration shall not denote a pointer or reference to an
11680 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000011681 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000011682 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011683 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000011684 Invalid = true;
11685 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011686
Sebastian Redl54c04d42008-12-22 19:15:10 +000011687 QualType BaseType = ExDeclType;
11688 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000011689 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011690 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011691 BaseType = Ptr->getPointeeType();
11692 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011693 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000011694 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000011695 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011696 BaseType = Ref->getPointeeType();
11697 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011698 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011699 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000011700 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000011701 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000011702 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011703
Mike Stump11289f42009-09-09 15:08:12 +000011704 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011705 RequireNonAbstractType(Loc, ExDeclType,
11706 diag::err_abstract_type_in_decl,
11707 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000011708 Invalid = true;
11709
John McCall2ca705e2010-07-24 00:37:23 +000011710 // Only the non-fragile NeXT runtime currently supports C++ catches
11711 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011712 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000011713 QualType T = ExDeclType;
11714 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11715 T = RT->getPointeeType();
11716
11717 if (T->isObjCObjectType()) {
11718 Diag(Loc, diag::err_objc_object_catch);
11719 Invalid = true;
11720 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000011721 // FIXME: should this be a test for macosx-fragile specifically?
11722 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000011723 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000011724 }
11725 }
11726
Abramo Bagnaradff19302011-03-08 08:55:46 +000011727 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000011728 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000011729 ExDecl->setExceptionVariable(true);
11730
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011731 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011732 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000011733 Invalid = true;
11734
Douglas Gregor750734c2011-07-06 18:14:43 +000011735 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000011736 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000011737 // Insulate this from anything else we might currently be parsing.
11738 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11739
Douglas Gregor6de584c2010-03-05 23:38:39 +000011740 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000011741 // The object declared in an exception-declaration or, if the
11742 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000011743 // copy-initialized (8.5) from the exception object. [...]
11744 // The object is destroyed when the handler exits, after the destruction
11745 // of any automatic objects initialized within the handler.
11746 //
Nick Lewycky0f292892013-09-22 10:06:57 +000011747 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000011748 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +000011749 QualType initType = ExDeclType;
11750
11751 InitializedEntity entity =
11752 InitializedEntity::InitializeVariable(ExDecl);
11753 InitializationKind initKind =
11754 InitializationKind::CreateCopy(Loc, SourceLocation());
11755
11756 Expr *opaqueValue =
11757 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000011758 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11759 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000011760 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000011761 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000011762 else {
11763 // If the constructor used was non-trivial, set this as the
11764 // "initializer".
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011765 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000011766 if (!construct->getConstructor()->isTrivial()) {
11767 Expr *init = MaybeCreateExprWithCleanups(construct);
11768 ExDecl->setInit(init);
11769 }
11770
11771 // And make sure it's destructable.
11772 FinalizeVarWithDestructor(ExDecl, recordType);
11773 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000011774 }
11775 }
11776
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011777 if (Invalid)
11778 ExDecl->setInvalidDecl();
11779
11780 return ExDecl;
11781}
11782
11783/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11784/// handler.
John McCall48871652010-08-21 09:40:31 +000011785Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000011786 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000011787 bool Invalid = D.isInvalidType();
11788
11789 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000011790 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11791 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000011792 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11793 D.getIdentifierLoc());
11794 Invalid = true;
11795 }
11796
Sebastian Redl54c04d42008-12-22 19:15:10 +000011797 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000011798 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000011799 LookupOrdinaryName,
11800 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011801 // The scope should be freshly made just for us. There is just no way
Aaron Ballman9ef622e2014-06-02 13:10:07 +000011802 // it contains any previous declaration, except for function parameters in
11803 // a function-try-block's catch statement.
John McCall48871652010-08-21 09:40:31 +000011804 assert(!S->isDeclScope(PrevDecl));
Aaron Ballman9ef622e2014-06-02 13:10:07 +000011805 if (isDeclInScope(PrevDecl, CurContext, S)) {
11806 Diag(D.getIdentifierLoc(), diag::err_redefinition)
11807 << D.getIdentifier();
11808 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11809 Invalid = true;
11810 } else if (PrevDecl->isTemplateParameter())
Sebastian Redl54c04d42008-12-22 19:15:10 +000011811 // Maybe we will complain about the shadowed template parameter.
11812 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011813 }
11814
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011815 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000011816 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11817 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011818 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011819 }
11820
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000011821 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011822 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000011823 D.getIdentifierLoc(),
11824 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000011825 if (Invalid)
11826 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000011827
Sebastian Redl54c04d42008-12-22 19:15:10 +000011828 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000011829 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000011830 PushOnScopeChains(ExDecl, S);
11831 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011832 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000011833
Douglas Gregor758a8692009-06-17 21:51:59 +000011834 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000011835 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000011836}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011837
Abramo Bagnaraea947882011-03-08 16:41:52 +000011838Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000011839 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000011840 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000011841 SourceLocation RParenLoc) {
Richard Smith085a64f2014-06-20 19:57:12 +000011842 StringLiteral *AssertMessage =
11843 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011844
Richard Smithded9c2e2012-07-11 22:37:56 +000011845 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
Craig Topperc3ec1492014-05-26 06:22:03 +000011846 return nullptr;
Richard Smithded9c2e2012-07-11 22:37:56 +000011847
11848 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11849 AssertMessage, RParenLoc, false);
11850}
11851
11852Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11853 Expr *AssertExpr,
11854 StringLiteral *AssertMessage,
11855 SourceLocation RParenLoc,
11856 bool Failed) {
Richard Smith085a64f2014-06-20 19:57:12 +000011857 assert(AssertExpr != nullptr && "Expected non-null condition");
Richard Smithded9c2e2012-07-11 22:37:56 +000011858 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11859 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000011860 // In a static_assert-declaration, the constant-expression shall be a
11861 // constant expression that can be contextually converted to bool.
11862 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11863 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011864 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000011865
Richard Smith902ca212011-12-14 23:32:26 +000011866 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000011867 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000011868 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000011869 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000011870 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011871
Richard Smithded9c2e2012-07-11 22:37:56 +000011872 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000011873 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000011874 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith085a64f2014-06-20 19:57:12 +000011875 if (AssertMessage)
11876 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000011877 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith085a64f2014-06-20 19:57:12 +000011878 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000011879 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000011880 }
Anders Carlsson54b26982009-03-14 00:33:21 +000011881 }
Mike Stump11289f42009-09-09 15:08:12 +000011882
Abramo Bagnaraea947882011-03-08 16:41:52 +000011883 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000011884 AssertExpr, AssertMessage, RParenLoc,
11885 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000011886
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000011887 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000011888 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000011889}
Sebastian Redlf769df52009-03-24 22:27:57 +000011890
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011891/// \brief Perform semantic analysis of the given friend type declaration.
11892///
11893/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000011894FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000011895 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011896 TypeSourceInfo *TSInfo) {
11897 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11898
11899 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000011900 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011901
Richard Smithc8239732011-10-18 21:39:00 +000011902 // C++03 [class.friend]p2:
11903 // An elaborated-type-specifier shall be used in a friend declaration
11904 // for a class.*
11905 //
11906 // * The class-key of the elaborated-type-specifier is required.
11907 if (!ActiveTemplateInstantiations.empty()) {
11908 // Do not complain about the form of friend template types during
11909 // template instantiation; we will already have complained when the
11910 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000011911 } else {
11912 if (!T->isElaboratedTypeSpecifier()) {
11913 // If we evaluated the type to a record type, suggest putting
11914 // a tag in front.
11915 if (const RecordType *RT = T->getAs<RecordType>()) {
11916 RecordDecl *RD = RT->getDecl();
Alp Tokera030cd02014-05-05 12:38:48 +000011917
11918 SmallString<16> InsertionText(" ");
11919 InsertionText += RD->getKindName();
11920
Nick Lewycky36722d22013-02-06 05:59:33 +000011921 Diag(TypeRange.getBegin(),
11922 getLangOpts().CPlusPlus11 ?
11923 diag::warn_cxx98_compat_unelaborated_friend_type :
11924 diag::ext_unelaborated_friend_type)
11925 << (unsigned) RD->getTagKind()
11926 << T
11927 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11928 InsertionText);
11929 } else {
11930 Diag(FriendLoc,
11931 getLangOpts().CPlusPlus11 ?
11932 diag::warn_cxx98_compat_nonclass_type_friend :
11933 diag::ext_nonclass_type_friend)
11934 << T
11935 << TypeRange;
11936 }
11937 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000011938 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011939 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000011940 diag::warn_cxx98_compat_enum_friend :
11941 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011942 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000011943 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011944 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011945
Nick Lewycky36722d22013-02-06 05:59:33 +000011946 // C++11 [class.friend]p3:
11947 // A friend declaration that does not declare a function shall have one
11948 // of the following forms:
11949 // friend elaborated-type-specifier ;
11950 // friend simple-type-specifier ;
11951 // friend typename-specifier ;
11952 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11953 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11954 }
Richard Smitha31a89a2012-09-20 01:31:00 +000011955
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011956 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000011957 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000011958 // the friend declaration is ignored.
Nikola Smiljanic3a01af02014-05-23 12:48:27 +000011959 return FriendDecl::Create(Context, CurContext,
11960 TSInfo->getTypeLoc().getLocStart(), TSInfo,
11961 FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000011962}
11963
John McCallace48cd2010-10-19 01:40:49 +000011964/// Handle a friend tag declaration where the scope specifier was
11965/// templated.
11966Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11967 unsigned TagSpec, SourceLocation TagLoc,
11968 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000011969 IdentifierInfo *Name,
11970 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000011971 AttributeList *Attr,
11972 MultiTemplateParamsArg TempParamLists) {
11973 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11974
11975 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000011976 bool Invalid = false;
11977
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011978 if (TemplateParameterList *TemplateParams =
11979 MatchTemplateParametersToScopeSpecifier(
Craig Topperc3ec1492014-05-26 06:22:03 +000011980 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000011981 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000011982 if (TemplateParams->size() > 0) {
11983 // This is a declaration of a class template.
11984 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +000011985 return nullptr;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000011986
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000011987 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
11988 NameLoc, Attr, TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000011989 /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000011990 FriendLoc, TempParamLists.size() - 1,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011991 TempParamLists.data()).get();
John McCallace48cd2010-10-19 01:40:49 +000011992 } else {
11993 // The "template<>" header is extraneous.
11994 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11995 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11996 isExplicitSpecialization = true;
11997 }
11998 }
11999
Craig Topperc3ec1492014-05-26 06:22:03 +000012000 if (Invalid) return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000012001
John McCallace48cd2010-10-19 01:40:49 +000012002 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000012003 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012004 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000012005 isAllExplicitSpecializations = false;
12006 break;
12007 }
12008 }
12009
12010 // FIXME: don't ignore attributes.
12011
12012 // If it's explicit specializations all the way down, just forget
12013 // about the template header and build an appropriate non-templated
12014 // friend. TODO: for source fidelity, remember the headers.
12015 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012016 if (SS.isEmpty()) {
12017 bool Owned = false;
12018 bool IsDependent = false;
12019 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000012020 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012021 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000012022 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000012023 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012024 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000012025 /*UnderlyingType=*/TypeResult(),
12026 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012027 }
Richard Smith649c7b062014-01-08 00:56:48 +000012028
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012029 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000012030 ElaboratedTypeKeyword Keyword
12031 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012032 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000012033 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000012034 if (T.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +000012035 return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000012036
12037 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12038 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000012039 DependentNameTypeLoc TL =
12040 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012041 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012042 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000012043 TL.setNameLoc(NameLoc);
12044 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000012045 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012046 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000012047 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000012048 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000012049 }
12050
12051 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012052 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000012053 Friend->setAccess(AS_public);
12054 CurContext->addDecl(Friend);
12055 return Friend;
12056 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000012057
12058 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
12059
12060
John McCallace48cd2010-10-19 01:40:49 +000012061
12062 // Handle the case of a templated-scope friend class. e.g.
12063 // template <class T> class A<T>::B;
12064 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000012065 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
12066 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000012067 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12068 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
12069 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000012070 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000012071 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000012072 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000012073 TL.setNameLoc(NameLoc);
12074
12075 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000012076 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000012077 Friend->setAccess(AS_public);
12078 Friend->setUnsupportedFriend(true);
12079 CurContext->addDecl(Friend);
12080 return Friend;
12081}
12082
12083
John McCall11083da2009-09-16 22:47:08 +000012084/// Handle a friend type declaration. This works in tandem with
12085/// ActOnTag.
12086///
12087/// Notes on friend class templates:
12088///
12089/// We generally treat friend class declarations as if they were
12090/// declaring a class. So, for example, the elaborated type specifier
12091/// in a friend declaration is required to obey the restrictions of a
12092/// class-head (i.e. no typedefs in the scope chain), template
12093/// parameters are required to match up with simple template-ids, &c.
12094/// However, unlike when declaring a template specialization, it's
12095/// okay to refer to a template specialization without an empty
12096/// template parameter declaration, e.g.
12097/// friend class A<T>::B<unsigned>;
12098/// We permit this as a special case; if there are any template
12099/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000012100/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000012101Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000012102 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012103 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000012104
12105 assert(DS.isFriendSpecified());
12106 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12107
John McCall11083da2009-09-16 22:47:08 +000012108 // Try to convert the decl specifier to a type. This works for
12109 // friend templates because ActOnTag never produces a ClassTemplateDecl
12110 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000012111 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000012112 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
12113 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000012114 if (TheDeclarator.isInvalidType())
Craig Topperc3ec1492014-05-26 06:22:03 +000012115 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012116
Douglas Gregor6c110f32010-12-16 01:14:37 +000012117 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000012118 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000012119
John McCall11083da2009-09-16 22:47:08 +000012120 // This is definitely an error in C++98. It's probably meant to
12121 // be forbidden in C++0x, too, but the specification is just
12122 // poorly written.
12123 //
12124 // The problem is with declarations like the following:
12125 // template <T> friend A<T>::foo;
12126 // where deciding whether a class C is a friend or not now hinges
12127 // on whether there exists an instantiation of A that causes
12128 // 'foo' to equal C. There are restrictions on class-heads
12129 // (which we declare (by fiat) elaborated friend declarations to
12130 // be) that makes this tractable.
12131 //
12132 // FIXME: handle "template <> friend class A<T>;", which
12133 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000012134 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000012135 Diag(Loc, diag::err_tagless_friend_type_template)
12136 << DS.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000012137 return nullptr;
John McCall11083da2009-09-16 22:47:08 +000012138 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012139
John McCallaa74a0c2009-08-28 07:59:38 +000012140 // C++98 [class.friend]p1: A friend of a class is a function
12141 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000012142 // This is fixed in DR77, which just barely didn't make the C++03
12143 // deadline. It's also a very silly restriction that seriously
12144 // affects inner classes and which nobody else seems to implement;
12145 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000012146 //
12147 // But note that we could warn about it: it's always useless to
12148 // friend one of your own members (it's not, however, worthless to
12149 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000012150
John McCall11083da2009-09-16 22:47:08 +000012151 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012152 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000012153 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012154 NumTempParamLists,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000012155 TempParams.data(),
John McCall15ad0962010-03-25 18:04:51 +000012156 TSI,
John McCall11083da2009-09-16 22:47:08 +000012157 DS.getFriendSpecLoc());
12158 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000012159 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000012160
12161 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +000012162 return nullptr;
12163
John McCall11083da2009-09-16 22:47:08 +000012164 D->setAccess(AS_public);
12165 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000012166
John McCall48871652010-08-21 09:40:31 +000012167 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000012168}
12169
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000012170NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
12171 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000012172 const DeclSpec &DS = D.getDeclSpec();
12173
12174 assert(DS.isFriendSpecified());
12175 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12176
12177 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000012178 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000012179
12180 // C++ [class.friend]p1
12181 // A friend of a class is a function or class....
12182 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000012183 // It *doesn't* see through dependent types, which is correct
12184 // according to [temp.arg.type]p3:
12185 // If a declaration acquires a function type through a
12186 // type dependent on a template-parameter and this causes
12187 // a declaration that does not use the syntactic form of a
12188 // function declarator to have a function type, the program
12189 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012190 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000012191 Diag(Loc, diag::err_unexpected_friend);
12192
12193 // It might be worthwhile to try to recover by creating an
12194 // appropriate declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000012195 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012196 }
12197
12198 // C++ [namespace.memdef]p3
12199 // - If a friend declaration in a non-local class first declares a
12200 // class or function, the friend class or function is a member
12201 // of the innermost enclosing namespace.
12202 // - The name of the friend is not found by simple name lookup
12203 // until a matching declaration is provided in that namespace
12204 // scope (either before or after the class declaration granting
12205 // friendship).
12206 // - If a friend function is called, its name may be found by the
12207 // name lookup that considers functions from namespaces and
12208 // classes associated with the types of the function arguments.
12209 // - When looking for a prior declaration of a class or a function
12210 // declared as a friend, scopes outside the innermost enclosing
12211 // namespace scope are not considered.
12212
John McCallde3fd222010-10-12 23:13:28 +000012213 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012214 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
12215 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000012216 assert(Name);
12217
Douglas Gregor6c110f32010-12-16 01:14:37 +000012218 // Check for unexpanded parameter packs.
12219 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
12220 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
12221 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000012222 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000012223
John McCall07e91c02009-08-06 02:15:43 +000012224 // The context we found the declaration in, or in which we should
12225 // create the declaration.
12226 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000012227 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000012228 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000012229 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000012230
Richard Smith114394f2013-08-09 04:35:01 +000012231 // There are five cases here.
12232 // - There's no scope specifier and we're in a local class. Only look
12233 // for functions declared in the immediately-enclosing block scope.
12234 // We recover from invalid scope qualifiers as if they just weren't there.
Craig Topperc3ec1492014-05-26 06:22:03 +000012235 FunctionDecl *FunctionContainingLocalClass = nullptr;
Richard Smith114394f2013-08-09 04:35:01 +000012236 if ((SS.isInvalid() || !SS.isSet()) &&
12237 (FunctionContainingLocalClass =
12238 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
12239 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000012240 // If a friend declaration appears in a local class and the name
12241 // specified is an unqualified name, a prior declaration is
12242 // looked up without considering scopes that are outside the
12243 // innermost enclosing non-class scope. For a friend function
12244 // declaration, if there is no prior declaration, the program is
12245 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000012246
12247 // Find the innermost enclosing non-class scope. This is the block
12248 // scope containing the local class definition (or for a nested class,
12249 // the outer local class).
12250 DCScope = S->getFnParent();
12251
12252 // Look up the function name in the scope.
12253 Previous.clear(LookupLocalFriendName);
12254 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
12255
12256 if (!Previous.empty()) {
12257 // All possible previous declarations must have the same context:
12258 // either they were declared at block scope or they are members of
12259 // one of the enclosing local classes.
12260 DC = Previous.getRepresentativeDecl()->getDeclContext();
12261 } else {
12262 // This is ill-formed, but provide the context that we would have
12263 // declared the function in, if we were permitted to, for error recovery.
12264 DC = FunctionContainingLocalClass;
12265 }
Richard Smith541b38b2013-09-20 01:15:31 +000012266 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000012267
12268 // C++ [class.friend]p6:
12269 // A function can be defined in a friend declaration of a class if and
12270 // only if the class is a non-local class (9.8), the function name is
12271 // unqualified, and the function has namespace scope.
12272 if (D.isFunctionDefinition()) {
12273 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12274 }
12275
12276 // - There's no scope specifier, in which case we just go to the
12277 // appropriate scope and look for a function or function template
12278 // there as appropriate.
12279 } else if (SS.isInvalid() || !SS.isSet()) {
12280 // C++11 [namespace.memdef]p3:
12281 // If the name in a friend declaration is neither qualified nor
12282 // a template-id and the declaration is a function or an
12283 // elaborated-type-specifier, the lookup to determine whether
12284 // the entity has been previously declared shall not consider
12285 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000012286 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000012287
John McCallf7cfb222010-10-13 05:45:15 +000012288 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000012289 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000012290
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012291 // Skip class contexts. If someone can cite chapter and verse
12292 // for this behavior, that would be nice --- it's what GCC and
12293 // EDG do, and it seems like a reasonable intent, but the spec
12294 // really only says that checks for unqualified existing
12295 // declarations should stop at the nearest enclosing namespace,
12296 // not that they should only consider the nearest enclosing
12297 // namespace.
12298 while (DC->isRecord())
12299 DC = DC->getParent();
12300
12301 DeclContext *LookupDC = DC;
12302 while (LookupDC->isTransparentContext())
12303 LookupDC = LookupDC->getParent();
12304
12305 while (true) {
12306 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000012307
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012308 if (!Previous.empty()) {
12309 DC = LookupDC;
12310 break;
John McCallf4776592010-10-14 22:22:28 +000012311 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000012312
12313 if (isTemplateId) {
12314 if (isa<TranslationUnitDecl>(LookupDC)) break;
12315 } else {
12316 if (LookupDC->isFileContext()) break;
12317 }
12318 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000012319 }
12320
John McCallccbc0322010-10-13 06:22:15 +000012321 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000012322
John McCallde3fd222010-10-12 23:13:28 +000012323 // - There's a non-dependent scope specifier, in which case we
12324 // compute it and do a previous lookup there for a function
12325 // or function template.
12326 } else if (!SS.getScopeRep()->isDependent()) {
12327 DC = computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +000012328 if (!DC) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012329
Craig Topperc3ec1492014-05-26 06:22:03 +000012330 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012331
12332 LookupQualifiedName(Previous, DC);
12333
12334 // Ignore things found implicitly in the wrong scope.
12335 // TODO: better diagnostics for this case. Suggesting the right
12336 // qualified scope would be nice...
12337 LookupResult::Filter F = Previous.makeFilter();
12338 while (F.hasNext()) {
12339 NamedDecl *D = F.next();
12340 if (!DC->InEnclosingNamespaceSetOf(
12341 D->getDeclContext()->getRedeclContext()))
12342 F.erase();
12343 }
12344 F.done();
12345
12346 if (Previous.empty()) {
12347 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012348 Diag(Loc, diag::err_qualified_friend_not_found)
12349 << Name << TInfo->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +000012350 return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000012351 }
12352
12353 // C++ [class.friend]p1: A friend of a class is a function or
12354 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000012355 if (DC->Equals(CurContext))
12356 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000012357 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000012358 diag::warn_cxx98_compat_friend_is_member :
12359 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000012360
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012361 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012362 // C++ [class.friend]p6:
12363 // A function can be defined in a friend declaration of a class if and
12364 // only if the class is a non-local class (9.8), the function name is
12365 // unqualified, and the function has namespace scope.
12366 SemaDiagnosticBuilder DB
12367 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12368
12369 DB << SS.getScopeRep();
12370 if (DC->isFileContext())
12371 DB << FixItHint::CreateRemoval(SS.getRange());
12372 SS.clear();
12373 }
John McCallde3fd222010-10-12 23:13:28 +000012374
12375 // - There's a scope specifier that does not match any template
12376 // parameter lists, in which case we use some arbitrary context,
12377 // create a method or method template, and wait for instantiation.
12378 // - There's a scope specifier that does match some template
12379 // parameter lists, which we don't handle right now.
12380 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012381 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000012382 // C++ [class.friend]p6:
12383 // A function can be defined in a friend declaration of a class if and
12384 // only if the class is a non-local class (9.8), the function name is
12385 // unqualified, and the function has namespace scope.
12386 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12387 << SS.getScopeRep();
12388 }
12389
John McCallde3fd222010-10-12 23:13:28 +000012390 DC = CurContext;
12391 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000012392 }
Douglas Gregor16e65612011-10-10 01:11:59 +000012393
John McCallf7cfb222010-10-13 05:45:15 +000012394 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000012395 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000012396 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
12397 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
12398 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000012399 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000012400 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
12401 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
Craig Topperc3ec1492014-05-26 06:22:03 +000012402 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000012403 }
John McCall07e91c02009-08-06 02:15:43 +000012404 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012405
Douglas Gregordd847ba2011-11-03 16:37:14 +000012406 // FIXME: This is an egregious hack to cope with cases where the scope stack
12407 // does not contain the declaration context, i.e., in an out-of-line
12408 // definition of a class.
12409 Scope FakeDCScope(S, Scope::DeclScope, Diags);
12410 if (!DCScope) {
12411 FakeDCScope.setEntity(DC);
12412 DCScope = &FakeDCScope;
12413 }
Richard Smith114394f2013-08-09 04:35:01 +000012414
Francois Pichet00c7e6c2011-08-14 03:52:19 +000012415 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000012416 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012417 TemplateParams, AddToScope);
Craig Topperc3ec1492014-05-26 06:22:03 +000012418 if (!ND) return nullptr;
John McCall759e32b2009-08-31 22:39:49 +000012419
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012420 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000012421
Richard Smith114394f2013-08-09 04:35:01 +000012422 // If we performed typo correction, we might have added a scope specifier
12423 // and changed the decl context.
12424 DC = ND->getDeclContext();
12425
John McCall759e32b2009-08-31 22:39:49 +000012426 // Add the function declaration to the appropriate lookup tables,
12427 // adjusting the redeclarations list as necessary. We don't
12428 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000012429 //
John McCall759e32b2009-08-31 22:39:49 +000012430 // Also update the scope-based lookup if the target context's
12431 // lookup context is in lexical scope.
12432 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000012433 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000012434 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000012435 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012436 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000012437 }
John McCallaa74a0c2009-08-28 07:59:38 +000012438
12439 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000012440 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000012441 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000012442 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000012443 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000012444
John McCalla0a96892012-08-10 03:15:35 +000012445 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000012446 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000012447 } else {
12448 if (DC->isRecord()) CheckFriendAccess(ND);
12449
John McCall2c2eb122010-10-16 06:59:13 +000012450 FunctionDecl *FD;
12451 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12452 FD = FTD->getTemplatedDecl();
12453 else
12454 FD = cast<FunctionDecl>(ND);
12455
David Majnemer502b0ed2013-06-25 23:09:30 +000012456 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12457 // default argument expression, that declaration shall be a definition
12458 // and shall be the only declaration of the function or function
12459 // template in the translation unit.
12460 if (functionDeclHasDefaultArgument(FD)) {
12461 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12462 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12463 Diag(OldFD->getLocation(), diag::note_previous_declaration);
12464 } else if (!D.isFunctionDefinition())
12465 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12466 }
12467
John McCall2c2eb122010-10-16 06:59:13 +000012468 // Mark templated-scope function declarations as unsupported.
Richard Smith04b35e92014-09-29 05:57:29 +000012469 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
12470 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
12471 << SS.getScopeRep() << SS.getRange()
12472 << cast<CXXRecordDecl>(CurContext);
John McCall2c2eb122010-10-16 06:59:13 +000012473 FrD->setUnsupportedFriend(true);
Richard Smith04b35e92014-09-29 05:57:29 +000012474 }
John McCall2c2eb122010-10-16 06:59:13 +000012475 }
John McCallde3fd222010-10-12 23:13:28 +000012476
John McCall48871652010-08-21 09:40:31 +000012477 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000012478}
12479
John McCall48871652010-08-21 09:40:31 +000012480void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12481 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000012482
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012483 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000012484 if (!Fn) {
12485 Diag(DelLoc, diag::err_deleted_non_function);
12486 return;
12487 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012488
Douglas Gregorec9fd132012-01-14 16:38:05 +000012489 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000012490 // Don't consider the implicit declaration we generate for explicit
12491 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000012492 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12493 Prev->getPreviousDecl()) &&
12494 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000012495 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000012496 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12497 Prev->isImplicit() ? diag::note_previous_implicit_declaration
12498 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000012499 }
Sebastian Redlf769df52009-03-24 22:27:57 +000012500 // If the declaration wasn't the first, we delete the function anyway for
12501 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000012502 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000012503 }
Richard Smithb4d2a152013-04-02 19:38:47 +000012504
Nico Rieck9de0a572014-05-29 16:51:19 +000012505 // dllimport/dllexport cannot be deleted.
12506 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12507 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12508 Fn->setInvalidDecl();
12509 }
12510
Richard Smithb4d2a152013-04-02 19:38:47 +000012511 if (Fn->isDeleted())
12512 return;
12513
12514 // See if we're deleting a function which is already known to override a
12515 // non-deleted virtual function.
12516 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12517 bool IssuedDiagnostic = false;
12518 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12519 E = MD->end_overridden_methods();
12520 I != E; ++I) {
12521 if (!(*MD->begin_overridden_methods())->isDeleted()) {
12522 if (!IssuedDiagnostic) {
12523 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12524 IssuedDiagnostic = true;
12525 }
12526 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12527 }
12528 }
12529 }
12530
Richard Smithb63b6ee2014-01-22 01:43:19 +000012531 // C++11 [basic.start.main]p3:
12532 // A program that defines main as deleted [...] is ill-formed.
12533 if (Fn->isMain())
12534 Diag(DelLoc, diag::err_deleted_main);
12535
Alexis Hunt4a8ea102011-05-06 20:44:56 +000012536 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000012537}
Sebastian Redl4c018662009-04-27 21:33:24 +000012538
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012539void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000012540 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012541
12542 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000012543 if (MD->getParent()->isDependentType()) {
12544 MD->setDefaulted();
12545 MD->setExplicitlyDefaulted();
12546 return;
12547 }
12548
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012549 CXXSpecialMember Member = getSpecialMember(MD);
12550 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000012551 if (!MD->isInvalidDecl())
12552 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012553 return;
12554 }
12555
12556 MD->setDefaulted();
12557 MD->setExplicitlyDefaulted();
12558
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012559 // If this definition appears within the record, do the checking when
12560 // the record is complete.
12561 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000012562 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012563 // Find the uninstantiated declaration that actually had the '= default'
12564 // on it.
Richard Smith802c4b72012-08-23 06:16:52 +000012565 Pattern->isDefined(Primary);
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012566
Richard Smith3901dfe2013-03-27 00:22:47 +000012567 // If the method was defaulted on its first declaration, we will have
12568 // already performed the checking in CheckCompletedCXXClass. Such a
12569 // declaration doesn't trigger an implicit definition.
Alexis Hunt61ae8d32011-05-23 23:14:04 +000012570 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012571 return;
12572
Richard Smithd3b5c9082012-07-27 04:22:15 +000012573 CheckExplicitlyDefaultedSpecialMember(MD);
12574
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012575 if (MD->isInvalidDecl())
12576 return;
12577
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012578 switch (Member) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012579 case CXXDefaultConstructor:
12580 DefineImplicitDefaultConstructor(DefaultLoc,
12581 cast<CXXConstructorDecl>(MD));
Alexis Hunt913820d2011-05-13 06:10:58 +000012582 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012583 case CXXCopyConstructor:
12584 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012585 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012586 case CXXCopyAssignment:
12587 DefineImplicitCopyAssignment(DefaultLoc, MD);
Alexis Huntc9a55732011-05-14 05:23:28 +000012588 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012589 case CXXDestructor:
12590 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Alexis Huntf91729462011-05-12 22:46:25 +000012591 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012592 case CXXMoveConstructor:
12593 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Alexis Hunt119c10e2011-05-25 23:16:36 +000012594 break;
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012595 case CXXMoveAssignment:
12596 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012597 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000012598 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000012599 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000012600 }
12601 } else {
12602 Diag(DefaultLoc, diag::err_default_special_members);
12603 }
12604}
12605
Sebastian Redl4c018662009-04-27 21:33:24 +000012606static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000012607 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000012608 Stmt *SubStmt = *CI;
12609 if (!SubStmt)
12610 continue;
12611 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000012612 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000012613 diag::err_return_in_constructor_handler);
12614 if (!isa<Expr>(SubStmt))
12615 SearchForReturnInStmt(Self, SubStmt);
12616 }
12617}
12618
12619void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12620 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12621 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12622 SearchForReturnInStmt(*this, Handler);
12623 }
12624}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012625
David Blaikie68f71a32013-01-18 23:03:15 +000012626bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000012627 const CXXMethodDecl *Old) {
12628 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12629 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12630
12631 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12632
12633 // If the calling conventions match, everything is fine
12634 if (NewCC == OldCC)
12635 return false;
12636
Hans Wennborg2545efe2013-12-11 17:42:11 +000012637 // If the calling conventions mismatch because the new function is static,
12638 // suppress the calling convention mismatch error; the error about static
12639 // function override (err_static_overrides_virtual from
12640 // Sema::CheckFunctionDeclaration) is more clear.
12641 if (New->getStorageClass() == SC_Static)
12642 return false;
12643
Reid Kleckner78af0702013-08-27 23:08:25 +000012644 Diag(New->getLocation(),
12645 diag::err_conflicting_overriding_cc_attributes)
12646 << New->getDeclName() << New->getType() << Old->getType();
12647 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12648 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000012649}
12650
Mike Stump11289f42009-09-09 15:08:12 +000012651bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012652 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000012653 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12654 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012655
Chandler Carruth284bb2e2010-02-15 11:53:20 +000012656 if (Context.hasSameType(NewTy, OldTy) ||
12657 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012658 return false;
Mike Stump11289f42009-09-09 15:08:12 +000012659
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012660 // Check if the return types are covariant
12661 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000012662
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012663 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012664 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12665 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012666 NewClassTy = NewPT->getPointeeType();
12667 OldClassTy = OldPT->getPointeeType();
12668 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012669 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12670 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12671 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12672 NewClassTy = NewRT->getPointeeType();
12673 OldClassTy = OldRT->getPointeeType();
12674 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012675 }
12676 }
Mike Stump11289f42009-09-09 15:08:12 +000012677
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012678 // The return types aren't either both pointers or references to a class type.
12679 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000012680 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012681 diag::err_different_return_type_for_overriding_virtual_function)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012682 << New->getDeclName() << NewTy << OldTy
12683 << New->getReturnTypeSourceRange();
12684 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12685 << Old->getReturnTypeSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000012686
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012687 return true;
12688 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012689
Anders Carlssone60365b2009-12-31 18:34:24 +000012690 // C++ [class.virtual]p6:
12691 // If the return type of D::f differs from the return type of B::f, the
12692 // class type in the return type of D::f shall be complete at the point of
12693 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012694 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12695 if (!RT->isBeingDefined() &&
12696 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012697 diag::err_covariant_return_incomplete,
12698 New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000012699 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000012700 }
Anders Carlssone60365b2009-12-31 18:34:24 +000012701
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000012702 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012703 // Check if the new class derives from the old class.
12704 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
Alp Tokerd0787eb2014-07-02 01:47:15 +000012705 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
12706 << New->getDeclName() << NewTy << OldTy
12707 << New->getReturnTypeSourceRange();
12708 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12709 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012710 return true;
12711 }
Mike Stump11289f42009-09-09 15:08:12 +000012712
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012713 // Check if we the conversion from derived to base is valid.
Alp Tokerd0787eb2014-07-02 01:47:15 +000012714 if (CheckDerivedToBaseConversion(
12715 NewClassTy, OldClassTy,
12716 diag::err_covariant_return_inaccessible_base,
12717 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12718 New->getLocation(), New->getReturnTypeSourceRange(),
12719 New->getDeclName(), nullptr)) {
John McCallc1465822011-02-14 07:13:47 +000012720 // FIXME: this note won't trigger for delayed access control
12721 // diagnostics, and it's impossible to get an undelayed error
12722 // here from access control during the original parse because
12723 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Alp Tokerd0787eb2014-07-02 01:47:15 +000012724 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12725 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012726 return true;
12727 }
12728 }
Mike Stump11289f42009-09-09 15:08:12 +000012729
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012730 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000012731 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012732 Diag(New->getLocation(),
12733 diag::err_covariant_return_type_different_qualifications)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012734 << New->getDeclName() << NewTy << OldTy
12735 << New->getReturnTypeSourceRange();
12736 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12737 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012738 return true;
12739 };
Mike Stump11289f42009-09-09 15:08:12 +000012740
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012741
12742 // The new class type must have the same or less qualifiers as the old type.
12743 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12744 Diag(New->getLocation(),
12745 diag::err_covariant_return_type_class_type_more_qualified)
Alp Tokerd0787eb2014-07-02 01:47:15 +000012746 << New->getDeclName() << NewTy << OldTy
12747 << New->getReturnTypeSourceRange();
12748 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12749 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012750 return true;
12751 };
Mike Stump11289f42009-09-09 15:08:12 +000012752
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000012753 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000012754}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012755
Douglas Gregor21920e372009-12-01 17:24:26 +000012756/// \brief Mark the given method pure.
12757///
12758/// \param Method the method to be marked pure.
12759///
12760/// \param InitRange the source range that covers the "0" initializer.
12761bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012762 SourceLocation EndLoc = InitRange.getEnd();
12763 if (EndLoc.isValid())
12764 Method->setRangeEnd(EndLoc);
12765
Douglas Gregor21920e372009-12-01 17:24:26 +000012766 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12767 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000012768 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000012769 }
Douglas Gregor21920e372009-12-01 17:24:26 +000012770
12771 if (!Method->isInvalidDecl())
12772 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12773 << Method->getDeclName() << InitRange;
12774 return true;
12775}
12776
Douglas Gregor926410d2012-02-21 02:22:07 +000012777/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012778static bool isStaticDataMember(const Decl *D) {
12779 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12780 return Var->isStaticDataMember();
12781
12782 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000012783}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000012784
John McCall1f4ee7b2009-12-19 09:28:58 +000012785/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12786/// an initializer for the out-of-line declaration 'Dcl'. The scope
12787/// is a fresh scope pushed for just this purpose.
12788///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012789/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12790/// static data member of class X, names should be looked up in the scope of
12791/// class X.
John McCall48871652010-08-21 09:40:31 +000012792void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012793 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000012794 if (!D || D->isInvalidDecl())
12795 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012796
Richard Smitha2302242013-12-05 07:51:02 +000012797 // We will always have a nested name specifier here, but this declaration
12798 // might not be out of line if the specifier names the current namespace:
12799 // extern int n;
12800 // int ::n = 0;
12801 if (D->isOutOfLine())
12802 EnterDeclaratorContext(S, D->getDeclContext());
12803
Douglas Gregor926410d2012-02-21 02:22:07 +000012804 // If we are parsing the initializer for a static data member, push a
12805 // new expression evaluation context that is associated with this static
12806 // data member.
12807 if (isStaticDataMember(D))
12808 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012809}
12810
12811/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000012812/// initializer for the out-of-line declaration 'D'.
12813void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012814 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000012815 if (!D || D->isInvalidDecl())
12816 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012817
Douglas Gregor926410d2012-02-21 02:22:07 +000012818 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000012819 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000012820
Richard Smitha2302242013-12-05 07:51:02 +000012821 if (D->isOutOfLine())
12822 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000012823}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012824
12825/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12826/// C++ if/switch/while/for statement.
12827/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000012828DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012829 // C++ 6.4p2:
12830 // The declarator shall not specify a function or an array.
12831 // The type-specifier-seq shall not contain typedef and shall not declare a
12832 // new class or enumeration.
12833 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12834 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012835
12836 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012837 if (!Dcl)
12838 return true;
12839
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000012840 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12841 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012842 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000012843 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012844 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012845
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000012846 return Dcl;
12847}
Anders Carlssonf98849e2009-12-02 17:15:43 +000012848
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012849void Sema::LoadExternalVTableUses() {
12850 if (!ExternalSource)
12851 return;
12852
12853 SmallVector<ExternalVTableUse, 4> VTables;
12854 ExternalSource->ReadUsedVTables(VTables);
12855 SmallVector<VTableUse, 4> NewUses;
12856 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12857 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12858 = VTablesUsed.find(VTables[I].Record);
12859 // Even if a definition wasn't required before, it may be required now.
12860 if (Pos != VTablesUsed.end()) {
12861 if (!Pos->second && VTables[I].DefinitionRequired)
12862 Pos->second = true;
12863 continue;
12864 }
12865
12866 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12867 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12868 }
12869
12870 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12871}
12872
Douglas Gregor88d292c2010-05-13 16:44:06 +000012873void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12874 bool DefinitionRequired) {
12875 // Ignore any vtable uses in unevaluated operands or for classes that do
12876 // not have a vtable.
12877 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000012878 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000012879 return;
12880
Douglas Gregor88d292c2010-05-13 16:44:06 +000012881 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012882 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012883 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12884 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12885 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12886 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000012887 // If we already had an entry, check to see if we are promoting this vtable
12888 // to required a definition. If so, we need to reappend to the VTableUses
12889 // list, since we may have already processed the first entry.
12890 if (DefinitionRequired && !Pos.first->second) {
12891 Pos.first->second = true;
12892 } else {
12893 // Otherwise, we can early exit.
12894 return;
12895 }
Hans Wennborg3d791542014-02-24 15:58:24 +000012896 } else {
12897 // The Microsoft ABI requires that we perform the destructor body
12898 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
12899 // the deleting destructor is emitted with the vtable, not with the
12900 // destructor definition as in the Itanium ABI.
12901 // If it has a definition, we do the check at that point instead.
12902 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12903 Class->hasUserDeclaredDestructor() &&
12904 !Class->getDestructor()->isDefined() &&
12905 !Class->getDestructor()->isDeleted()) {
Reid Kleckner67130862014-06-12 22:39:12 +000012906 CXXDestructorDecl *DD = Class->getDestructor();
12907 ContextRAII SavedContext(*this, DD);
12908 CheckDestructor(DD);
Hans Wennborg3d791542014-02-24 15:58:24 +000012909 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000012910 }
12911
12912 // Local classes need to have their virtual members marked
12913 // immediately. For all other classes, we mark their virtual members
12914 // at the end of the translation unit.
12915 if (Class->isLocalClass())
12916 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000012917 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000012918 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000012919}
12920
Douglas Gregor88d292c2010-05-13 16:44:06 +000012921bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000012922 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012923 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000012924 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000012925
Douglas Gregor88d292c2010-05-13 16:44:06 +000012926 // Note: The VTableUses vector could grow as a result of marking
12927 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000012928 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000012929 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000012930 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012931 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000012932 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012933 if (!Class)
12934 continue;
12935
12936 SourceLocation Loc = VTableUses[I].second;
12937
Richard Smithd3b5c9082012-07-27 04:22:15 +000012938 bool DefineVTable = true;
12939
Douglas Gregor88d292c2010-05-13 16:44:06 +000012940 // If this class has a key function, but that key function is
12941 // defined in another translation unit, we don't need to emit the
12942 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000012943 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000012944 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000012945 // The key function is in another translation unit.
12946 DefineVTable = false;
12947 TemplateSpecializationKind TSK =
12948 KeyFunction->getTemplateSpecializationKind();
12949 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12950 TSK != TSK_ImplicitInstantiation &&
12951 "Instantiations don't have key functions");
12952 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012953 } else if (!KeyFunction) {
12954 // If we have a class with no key function that is the subject
12955 // of an explicit instantiation declaration, suppress the
12956 // vtable; it will live with the explicit instantiation
12957 // definition.
12958 bool IsExplicitInstantiationDeclaration
12959 = Class->getTemplateSpecializationKind()
12960 == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000012961 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000012962 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000012963 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000012964 if (TSK == TSK_ExplicitInstantiationDeclaration)
12965 IsExplicitInstantiationDeclaration = true;
12966 else if (TSK == TSK_ExplicitInstantiationDefinition) {
12967 IsExplicitInstantiationDeclaration = false;
12968 break;
12969 }
12970 }
12971
12972 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000012973 DefineVTable = false;
12974 }
12975
12976 // The exception specifications for all virtual members may be needed even
12977 // if we are not providing an authoritative form of the vtable in this TU.
12978 // We may choose to emit it available_externally anyway.
12979 if (!DefineVTable) {
12980 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12981 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012982 }
12983
12984 // Mark all of the virtual members of this class as referenced, so
12985 // that we can build a vtable. Then, tell the AST consumer that a
12986 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000012987 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000012988 MarkVirtualMembersReferenced(Loc, Class);
12989 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12990 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12991
12992 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola3ae00052013-05-13 00:12:11 +000012993 if (Class->isExternallyVisible() &&
Douglas Gregor88d292c2010-05-13 16:44:06 +000012994 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012995 const FunctionDecl *KeyFunctionDef = nullptr;
Douglas Gregor34bc6e52011-09-23 19:04:03 +000012996 if (!KeyFunction ||
12997 (KeyFunction->hasBody(KeyFunctionDef) &&
12998 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000012999 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
13000 TSK_ExplicitInstantiationDefinition
13001 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
13002 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000013003 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000013004 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000013005 VTableUses.clear();
13006
Douglas Gregor97509692011-04-22 22:25:37 +000013007 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000013008}
Anders Carlsson82fccd02009-12-07 08:24:59 +000013009
Richard Smithd3b5c9082012-07-27 04:22:15 +000013010void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
13011 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000013012 for (const auto *I : RD->methods())
13013 if (I->isVirtual() && !I->isPure())
13014 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000013015}
13016
Rafael Espindola5b334082010-03-26 00:36:59 +000013017void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
13018 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000013019 // Mark all functions which will appear in RD's vtable as used.
13020 CXXFinalOverriderMap FinalOverriders;
13021 RD->getFinalOverriders(FinalOverriders);
13022 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
13023 E = FinalOverriders.end();
13024 I != E; ++I) {
13025 for (OverridingMethods::const_iterator OI = I->second.begin(),
13026 OE = I->second.end();
13027 OI != OE; ++OI) {
13028 assert(OI->second.size() > 0 && "no final overrider");
13029 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000013030
Richard Smith4ff9ff92012-07-07 06:59:51 +000013031 // C++ [basic.def.odr]p2:
13032 // [...] A virtual member function is used if it is not pure. [...]
13033 if (!Overrider->isPure())
13034 MarkFunctionReferenced(Loc, Overrider);
13035 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000013036 }
Rafael Espindola5b334082010-03-26 00:36:59 +000013037
13038 // Only classes that have virtual bases need a VTT.
13039 if (RD->getNumVBases() == 0)
13040 return;
13041
Aaron Ballman574705e2014-03-13 15:41:46 +000013042 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000013043 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000013044 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000013045 if (Base->getNumVBases() == 0)
13046 continue;
13047 MarkVirtualMembersReferenced(Loc, Base);
13048 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000013049}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013050
13051/// SetIvarInitializers - This routine builds initialization ASTs for the
13052/// Objective-C implementation whose ivars need be initialized.
13053void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000013054 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013055 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000013056 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000013057 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013058 CollectIvarsToConstructOrDestruct(OID, ivars);
13059 if (ivars.empty())
13060 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000013061 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013062 for (unsigned i = 0; i < ivars.size(); i++) {
13063 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000013064 if (Field->isInvalidDecl())
13065 continue;
13066
Alexis Hunt1d792652011-01-08 20:30:50 +000013067 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013068 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
13069 InitializationKind InitKind =
13070 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000013071
13072 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
13073 ExprResult MemberInit =
13074 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000013075 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013076 // Note, MemberInit could actually come back empty if no initialization
13077 // is required (e.g., because it would call a trivial default constructor)
13078 if (!MemberInit.get() || MemberInit.isInvalid())
13079 continue;
John McCallacf0ee52010-10-08 02:01:28 +000013080
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013081 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000013082 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
13083 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013084 MemberInit.getAs<Expr>(),
Alexis Hunt1d792652011-01-08 20:30:50 +000013085 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013086 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000013087
13088 // Be sure that the destructor is accessible and is marked as referenced.
13089 if (const RecordType *RecordTy
13090 = Context.getBaseElementType(Field->getType())
13091 ->getAs<RecordType>()) {
13092 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000013093 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000013094 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000013095 CheckDestructorAccess(Field->getLocation(), Destructor,
13096 PDiag(diag::err_access_dtor_ivar)
13097 << Context.getBaseElementType(Field->getType()));
13098 }
13099 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000013100 }
13101 ObjCImplementation->setIvarInitializers(Context,
13102 AllToInit.data(), AllToInit.size());
13103 }
13104}
Alexis Hunt6118d662011-05-04 05:57:24 +000013105
Alexis Hunt27a761d2011-05-04 23:29:54 +000013106static
13107void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
13108 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
13109 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
13110 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
13111 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000013112 if (Ctor->isInvalidDecl())
13113 return;
13114
Richard Smith802c4b72012-08-23 06:16:52 +000013115 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
13116
13117 // Target may not be determinable yet, for instance if this is a dependent
13118 // call in an uninstantiated template.
13119 if (Target) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013120 const FunctionDecl *FNTarget = nullptr;
Richard Smith802c4b72012-08-23 06:16:52 +000013121 (void)Target->hasBody(FNTarget);
13122 Target = const_cast<CXXConstructorDecl*>(
13123 cast_or_null<CXXConstructorDecl>(FNTarget));
13124 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000013125
13126 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
13127 // Avoid dereferencing a null pointer here.
Craig Topperc3ec1492014-05-26 06:22:03 +000013128 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000013129
13130 if (!Current.insert(Canonical))
13131 return;
13132
13133 // We know that beyond here, we aren't chaining into a cycle.
13134 if (!Target || !Target->isDelegatingConstructor() ||
13135 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013136 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000013137 Current.clear();
13138 // We've hit a cycle.
13139 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
13140 Current.count(TCanonical)) {
13141 // If we haven't diagnosed this cycle yet, do so now.
13142 if (!Invalid.count(TCanonical)) {
13143 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000013144 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013145 << Ctor;
13146
Richard Smith802c4b72012-08-23 06:16:52 +000013147 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000013148 if (TCanonical != Canonical)
13149 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
13150
13151 CXXConstructorDecl *C = Target;
13152 while (C->getCanonicalDecl() != Canonical) {
Craig Topperc3ec1492014-05-26 06:22:03 +000013153 const FunctionDecl *FNTarget = nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000013154 (void)C->getTargetConstructor()->hasBody(FNTarget);
13155 assert(FNTarget && "Ctor cycle through bodiless function");
13156
Richard Smith802c4b72012-08-23 06:16:52 +000013157 C = const_cast<CXXConstructorDecl*>(
13158 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000013159 S.Diag(C->getLocation(), diag::note_which_delegates_to);
13160 }
13161 }
13162
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013163 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000013164 Current.clear();
13165 } else {
13166 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
13167 }
13168}
13169
13170
Alexis Hunt6118d662011-05-04 05:57:24 +000013171void Sema::CheckDelegatingCtorCycles() {
13172 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
13173
Douglas Gregorbae31202011-07-27 21:57:17 +000013174 for (DelegatingCtorDeclsType::iterator
13175 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000013176 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000013177 I != E; ++I)
13178 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000013179
Benjamin Kramer8bf44352013-07-24 15:28:33 +000013180 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
13181 CE = Invalid.end();
13182 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000013183 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000013184}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000013185
Douglas Gregor3024f072012-04-16 07:05:22 +000013186namespace {
13187 /// \brief AST visitor that finds references to the 'this' expression.
13188 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
13189 Sema &S;
13190
13191 public:
13192 explicit FindCXXThisExpr(Sema &S) : S(S) { }
13193
13194 bool VisitCXXThisExpr(CXXThisExpr *E) {
13195 S.Diag(E->getLocation(), diag::err_this_static_member_func)
13196 << E->isImplicit();
13197 return false;
13198 }
13199 };
13200}
13201
13202bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
13203 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13204 if (!TSInfo)
13205 return false;
13206
13207 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000013208 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000013209 if (!ProtoTL)
13210 return false;
13211
13212 // C++11 [expr.prim.general]p3:
13213 // [The expression this] shall not appear before the optional
13214 // cv-qualifier-seq and it shall not appear within the declaration of a
13215 // static member function (although its type and value category are defined
13216 // within a static member function as they are within a non-static member
13217 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000013218 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000013219 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000013220 FindCXXThisExpr Finder(*this);
13221
13222 // If the return type came after the cv-qualifier-seq, check it now.
13223 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000013224 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000013225 return true;
13226
13227 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000013228 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
13229 return true;
13230
13231 return checkThisInStaticMemberFunctionAttributes(Method);
13232}
13233
13234bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
13235 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13236 if (!TSInfo)
13237 return false;
13238
13239 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000013240 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000013241 if (!ProtoTL)
13242 return false;
13243
David Blaikie6adc78e2013-02-18 22:06:02 +000013244 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000013245 FindCXXThisExpr Finder(*this);
13246
Douglas Gregor3024f072012-04-16 07:05:22 +000013247 switch (Proto->getExceptionSpecType()) {
Richard Smithf623c962012-04-17 00:58:00 +000013248 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000013249 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000013250 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000013251 case EST_DynamicNone:
13252 case EST_MSAny:
13253 case EST_None:
13254 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000013255
Douglas Gregor3024f072012-04-16 07:05:22 +000013256 case EST_ComputedNoexcept:
13257 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
13258 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000013259
Douglas Gregor3024f072012-04-16 07:05:22 +000013260 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000013261 for (const auto &E : Proto->exceptions()) {
13262 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000013263 return true;
13264 }
13265 break;
13266 }
Douglas Gregor433e0532012-04-16 18:27:27 +000013267
13268 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000013269}
13270
13271bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
13272 FindCXXThisExpr Finder(*this);
13273
13274 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013275 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013276 // FIXME: This should be emitted by tblgen.
Craig Topperc3ec1492014-05-26 06:22:03 +000013277 Expr *Arg = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +000013278 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013279 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013280 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013281 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013282 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013283 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013284 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013285 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013286 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013287 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013288 Arg = ETLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000013289 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013290 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000013291 Arg = STLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000013292 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
Aaron Ballman18d85ae2014-03-20 16:02:49 +000013293 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000013294 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013295 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013296 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013297 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013298 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013299 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013300 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013301 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013302 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000013303 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000013304 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000013305
13306 if (Arg && !Finder.TraverseStmt(Arg))
13307 return true;
13308
13309 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13310 if (!Finder.TraverseStmt(Args[I]))
13311 return true;
13312 }
13313 }
13314
13315 return false;
13316}
13317
NAKAMURA Takumi23224152014-10-17 12:48:37 +000013318void
13319Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
13320 ArrayRef<ParsedType> DynamicExceptions,
13321 ArrayRef<SourceRange> DynamicExceptionRanges,
13322 Expr *NoexceptExpr,
13323 SmallVectorImpl<QualType> &Exceptions,
13324 FunctionProtoType::ExceptionSpecInfo &ESI) {
Douglas Gregor433e0532012-04-16 18:27:27 +000013325 Exceptions.clear();
Richard Smith8acb4282014-07-31 21:57:55 +000013326 ESI.Type = EST;
Douglas Gregor433e0532012-04-16 18:27:27 +000013327 if (EST == EST_Dynamic) {
13328 Exceptions.reserve(DynamicExceptions.size());
13329 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13330 // FIXME: Preserve type source info.
13331 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13332
NAKAMURA Takumi23224152014-10-17 12:48:37 +000013333 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13334 collectUnexpandedParameterPacks(ET, Unexpanded);
13335 if (!Unexpanded.empty()) {
13336 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
13337 UPPC_ExceptionType,
13338 Unexpanded);
13339 continue;
Douglas Gregor433e0532012-04-16 18:27:27 +000013340 }
13341
13342 // Check that the type is valid for an exception spec, and
13343 // drop it if not.
13344 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13345 Exceptions.push_back(ET);
13346 }
Richard Smith8acb4282014-07-31 21:57:55 +000013347 ESI.Exceptions = Exceptions;
Douglas Gregor433e0532012-04-16 18:27:27 +000013348 return;
13349 }
Richard Smith8acb4282014-07-31 21:57:55 +000013350
Douglas Gregor433e0532012-04-16 18:27:27 +000013351 if (EST == EST_ComputedNoexcept) {
13352 // If an error occurred, there's no expression here.
13353 if (NoexceptExpr) {
13354 assert((NoexceptExpr->isTypeDependent() ||
13355 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13356 Context.BoolTy) &&
13357 "Parser should have made sure that the expression is boolean");
NAKAMURA Takumi23224152014-10-17 12:48:37 +000013358 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
Richard Smith8acb4282014-07-31 21:57:55 +000013359 ESI.Type = EST_BasicNoexcept;
Douglas Gregor433e0532012-04-16 18:27:27 +000013360 return;
13361 }
Richard Smith8acb4282014-07-31 21:57:55 +000013362
Douglas Gregor433e0532012-04-16 18:27:27 +000013363 if (!NoexceptExpr->isValueDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +000013364 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
Douglas Gregore2b37442012-05-04 22:38:52 +000013365 diag::err_noexcept_needs_constant_expression,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013366 /*AllowFold*/ false).get();
Richard Smith8acb4282014-07-31 21:57:55 +000013367 ESI.NoexceptExpr = NoexceptExpr;
Douglas Gregor433e0532012-04-16 18:27:27 +000013368 }
13369 return;
13370 }
13371}
13372
John McCall5e77d762013-04-16 07:28:30 +000013373/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13374///
13375MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13376 SourceLocation DeclStart,
13377 Declarator &D, Expr *BitWidth,
13378 InClassInitStyle InitStyle,
13379 AccessSpecifier AS,
13380 AttributeList *MSPropertyAttr) {
13381 IdentifierInfo *II = D.getIdentifier();
13382 if (!II) {
13383 Diag(DeclStart, diag::err_anonymous_property);
Craig Topperc3ec1492014-05-26 06:22:03 +000013384 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013385 }
13386 SourceLocation Loc = D.getIdentifierLoc();
13387
13388 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13389 QualType T = TInfo->getType();
13390 if (getLangOpts().CPlusPlus) {
13391 CheckExtraCXXDefaultArguments(D);
13392
13393 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13394 UPPC_DataMemberType)) {
13395 D.setInvalidType();
13396 T = Context.IntTy;
13397 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13398 }
13399 }
13400
13401 DiagnoseFunctionSpecifiers(D.getDeclSpec());
13402
13403 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13404 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13405 diag::err_invalid_thread)
13406 << DeclSpec::getSpecifierName(TSCS);
13407
13408 // Check to see if this name was declared as a member previously
Craig Topperc3ec1492014-05-26 06:22:03 +000013409 NamedDecl *PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013410 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13411 LookupName(Previous, S);
13412 switch (Previous.getResultKind()) {
13413 case LookupResult::Found:
13414 case LookupResult::FoundUnresolvedValue:
13415 PrevDecl = Previous.getAsSingle<NamedDecl>();
13416 break;
13417
13418 case LookupResult::FoundOverloaded:
13419 PrevDecl = Previous.getRepresentativeDecl();
13420 break;
13421
13422 case LookupResult::NotFound:
13423 case LookupResult::NotFoundInCurrentInstantiation:
13424 case LookupResult::Ambiguous:
13425 break;
13426 }
13427
13428 if (PrevDecl && PrevDecl->isTemplateParameter()) {
13429 // Maybe we will complain about the shadowed template parameter.
13430 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13431 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000013432 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013433 }
13434
13435 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Craig Topperc3ec1492014-05-26 06:22:03 +000013436 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000013437
13438 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000013439 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000013440 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13441 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000013442 ProcessDeclAttributes(TUScope, NewPD, D);
13443 NewPD->setAccess(AS);
13444
13445 if (NewPD->isInvalidDecl())
13446 Record->setInvalidDecl();
13447
13448 if (D.getDeclSpec().isModulePrivateSpecified())
13449 NewPD->setModulePrivate();
13450
13451 if (NewPD->isInvalidDecl() && PrevDecl) {
13452 // Don't introduce NewFD into scope; there's already something
13453 // with the same name in the same scope.
13454 } else if (II) {
13455 PushOnScopeChains(NewPD, S);
13456 } else
13457 Record->addDecl(NewPD);
13458
13459 return NewPD;
13460}