blob: c385e0481baabb43a6e36191b3aedbf98fe6e5c6 [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
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000014#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000015#include "clang/AST/ASTContext.h"
Faisal Vali2b391ab2013-09-26 19:54:12 +000016#include "clang/AST/ASTLambda.h"
Sebastian Redlab238a72011-04-24 16:28:06 +000017#include "clang/AST/ASTMutationListener.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/CharUnits.h"
Richard Trieu4fc85362012-06-14 23:11:34 +000020#include "clang/AST/EvaluatedExprVisitor.h"
Alexis Huntc5575cc2011-02-26 19:13:13 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000022#include "clang/AST/RecordLayout.h"
Douglas Gregor3024f072012-04-16 07:05:22 +000023#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000024#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000025#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000026#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000027#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballman02df2e02012-12-09 17:45:41 +000028#include "clang/Basic/TargetInfo.h"
Richard Smithf4198b72013-07-23 08:14:48 +000029#include "clang/Lex/LiteralSupport.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000030#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/CXXFieldCollector.h"
32#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/Initialization.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/ParsedTemplate.h"
36#include "clang/Sema/Scope.h"
37#include "clang/Sema/ScopeInfo.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000038#include "clang/Sema/SemaInternal.h"
Reid Klecknerd60b82f2014-11-17 23:36:45 +000039#include "clang/Sema/Template.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000040#include "llvm/ADT/STLExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000041#include "llvm/ADT/SmallString.h"
Richard Smith7873de02016-08-11 22:25:46 +000042#include "llvm/ADT/StringExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000043#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000044#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000045
46using namespace clang;
47
Chris Lattner58258242008-04-10 02:22:51 +000048//===----------------------------------------------------------------------===//
49// CheckDefaultArgumentVisitor
50//===----------------------------------------------------------------------===//
51
Chris Lattnerb0d38442008-04-12 23:52:44 +000052namespace {
53 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
54 /// the default argument of a parameter to determine whether it
55 /// contains any ill-formed subexpressions. For example, this will
56 /// diagnose the use of local variables or parameters within the
57 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000058 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000059 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000060 Expr *DefaultArg;
61 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000062
Chris Lattnerb0d38442008-04-12 23:52:44 +000063 public:
Mike Stump11289f42009-09-09 15:08:12 +000064 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000065 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000066
Chris Lattnerb0d38442008-04-12 23:52:44 +000067 bool VisitExpr(Expr *Node);
68 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000069 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0d49512012-02-10 23:30:22 +000070 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall7353c862013-04-09 01:56:28 +000071 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000072 };
Chris Lattner58258242008-04-10 02:22:51 +000073
Chris Lattnerb0d38442008-04-12 23:52:44 +000074 /// VisitExpr - Visit all of the children of this expression.
75 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
76 bool IsInvalid = false;
Benjamin Kramer642f1732015-07-02 21:03:14 +000077 for (Stmt *SubStmt : Node->children())
78 IsInvalid |= Visit(SubStmt);
Chris Lattnerb0d38442008-04-12 23:52:44 +000079 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000080 }
81
Chris Lattnerb0d38442008-04-12 23:52:44 +000082 /// VisitDeclRefExpr - Visit a reference to a declaration, to
83 /// determine whether this declaration can be used in the default
84 /// argument expression.
85 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000086 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000087 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
88 // C++ [dcl.fct.default]p9
89 // Default arguments are evaluated each time the function is
90 // called. The order of evaluation of function arguments is
91 // unspecified. Consequently, parameters of a function shall not
92 // be used in default argument expressions, even if they are not
93 // evaluated. Parameters of a function declared before a default
94 // argument expression are in scope and can hide namespace and
95 // class member names.
Daniel Dunbar62ee6412012-03-09 18:35:03 +000096 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +000097 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000098 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000099 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +0000100 // C++ [dcl.fct.default]p7
101 // Local variables shall not be used in default argument
102 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +0000103 if (VDecl->isLocalVarDecl())
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000104 return S->Diag(DRE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000105 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +0000106 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000107 }
Chris Lattner58258242008-04-10 02:22:51 +0000108
Douglas Gregor8e12c382008-11-04 13:41:56 +0000109 return false;
110 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000111
Douglas Gregor97a9c812008-11-04 14:32:21 +0000112 /// VisitCXXThisExpr - Visit a C++ "this" expression.
113 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
114 // C++ [dcl.fct.default]p8:
115 // The keyword this shall not be used in a default argument of a
116 // member function.
Daniel Dunbar62ee6412012-03-09 18:35:03 +0000117 return S->Diag(ThisE->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000118 diag::err_param_default_argument_references_this)
119 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000120 }
Douglas Gregorf0d49512012-02-10 23:30:22 +0000121
John McCall7353c862013-04-09 01:56:28 +0000122 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
123 bool Invalid = false;
124 for (PseudoObjectExpr::semantics_iterator
125 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
126 Expr *E = *i;
127
128 // Look through bindings.
129 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
130 E = OVE->getSourceExpr();
131 assert(E && "pseudo-object binding without source expression?");
132 }
133
134 Invalid |= Visit(E);
135 }
136 return Invalid;
137 }
138
Douglas Gregorf0d49512012-02-10 23:30:22 +0000139 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
140 // C++11 [expr.lambda.prim]p13:
141 // A lambda-expression appearing in a default argument shall not
142 // implicitly or explicitly capture any entity.
143 if (Lambda->capture_begin() == Lambda->capture_end())
144 return false;
145
Erich Keanebb863642017-09-20 22:28:24 +0000146 return S->Diag(Lambda->getLocStart(),
Douglas Gregorf0d49512012-02-10 23:30:22 +0000147 diag::err_lambda_capture_default_arg);
148 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000149}
Chris Lattner58258242008-04-10 02:22:51 +0000150
Richard Smithb7151b92013-04-10 06:11:48 +0000151void
152Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
153 const CXXMethodDecl *Method) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000154 // If we have an MSAny spec already, don't bother.
155 if (!Method || ComputedEST == EST_MSAny)
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000156 return;
157
158 const FunctionProtoType *Proto
159 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +0000160 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
161 if (!Proto)
162 return;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000163
164 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
165
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000166 // If we have a throw-all spec at this point, ignore the function.
167 if (ComputedEST == EST_None)
168 return;
169
Erich Keane97dfc4a2017-09-28 20:47:10 +0000170 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
171 EST = EST_BasicNoexcept;
172
Davide Italiano1a7f6482015-07-16 22:37:54 +0000173 switch(EST) {
174 // If this function can throw any exceptions, make a note of that.
175 case EST_MSAny:
176 case EST_None:
177 ClearExceptions();
178 ComputedEST = EST;
179 return;
180 // FIXME: If the call to this decl is using any of its default arguments, we
181 // need to search them for potentially-throwing calls.
182 // If this function has a basic noexcept, it doesn't affect the outcome.
183 case EST_BasicNoexcept:
184 return;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000185 // If we're still at noexcept(true) and there's a nothrow() callee,
186 // change to that specification.
Davide Italiano1a7f6482015-07-16 22:37:54 +0000187 case EST_DynamicNone:
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000188 if (ComputedEST == EST_BasicNoexcept)
189 ComputedEST = EST_DynamicNone;
190 return;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000191 // Check out noexcept specs.
Davide Italiano1a7f6482015-07-16 22:37:54 +0000192 case EST_ComputedNoexcept:
193 {
Richard Smithf623c962012-04-17 00:58:00 +0000194 FunctionProtoType::NoexceptResult NR =
195 Proto->getNoexceptSpec(Self->Context);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000196 assert(NR != FunctionProtoType::NR_NoNoexcept &&
197 "Must have noexcept result for EST_ComputedNoexcept.");
198 assert(NR != FunctionProtoType::NR_Dependent &&
199 "Should not generate implicit declarations for dependent cases, "
200 "and don't know how to handle them anyway.");
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000201 // noexcept(false) -> no spec on the new function
202 if (NR == FunctionProtoType::NR_Throw) {
203 ClearExceptions();
204 ComputedEST = EST_None;
205 }
206 // noexcept(true) won't change anything either.
207 return;
208 }
Davide Italiano1a7f6482015-07-16 22:37:54 +0000209 default:
210 break;
211 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000212 assert(EST == EST_Dynamic && "EST case not considered earlier.");
213 assert(ComputedEST != EST_None &&
214 "Shouldn't collect exceptions when throw-all is guaranteed.");
215 ComputedEST = EST_Dynamic;
216 // Record the exceptions in this function's exception specification.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000217 for (const auto &E : Proto->exceptions())
David Blaikie82e95a32014-11-19 07:49:47 +0000218 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000219 Exceptions.push_back(E);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000220}
221
Richard Smith938f40b2011-06-11 17:19:42 +0000222void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000223 if (!E || ComputedEST == EST_MSAny)
Richard Smith938f40b2011-06-11 17:19:42 +0000224 return;
225
226 // FIXME:
227 //
228 // C++0x [except.spec]p14:
NAKAMURA Takumi53648472011-06-21 03:19:28 +0000229 // [An] implicit exception-specification specifies the type-id T if and
230 // only if T is allowed by the exception-specification of a function directly
231 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith938f40b2011-06-11 17:19:42 +0000232 // function it directly invokes allows all exceptions, and f shall allow no
233 // exceptions if every function it directly invokes allows no exceptions.
234 //
235 // Note in particular that if an implicit exception-specification is generated
236 // for a function containing a throw-expression, that specification can still
237 // be noexcept(true).
238 //
239 // Note also that 'directly invoked' is not defined in the standard, and there
240 // is no indication that we should only consider potentially-evaluated calls.
241 //
242 // Ultimately we should implement the intent of the standard: the exception
243 // specification should be the set of exceptions which can be thrown by the
244 // implicit definition. For now, we assume that any non-nothrow expression can
245 // throw any exception.
246
Richard Smithf623c962012-04-17 00:58:00 +0000247 if (Self->canThrow(E))
Richard Smith938f40b2011-06-11 17:19:42 +0000248 ComputedEST = EST_None;
249}
250
Anders Carlssonc80a1272009-08-25 02:29:20 +0000251bool
John McCallb268a282010-08-23 23:25:46 +0000252Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000253 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000254 if (RequireCompleteType(Param->getLocation(), Param->getType(),
255 diag::err_typecheck_decl_incomplete_type)) {
256 Param->setInvalidDecl();
257 return true;
258 }
259
Anders Carlssonc80a1272009-08-25 02:29:20 +0000260 // C++ [dcl.fct.default]p5
261 // A default argument expression is implicitly converted (clause
262 // 4) to the parameter type. The default argument expression has
263 // the same semantic constraints as the initializer expression in
264 // a declaration of a variable of the parameter type, using the
265 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000266 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
267 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000268 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
269 EqualLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000270 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000271 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman5f101b92009-12-22 02:46:13 +0000272 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000273 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000274 Arg = Result.getAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000275
Richard Smithc406cb72013-01-17 01:17:56 +0000276 CheckCompletedExpr(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000277 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000278
Anders Carlssonc80a1272009-08-25 02:29:20 +0000279 // Okay: add the default argument to the parameter
280 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000281
Erich Keanebb863642017-09-20 22:28:24 +0000282 // We have already instantiated this parameter; provide each of the
Douglas Gregor758cb672010-10-12 18:23:32 +0000283 // instantiations with the uninstantiated default argument.
284 UnparsedDefaultArgInstantiationsMap::iterator InstPos
285 = UnparsedDefaultArgInstantiations.find(Param);
286 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
287 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
288 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
Erich Keanebb863642017-09-20 22:28:24 +0000289
Douglas Gregor758cb672010-10-12 18:23:32 +0000290 // We're done tracking this parameter's instantiations.
291 UnparsedDefaultArgInstantiations.erase(InstPos);
292 }
Erich Keanebb863642017-09-20 22:28:24 +0000293
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000294 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000295}
296
Chris Lattner58258242008-04-10 02:22:51 +0000297/// ActOnParamDefaultArgument - Check whether the default argument
298/// provided for a function parameter is well-formed. If so, attach it
299/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000300void
John McCall48871652010-08-21 09:40:31 +0000301Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000302 Expr *DefaultArg) {
303 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000304 return;
Mike Stump11289f42009-09-09 15:08:12 +0000305
John McCall48871652010-08-21 09:40:31 +0000306 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000307 UnparsedDefaultArgLocs.erase(Param);
308
Chris Lattner199abbc2008-04-08 05:04:30 +0000309 // Default arguments are only permitted in C++
David Blaikiebbafb8a2012-03-11 07:00:24 +0000310 if (!getLangOpts().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000311 Diag(EqualLoc, diag::err_param_default_argument)
312 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000313 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000314 return;
315 }
316
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000317 // Check for unexpanded parameter packs.
318 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
319 Param->setInvalidDecl();
320 return;
Benjamin Kramer3b8044c2015-03-27 13:58:31 +0000321 }
322
323 // C++11 [dcl.fct.default]p3
324 // A default argument expression [...] shall not be specified for a
325 // parameter pack.
326 if (Param->isParameterPack()) {
327 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
328 << DefaultArg->getSourceRange();
329 return;
330 }
331
Anders Carlssonf1c26952009-08-25 01:02:06 +0000332 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000333 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
334 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000335 Param->setInvalidDecl();
336 return;
337 }
Mike Stump11289f42009-09-09 15:08:12 +0000338
John McCallb268a282010-08-23 23:25:46 +0000339 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000340}
341
Douglas Gregor58354032008-12-24 00:01:03 +0000342/// ActOnParamUnparsedDefaultArgument - We've seen a default
343/// argument for a function parameter, but we can't parse it yet
344/// because we're inside a class definition. Note that this default
345/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000346void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000347 SourceLocation EqualLoc,
348 SourceLocation ArgLoc) {
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);
Nick Lewycky0f292892013-09-22 10:06:57 +0000353 Param->setUnparsedDefaultArg();
Anders Carlsson84613c42009-06-12 16:51:40 +0000354 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000355}
356
Douglas Gregor4d87df52008-12-16 21:30:33 +0000357/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
358/// the default argument for the parameter param failed.
Serge Pavlovb4b35782014-07-22 01:54:49 +0000359void Sema::ActOnParamDefaultArgumentError(Decl *param,
360 SourceLocation EqualLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000361 if (!param)
362 return;
Mike Stump11289f42009-09-09 15:08:12 +0000363
John McCall48871652010-08-21 09:40:31 +0000364 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000365 Param->setInvalidDecl();
Anders Carlsson84613c42009-06-12 16:51:40 +0000366 UnparsedDefaultArgLocs.erase(Param);
Serge Pavlovb4b35782014-07-22 01:54:49 +0000367 Param->setDefaultArg(new(Context)
Fariborz Jahanian7bd22e92014-10-01 18:03:51 +0000368 OpaqueValueExpr(EqualLoc,
369 Param->getType().getNonReferenceType(),
370 VK_RValue));
Douglas Gregor4d87df52008-12-16 21:30:33 +0000371}
372
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000373/// CheckExtraCXXDefaultArguments - Check for any extra default
374/// arguments in the declarator, which is not a function declaration
375/// or definition and therefore is not permitted to have default
376/// arguments. This routine should be invoked for every declarator
377/// that is not a function declaration or definition.
378void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
379 // C++ [dcl.fct.default]p3
380 // A default argument expression shall be specified only in the
381 // parameter-declaration-clause of a function declaration or in a
382 // template-parameter (14.1). It shall not be specified for a
383 // parameter pack. If it is specified in a
384 // parameter-declaration-clause, it shall not occur within a
385 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000386 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattner83f095c2009-03-28 19:18:32 +0000387 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000388 DeclaratorChunk &chunk = D.getTypeObject(i);
389 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000390 if (MightBeFunction) {
391 // This is a function declaration. It can have default arguments, but
392 // keep looking in case its return type is a function type with default
393 // arguments.
394 MightBeFunction = false;
395 continue;
396 }
Alp Tokerc5350722014-02-26 22:27:52 +0000397 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
398 ++argIdx) {
399 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000400 if (Param->hasUnparsedDefaultArg()) {
Malcolm Parsonsca9d8342016-11-17 21:00:09 +0000401 std::unique_ptr<CachedTokens> Toks =
402 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
David Majnemerb3c6d522015-01-13 07:42:33 +0000403 SourceRange SR;
404 if (Toks->size() > 1)
405 SR = SourceRange((*Toks)[1].getLocation(),
406 Toks->back().getLocation());
407 else
408 SR = UnparsedDefaultArgLocs[Param];
Douglas Gregor4d87df52008-12-16 21:30:33 +0000409 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
David Majnemerb3c6d522015-01-13 07:42:33 +0000410 << SR;
Douglas Gregor58354032008-12-24 00:01:03 +0000411 } else if (Param->getDefaultArg()) {
412 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
413 << Param->getDefaultArg()->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +0000414 Param->setDefaultArg(nullptr);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000415 }
416 }
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000417 } else if (chunk.Kind != DeclaratorChunk::Paren) {
418 MightBeFunction = false;
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000419 }
420 }
421}
422
David Majnemer502b0ed2013-06-25 23:09:30 +0000423static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
424 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
425 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
426 if (!PVD->hasDefaultArg())
427 return false;
428 if (!PVD->hasInheritedDefaultArg())
429 return true;
430 }
431 return false;
432}
433
Craig Toppere4794282012-09-21 04:33:26 +0000434/// MergeCXXFunctionDecl - Merge two declarations of the same C++
435/// function, once we already know that they have the same
436/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
437/// error, false otherwise.
James Molloye9430032012-03-13 08:55:35 +0000438bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
439 Scope *S) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000440 bool Invalid = false;
441
Richard Smithc7d48d12015-05-20 17:50:35 +0000442 // The declaration context corresponding to the scope is the semantic
443 // parent, unless this is a local function declaration, in which case
444 // it is that surrounding function.
445 DeclContext *ScopeDC = New->isLocalExternDecl()
446 ? New->getLexicalDeclContext()
447 : New->getDeclContext();
448
449 // Find the previous declaration for the purpose of default arguments.
450 FunctionDecl *PrevForDefaultArgs = Old;
451 for (/**/; PrevForDefaultArgs;
452 // Don't bother looking back past the latest decl if this is a local
453 // extern declaration; nothing else could work.
454 PrevForDefaultArgs = New->isLocalExternDecl()
455 ? nullptr
456 : PrevForDefaultArgs->getPreviousDecl()) {
457 // Ignore hidden declarations.
458 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
459 continue;
460
461 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
462 !New->isCXXClassMember()) {
463 // Ignore default arguments of old decl if they are not in
464 // the same scope and this is not an out-of-line definition of
465 // a member function.
466 continue;
467 }
468
469 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
470 // If only one of these is a local function declaration, then they are
471 // declared in different scopes, even though isDeclInScope may think
472 // they're in the same scope. (If both are local, the scope check is
Simon Pilgrim2c518802017-03-30 14:13:19 +0000473 // sufficient, and if neither is local, then they are in the same scope.)
Richard Smithc7d48d12015-05-20 17:50:35 +0000474 continue;
475 }
476
Nico Webera6916892016-06-10 18:53:04 +0000477 // We found the right previous declaration.
Richard Smithc7d48d12015-05-20 17:50:35 +0000478 break;
479 }
480
Chris Lattner199abbc2008-04-08 05:04:30 +0000481 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000482 // For non-template functions, default arguments can be added in
483 // later declarations of a function in the same
484 // scope. Declarations in different scopes have completely
485 // distinct sets of default arguments. That is, declarations in
486 // inner scopes do not acquire default arguments from
487 // declarations in outer scopes, and vice versa. In a given
488 // function declaration, all parameters subsequent to a
489 // parameter with a default argument shall have default
490 // arguments supplied in this or previous declarations. A
491 // default argument shall not be redefined by a later
492 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000493 //
494 // C++ [dcl.fct.default]p6:
Richard Smith541b38b2013-09-20 01:15:31 +0000495 // Except for member functions of class templates, the default arguments
496 // in a member function definition that appears outside of the class
497 // definition are added to the set of default arguments provided by the
Douglas Gregorc732aba2009-09-11 18:44:32 +0000498 // member function declaration in the class definition.
Richard Smithc7d48d12015-05-20 17:50:35 +0000499 for (unsigned p = 0, NumParams = PrevForDefaultArgs
500 ? PrevForDefaultArgs->getNumParams()
501 : 0;
502 p < NumParams; ++p) {
503 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
Chris Lattner199abbc2008-04-08 05:04:30 +0000504 ParmVarDecl *NewParam = New->getParamDecl(p);
505
Richard Smithc7d48d12015-05-20 17:50:35 +0000506 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
James Molloye9430032012-03-13 08:55:35 +0000507 bool NewParamHasDfl = NewParam->hasDefaultArg();
508
James Molloye9430032012-03-13 08:55:35 +0000509 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000510 unsigned DiagDefaultParamID =
511 diag::err_param_default_argument_redefinition;
512
513 // MSVC accepts that default parameters be redefined for member functions
514 // of template class. The new default parameter's value is ignored.
515 Invalid = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000516 if (getLangOpts().MicrosoftExt) {
Richard Smithc7d48d12015-05-20 17:50:35 +0000517 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000518 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000519 // Merge the old default argument into the new parameter.
520 NewParam->setHasInheritedDefaultArg();
521 if (OldParam->hasUninstantiatedDefaultArg())
522 NewParam->setUninstantiatedDefaultArg(
523 OldParam->getUninstantiatedDefaultArg());
524 else
525 NewParam->setDefaultArg(OldParam->getInit());
Richard Smith1b98ccc2014-07-19 01:39:17 +0000526 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000527 Invalid = false;
528 }
529 }
Erich Keanebb863642017-09-20 22:28:24 +0000530
531 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
Francois Pichet8cb243a2011-04-10 04:58:30 +0000532 // hint here. Alternatively, we could walk the type-source information
533 // for NewParam to find the last source location in the type... but it
534 // isn't worth the effort right now. This is the kind of test case that
535 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000536 // int f(int);
537 // void g(int (*fp)(int) = f);
538 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000539 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000540 << NewParam->getDefaultArgRange();
Erich Keanebb863642017-09-20 22:28:24 +0000541
Douglas Gregorc732aba2009-09-11 18:44:32 +0000542 // Look for the function declaration where the default argument was
543 // actually written, which may be a declaration prior to Old.
Richard Smithc7d48d12015-05-20 17:50:35 +0000544 for (auto Older = PrevForDefaultArgs;
545 OldParam->hasInheritedDefaultArg(); /**/) {
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000546 Older = Older->getPreviousDecl();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000547 OldParam = Older->getParamDecl(p);
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000548 }
549
Douglas Gregorc732aba2009-09-11 18:44:32 +0000550 Diag(OldParam->getLocation(), diag::note_previous_definition)
551 << OldParam->getDefaultArgRange();
James Molloye9430032012-03-13 08:55:35 +0000552 } else if (OldParamHasDfl) {
Serge Pavlov79271ab2017-06-08 06:31:19 +0000553 // Merge the old default argument into the new parameter unless the new
554 // function is a friend declaration in a template class. In the latter
555 // case the default arguments will be inherited when the friend
556 // declaration will be instantiated.
557 if (New->getFriendObjectKind() == Decl::FOK_None ||
558 !New->getLexicalDeclContext()->isDependentContext()) {
559 // It's important to use getInit() here; getDefaultArg()
560 // strips off any top-level ExprWithCleanups.
561 NewParam->setHasInheritedDefaultArg();
562 if (OldParam->hasUnparsedDefaultArg())
563 NewParam->setUnparsedDefaultArg();
564 else if (OldParam->hasUninstantiatedDefaultArg())
565 NewParam->setUninstantiatedDefaultArg(
566 OldParam->getUninstantiatedDefaultArg());
567 else
568 NewParam->setDefaultArg(OldParam->getInit());
569 }
James Molloye9430032012-03-13 08:55:35 +0000570 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000571 if (New->getDescribedFunctionTemplate()) {
572 // Paragraph 4, quoted above, only applies to non-template functions.
573 Diag(NewParam->getLocation(),
574 diag::err_param_default_argument_template_redecl)
575 << NewParam->getDefaultArgRange();
Richard Smithc7d48d12015-05-20 17:50:35 +0000576 Diag(PrevForDefaultArgs->getLocation(),
577 diag::note_template_prev_declaration)
578 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000579 } else if (New->getTemplateSpecializationKind()
580 != TSK_ImplicitInstantiation &&
581 New->getTemplateSpecializationKind() != TSK_Undeclared) {
582 // C++ [temp.expr.spec]p21:
583 // Default function arguments shall not be specified in a declaration
584 // or a definition for one of the following explicit specializations:
585 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000586 // - the explicit specialization of a member function template;
Erich Keanebb863642017-09-20 22:28:24 +0000587 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000588 // template where the class template specialization to which the
Erich Keanebb863642017-09-20 22:28:24 +0000589 // member function specialization belongs is implicitly
Douglas Gregor62e10f02009-10-13 17:02:54 +0000590 // instantiated.
591 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
592 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
593 << New->getDeclName()
594 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000595 } else if (New->getDeclContext()->isDependentContext()) {
596 // C++ [dcl.fct.default]p6 (DR217):
Erich Keanebb863642017-09-20 22:28:24 +0000597 // Default arguments for a member function of a class template shall
598 // be specified on the initial declaration of the member function
Douglas Gregorc732aba2009-09-11 18:44:32 +0000599 // within the class template.
600 //
Erich Keanebb863642017-09-20 22:28:24 +0000601 // Reading the tea leaves a bit in DR217 and its reference to DR205
602 // leads me to the conclusion that one cannot add default function
603 // arguments for an out-of-line definition of a member function of a
Douglas Gregorc732aba2009-09-11 18:44:32 +0000604 // dependent type.
605 int WhichKind = 2;
Erich Keanebb863642017-09-20 22:28:24 +0000606 if (CXXRecordDecl *Record
Douglas Gregorc732aba2009-09-11 18:44:32 +0000607 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
608 if (Record->getDescribedClassTemplate())
609 WhichKind = 0;
610 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
611 WhichKind = 1;
612 else
613 WhichKind = 2;
614 }
Erich Keanebb863642017-09-20 22:28:24 +0000615
616 Diag(NewParam->getLocation(),
Douglas Gregorc732aba2009-09-11 18:44:32 +0000617 diag::err_param_default_argument_member_template_redecl)
618 << WhichKind
619 << NewParam->getDefaultArgRange();
620 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000621 }
622 }
623
Richard Smith58c3cc12012-11-28 03:45:24 +0000624 // DR1344: If a default argument is added outside a class definition and that
625 // default argument makes the function a special member function, the program
626 // is ill-formed. This can only happen for constructors.
627 if (isa<CXXConstructorDecl>(New) &&
628 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
629 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
630 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
631 if (NewSM != OldSM) {
632 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
633 assert(NewParam->hasDefaultArg());
634 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
635 << NewParam->getDefaultArgRange() << NewSM;
636 Diag(Old->getLocation(), diag::note_previous_declaration);
637 }
638 }
639
David Majnemeree4f4022014-03-30 06:44:54 +0000640 const FunctionDecl *Def;
Richard Smith5b8b3db2012-02-20 23:28:05 +0000641 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000642 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000643 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000644 if (New->isConstexpr() != Old->isConstexpr()) {
645 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
646 << New << New->isConstexpr();
647 Diag(Old->getLocation(), diag::note_previous_declaration);
648 Invalid = true;
Reid Kleckner93864172015-04-08 00:04:47 +0000649 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
Serge Pavlov673f44c2017-06-08 06:07:07 +0000650 Old->isDefined(Def) &&
651 // If a friend function is inlined but does not have 'inline'
652 // specifier, it is a definition. Do not report attribute conflict
653 // in this case, redefinition will be diagnosed later.
654 (New->isInlineSpecified() ||
655 New->getFriendObjectKind() == Decl::FOK_None)) {
David Majnemeree4f4022014-03-30 06:44:54 +0000656 // C++11 [dcl.fcn.spec]p4:
657 // If the definition of a function appears in a translation unit before its
658 // first declaration as inline, the program is ill-formed.
659 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
660 Diag(Def->getLocation(), diag::note_previous_definition);
661 Invalid = true;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000662 }
663
Richard Smithafe4aa82017-02-10 02:19:05 +0000664 // FIXME: It's not clear what should happen if multiple declarations of a
665 // deduction guide have different explicitness. For now at least we simply
666 // reject any case where the explicitness changes.
Richard Smithbc491202017-02-17 20:05:37 +0000667 auto *NewGuide = dyn_cast<CXXDeductionGuideDecl>(New);
668 if (NewGuide && NewGuide->isExplicitSpecified() !=
669 cast<CXXDeductionGuideDecl>(Old)->isExplicitSpecified()) {
Richard Smithafe4aa82017-02-10 02:19:05 +0000670 Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch)
Richard Smithbc491202017-02-17 20:05:37 +0000671 << NewGuide->isExplicitSpecified();
Richard Smithafe4aa82017-02-10 02:19:05 +0000672 Diag(Old->getLocation(), diag::note_previous_declaration);
673 }
674
David Majnemer502b0ed2013-06-25 23:09:30 +0000675 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000676 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000677 // the only declaration of the function or function template in the
678 // translation unit.
679 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
680 functionDeclHasDefaultArgument(Old)) {
681 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
682 Diag(Old->getLocation(), diag::note_previous_declaration);
683 Invalid = true;
684 }
685
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000686 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000687}
688
Richard Smith7873de02016-08-11 22:25:46 +0000689NamedDecl *
690Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
691 MultiTemplateParamsArg TemplateParamLists) {
692 assert(D.isDecompositionDeclarator());
693 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
694
695 // The syntax only allows a decomposition declarator as a simple-declaration
696 // or a for-range-declaration, but we parse it in more cases than that.
697 if (!D.mayHaveDecompositionDeclarator()) {
698 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
699 << Decomp.getSourceRange();
700 return nullptr;
701 }
702
703 if (!TemplateParamLists.empty()) {
704 // FIXME: There's no rule against this, but there are also no rules that
705 // would actually make it usable, so we reject it for now.
706 Diag(TemplateParamLists.front()->getTemplateLoc(),
707 diag::err_decomp_decl_template);
708 return nullptr;
709 }
710
711 Diag(Decomp.getLSquareLoc(), getLangOpts().CPlusPlus1z
712 ? diag::warn_cxx14_compat_decomp_decl
713 : diag::ext_decomp_decl)
714 << Decomp.getSourceRange();
715
716 // The semantic context is always just the current context.
717 DeclContext *const DC = CurContext;
718
719 // C++1z [dcl.dcl]/8:
720 // The decl-specifier-seq shall contain only the type-specifier auto
721 // and cv-qualifiers.
722 auto &DS = D.getDeclSpec();
723 {
724 SmallVector<StringRef, 8> BadSpecifiers;
725 SmallVector<SourceLocation, 8> BadSpecifierLocs;
726 if (auto SCS = DS.getStorageClassSpec()) {
727 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
728 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
729 }
730 if (auto TSCS = DS.getThreadStorageClassSpec()) {
731 BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
732 BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
733 }
734 if (DS.isConstexprSpecified()) {
735 BadSpecifiers.push_back("constexpr");
736 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
737 }
738 if (DS.isInlineSpecified()) {
739 BadSpecifiers.push_back("inline");
740 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
741 }
742 if (!BadSpecifiers.empty()) {
743 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
744 Err << (int)BadSpecifiers.size()
745 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
746 // Don't add FixItHints to remove the specifiers; we do still respect
747 // them when building the underlying variable.
748 for (auto Loc : BadSpecifierLocs)
749 Err << SourceRange(Loc, Loc);
750 }
751 // We can't recover from it being declared as a typedef.
752 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
753 return nullptr;
754 }
755
756 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
757 QualType R = TInfo->getType();
758
759 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
760 UPPC_DeclarationType))
761 D.setInvalidType();
762
763 // The syntax only allows a single ref-qualifier prior to the decomposition
764 // declarator. No other declarator chunks are permitted. Also check the type
765 // specifier here.
766 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
767 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
768 (D.getNumTypeObjects() == 1 &&
769 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
770 Diag(Decomp.getLSquareLoc(),
771 (D.hasGroupingParens() ||
772 (D.getNumTypeObjects() &&
773 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
774 ? diag::err_decomp_decl_parens
775 : diag::err_decomp_decl_type)
776 << R;
777
778 // In most cases, there's no actual problem with an explicitly-specified
779 // type, but a function type won't work here, and ActOnVariableDeclarator
780 // shouldn't be called for such a type.
781 if (R->isFunctionType())
782 D.setInvalidType();
783 }
784
785 // Build the BindingDecls.
786 SmallVector<BindingDecl*, 8> Bindings;
787
788 // Build the BindingDecls.
789 for (auto &B : D.getDecompositionDeclarator().bindings()) {
790 // Check for name conflicts.
791 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
792 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +0000793 ForVisibleRedeclaration);
Richard Smith7873de02016-08-11 22:25:46 +0000794 LookupName(Previous, S,
795 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
796
797 // It's not permitted to shadow a template parameter name.
798 if (Previous.isSingleResult() &&
799 Previous.getFoundDecl()->isTemplateParameter()) {
800 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
801 Previous.getFoundDecl());
802 Previous.clear();
803 }
804
805 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
806 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
807 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
808 /*AllowInlineNamespace*/false);
809 if (!Previous.empty()) {
810 auto *Old = Previous.getRepresentativeDecl();
811 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
812 Diag(Old->getLocation(), diag::note_previous_definition);
813 }
814
Richard Smith32cb8c92016-08-12 00:53:41 +0000815 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
Richard Smith7873de02016-08-11 22:25:46 +0000816 PushOnScopeChains(BD, S, true);
817 Bindings.push_back(BD);
818 ParsingInitForAutoVars.insert(BD);
819 }
820
821 // There are no prior lookup results for the variable itself, because it
822 // is unnamed.
823 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
824 Decomp.getLSquareLoc());
Richard Smithbecb92d2017-10-10 22:33:17 +0000825 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
826 ForVisibleRedeclaration);
Richard Smith7873de02016-08-11 22:25:46 +0000827
828 // Build the variable that holds the non-decomposed object.
829 bool AddToScope = true;
830 NamedDecl *New =
831 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
832 MultiTemplateParamsArg(), AddToScope, Bindings);
Richard Smith81df9eb2017-10-02 22:43:36 +0000833 if (AddToScope) {
834 S->AddDecl(New);
835 CurContext->addHiddenDecl(New);
836 }
Richard Smith7873de02016-08-11 22:25:46 +0000837
838 if (isInOpenMPDeclareTargetContext())
839 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
840
841 return New;
842}
843
844static bool checkSimpleDecomposition(
845 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
Benjamin Kramer6ca15b62016-11-24 15:36:17 +0000846 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
Richard Smith7873de02016-08-11 22:25:46 +0000847 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
848 if ((int64_t)Bindings.size() != NumElems) {
849 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
850 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
851 << (NumElems < Bindings.size());
852 return true;
853 }
854
855 unsigned I = 0;
856 for (auto *B : Bindings) {
857 SourceLocation Loc = B->getLocation();
858 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
859 if (E.isInvalid())
860 return true;
861 E = GetInit(Loc, E.get(), I++);
862 if (E.isInvalid())
863 return true;
864 B->setBinding(ElemType, E.get());
865 }
866
867 return false;
868}
869
870static bool checkArrayLikeDecomposition(Sema &S,
871 ArrayRef<BindingDecl *> Bindings,
872 ValueDecl *Src, QualType DecompType,
Benjamin Kramer6ca15b62016-11-24 15:36:17 +0000873 const llvm::APSInt &NumElems,
Richard Smith7873de02016-08-11 22:25:46 +0000874 QualType ElemType) {
875 return checkSimpleDecomposition(
876 S, Bindings, Src, DecompType, NumElems, ElemType,
877 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
878 ExprResult E = S.ActOnIntegerConstant(Loc, I);
879 if (E.isInvalid())
880 return ExprError();
881 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
882 });
883}
884
885static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
886 ValueDecl *Src, QualType DecompType,
887 const ConstantArrayType *CAT) {
888 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
889 llvm::APSInt(CAT->getSize()),
890 CAT->getElementType());
891}
892
893static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
894 ValueDecl *Src, QualType DecompType,
895 const VectorType *VT) {
896 return checkArrayLikeDecomposition(
897 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
898 S.Context.getQualifiedType(VT->getElementType(),
899 DecompType.getQualifiers()));
900}
901
902static bool checkComplexDecomposition(Sema &S,
903 ArrayRef<BindingDecl *> Bindings,
904 ValueDecl *Src, QualType DecompType,
905 const ComplexType *CT) {
906 return checkSimpleDecomposition(
907 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
908 S.Context.getQualifiedType(CT->getElementType(),
909 DecompType.getQualifiers()),
910 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
911 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
912 });
913}
914
915static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
916 TemplateArgumentListInfo &Args) {
917 SmallString<128> SS;
918 llvm::raw_svector_ostream OS(SS);
919 bool First = true;
920 for (auto &Arg : Args.arguments()) {
921 if (!First)
922 OS << ", ";
923 Arg.getArgument().print(PrintingPolicy, OS);
924 First = false;
925 }
926 return OS.str();
927}
928
929static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
930 SourceLocation Loc, StringRef Trait,
931 TemplateArgumentListInfo &Args,
932 unsigned DiagID) {
933 auto DiagnoseMissing = [&] {
934 if (DiagID)
935 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
936 Args);
937 return true;
938 };
939
940 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
941 NamespaceDecl *Std = S.getStdNamespace();
942 if (!Std)
943 return DiagnoseMissing();
944
945 // Look up the trait itself, within namespace std. We can diagnose various
946 // problems with this lookup even if we've been asked to not diagnose a
947 // missing specialization, because this can only fail if the user has been
948 // declaring their own names in namespace std or we don't support the
949 // standard library implementation in use.
950 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
951 Loc, Sema::LookupOrdinaryName);
952 if (!S.LookupQualifiedName(Result, Std))
953 return DiagnoseMissing();
954 if (Result.isAmbiguous())
955 return true;
956
957 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
958 if (!TraitTD) {
959 Result.suppressDiagnostics();
960 NamedDecl *Found = *Result.begin();
961 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
962 S.Diag(Found->getLocation(), diag::note_declared_at);
963 return true;
964 }
965
966 // Build the template-id.
967 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
968 if (TraitTy.isNull())
969 return true;
970 if (!S.isCompleteType(Loc, TraitTy)) {
971 if (DiagID)
972 S.RequireCompleteType(
973 Loc, TraitTy, DiagID,
974 printTemplateArgs(S.Context.getPrintingPolicy(), Args));
975 return true;
976 }
977
978 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
979 assert(RD && "specialization of class template is not a class?");
980
981 // Look up the member of the trait type.
982 S.LookupQualifiedName(TraitMemberLookup, RD);
983 return TraitMemberLookup.isAmbiguous();
984}
985
986static TemplateArgumentLoc
987getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
988 uint64_t I) {
989 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
990 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
991}
992
993static TemplateArgumentLoc
994getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
995 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
996}
997
998namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
999
1000static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1001 llvm::APSInt &Size) {
Faisal Valid143a0c2017-04-01 21:30:49 +00001002 EnterExpressionEvaluationContext ContextRAII(
1003 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Richard Smith7873de02016-08-11 22:25:46 +00001004
1005 DeclarationName Value = S.PP.getIdentifierInfo("value");
1006 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1007
1008 // Form template argument list for tuple_size<T>.
1009 TemplateArgumentListInfo Args(Loc, Loc);
1010 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1011
1012 // If there's no tuple_size specialization, it's not tuple-like.
1013 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
1014 return IsTupleLike::NotTupleLike;
1015
Richard Smith208732e2016-12-08 03:24:55 +00001016 // If we get this far, we've committed to the tuple interpretation, but
1017 // we can still fail if there actually isn't a usable ::value.
Richard Smith7873de02016-08-11 22:25:46 +00001018
1019 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1020 LookupResult &R;
1021 TemplateArgumentListInfo &Args;
1022 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1023 : R(R), Args(Args) {}
1024 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1025 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1026 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1027 }
1028 } Diagnoser(R, Args);
1029
1030 if (R.empty()) {
1031 Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1032 return IsTupleLike::Error;
1033 }
1034
1035 ExprResult E =
1036 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1037 if (E.isInvalid())
1038 return IsTupleLike::Error;
1039
1040 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1041 if (E.isInvalid())
1042 return IsTupleLike::Error;
1043
1044 return IsTupleLike::TupleLike;
1045}
1046
1047/// \return std::tuple_element<I, T>::type.
1048static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1049 unsigned I, QualType T) {
1050 // Form template argument list for tuple_element<I, T>.
1051 TemplateArgumentListInfo Args(Loc, Loc);
1052 Args.addArgument(
1053 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1054 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1055
1056 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1057 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1058 if (lookupStdTypeTraitMember(
1059 S, R, Loc, "tuple_element", Args,
1060 diag::err_decomp_decl_std_tuple_element_not_specialized))
1061 return QualType();
1062
1063 auto *TD = R.getAsSingle<TypeDecl>();
1064 if (!TD) {
1065 R.suppressDiagnostics();
1066 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1067 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1068 if (!R.empty())
1069 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1070 return QualType();
1071 }
1072
1073 return S.Context.getTypeDeclType(TD);
1074}
1075
1076namespace {
1077struct BindingDiagnosticTrap {
1078 Sema &S;
1079 DiagnosticErrorTrap Trap;
1080 BindingDecl *BD;
1081
1082 BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1083 : S(S), Trap(S.Diags), BD(BD) {}
1084 ~BindingDiagnosticTrap() {
1085 if (Trap.hasErrorOccurred())
1086 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1087 }
1088};
1089}
1090
Richard Smith3997b1b2016-08-12 01:55:21 +00001091static bool checkTupleLikeDecomposition(Sema &S,
1092 ArrayRef<BindingDecl *> Bindings,
Richard Smith97fcf4b2016-08-14 23:15:52 +00001093 VarDecl *Src, QualType DecompType,
Benjamin Kramer6ca15b62016-11-24 15:36:17 +00001094 const llvm::APSInt &TupleSize) {
Richard Smith7873de02016-08-11 22:25:46 +00001095 if ((int64_t)Bindings.size() != TupleSize) {
1096 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1097 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1098 << (TupleSize < Bindings.size());
1099 return true;
1100 }
1101
1102 if (Bindings.empty())
1103 return false;
1104
1105 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1106
1107 // [dcl.decomp]p3:
1108 // The unqualified-id get is looked up in the scope of E by class member
1109 // access lookup
1110 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1111 bool UseMemberGet = false;
1112 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1113 if (auto *RD = DecompType->getAsCXXRecordDecl())
1114 S.LookupQualifiedName(MemberGet, RD);
1115 if (MemberGet.isAmbiguous())
1116 return true;
1117 UseMemberGet = !MemberGet.empty();
1118 S.FilterAcceptableTemplateNames(MemberGet);
1119 }
1120
1121 unsigned I = 0;
1122 for (auto *B : Bindings) {
1123 BindingDiagnosticTrap Trap(S, B);
1124 SourceLocation Loc = B->getLocation();
1125
1126 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1127 if (E.isInvalid())
1128 return true;
1129
1130 // e is an lvalue if the type of the entity is an lvalue reference and
1131 // an xvalue otherwise
1132 if (!Src->getType()->isLValueReferenceType())
1133 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1134 E.get(), nullptr, VK_XValue);
1135
1136 TemplateArgumentListInfo Args(Loc, Loc);
1137 Args.addArgument(
1138 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1139
1140 if (UseMemberGet) {
1141 // if [lookup of member get] finds at least one declaration, the
1142 // initializer is e.get<i-1>().
1143 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1144 CXXScopeSpec(), SourceLocation(), nullptr,
1145 MemberGet, &Args, nullptr);
1146 if (E.isInvalid())
1147 return true;
1148
1149 E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
1150 } else {
1151 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1152 // in the associated namespaces.
1153 Expr *Get = UnresolvedLookupExpr::Create(
1154 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1155 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1156 UnresolvedSetIterator(), UnresolvedSetIterator());
1157
1158 Expr *Arg = E.get();
1159 E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
1160 }
1161 if (E.isInvalid())
1162 return true;
1163 Expr *Init = E.get();
1164
1165 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1166 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1167 if (T.isNull())
1168 return true;
1169
1170 // each vi is a variable of type "reference to T" initialized with the
1171 // initializer, where the reference is an lvalue reference if the
1172 // initializer is an lvalue and an rvalue reference otherwise
1173 QualType RefType =
1174 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1175 if (RefType.isNull())
1176 return true;
Richard Smith97fcf4b2016-08-14 23:15:52 +00001177 auto *RefVD = VarDecl::Create(
1178 S.Context, Src->getDeclContext(), Loc, Loc,
1179 B->getDeclName().getAsIdentifierInfo(), RefType,
1180 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1181 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1182 RefVD->setTSCSpec(Src->getTSCSpec());
1183 RefVD->setImplicit();
1184 if (Src->isInlineSpecified())
1185 RefVD->setInlineSpecified();
Richard Smithda383632016-08-15 01:33:41 +00001186 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
Richard Smith7873de02016-08-11 22:25:46 +00001187
Richard Smith97fcf4b2016-08-14 23:15:52 +00001188 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
Richard Smith7873de02016-08-11 22:25:46 +00001189 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1190 InitializationSequence Seq(S, Entity, Kind, Init);
1191 E = Seq.Perform(S, Entity, Kind, Init);
1192 if (E.isInvalid())
1193 return true;
Richard Smithda383632016-08-15 01:33:41 +00001194 E = S.ActOnFinishFullExpr(E.get(), Loc);
1195 if (E.isInvalid())
1196 return true;
Richard Smith97fcf4b2016-08-14 23:15:52 +00001197 RefVD->setInit(E.get());
1198 RefVD->checkInitIsICE();
1199
Richard Smith97fcf4b2016-08-14 23:15:52 +00001200 E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1201 DeclarationNameInfo(B->getDeclName(), Loc),
1202 RefVD);
1203 if (E.isInvalid())
1204 return true;
Richard Smith7873de02016-08-11 22:25:46 +00001205
1206 B->setBinding(T, E.get());
1207 I++;
1208 }
1209
1210 return false;
1211}
1212
1213/// Find the base class to decompose in a built-in decomposition of a class type.
1214/// This base class search is, unfortunately, not quite like any other that we
1215/// perform anywhere else in C++.
1216static const CXXRecordDecl *findDecomposableBaseClass(Sema &S,
1217 SourceLocation Loc,
1218 const CXXRecordDecl *RD,
1219 CXXCastPath &BasePath) {
1220 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1221 CXXBasePath &Path) {
1222 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1223 };
1224
1225 const CXXRecordDecl *ClassWithFields = nullptr;
1226 if (RD->hasDirectFields())
1227 // [dcl.decomp]p4:
1228 // Otherwise, all of E's non-static data members shall be public direct
1229 // members of E ...
1230 ClassWithFields = RD;
1231 else {
1232 // ... or of ...
1233 CXXBasePaths Paths;
1234 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1235 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1236 // If no classes have fields, just decompose RD itself. (This will work
1237 // if and only if zero bindings were provided.)
1238 return RD;
1239 }
1240
1241 CXXBasePath *BestPath = nullptr;
1242 for (auto &P : Paths) {
1243 if (!BestPath)
1244 BestPath = &P;
1245 else if (!S.Context.hasSameType(P.back().Base->getType(),
1246 BestPath->back().Base->getType())) {
1247 // ... the same ...
1248 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1249 << false << RD << BestPath->back().Base->getType()
1250 << P.back().Base->getType();
1251 return nullptr;
1252 } else if (P.Access < BestPath->Access) {
1253 BestPath = &P;
1254 }
1255 }
1256
1257 // ... unambiguous ...
1258 QualType BaseType = BestPath->back().Base->getType();
1259 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1260 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1261 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1262 return nullptr;
1263 }
1264
1265 // ... public base class of E.
1266 if (BestPath->Access != AS_public) {
1267 S.Diag(Loc, diag::err_decomp_decl_non_public_base)
1268 << RD << BaseType;
1269 for (auto &BS : *BestPath) {
1270 if (BS.Base->getAccessSpecifier() != AS_public) {
1271 S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path)
1272 << (BS.Base->getAccessSpecifier() == AS_protected)
1273 << (BS.Base->getAccessSpecifierAsWritten() == AS_none);
1274 break;
1275 }
1276 }
1277 return nullptr;
1278 }
1279
1280 ClassWithFields = BaseType->getAsCXXRecordDecl();
1281 S.BuildBasePathArray(Paths, BasePath);
1282 }
1283
1284 // The above search did not check whether the selected class itself has base
1285 // classes with fields, so check that now.
1286 CXXBasePaths Paths;
1287 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1288 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1289 << (ClassWithFields == RD) << RD << ClassWithFields
1290 << Paths.front().back().Base->getType();
1291 return nullptr;
1292 }
1293
1294 return ClassWithFields;
1295}
1296
1297static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1298 ValueDecl *Src, QualType DecompType,
1299 const CXXRecordDecl *RD) {
1300 CXXCastPath BasePath;
1301 RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath);
1302 if (!RD)
1303 return true;
1304 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1305 DecompType.getQualifiers());
1306
1307 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
Richard Smithf70a9062016-10-20 18:29:25 +00001308 unsigned NumFields =
1309 std::count_if(RD->field_begin(), RD->field_end(),
1310 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
Richard Smith7873de02016-08-11 22:25:46 +00001311 assert(Bindings.size() != NumFields);
1312 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1313 << DecompType << (unsigned)Bindings.size() << NumFields
1314 << (NumFields < Bindings.size());
1315 return true;
1316 };
1317
1318 // all of E's non-static data members shall be public [...] members,
1319 // E shall not have an anonymous union member, ...
1320 unsigned I = 0;
1321 for (auto *FD : RD->fields()) {
1322 if (FD->isUnnamedBitfield())
1323 continue;
1324
1325 if (FD->isAnonymousStructOrUnion()) {
1326 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1327 << DecompType << FD->getType()->isUnionType();
1328 S.Diag(FD->getLocation(), diag::note_declared_at);
1329 return true;
1330 }
1331
1332 // We have a real field to bind.
1333 if (I >= Bindings.size())
1334 return DiagnoseBadNumberOfBindings();
1335 auto *B = Bindings[I++];
1336
1337 SourceLocation Loc = B->getLocation();
1338 if (FD->getAccess() != AS_public) {
1339 S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType;
1340
1341 // Determine whether the access specifier was explicit.
1342 bool Implicit = true;
1343 for (const auto *D : RD->decls()) {
1344 if (declaresSameEntity(D, FD))
1345 break;
1346 if (isa<AccessSpecDecl>(D)) {
1347 Implicit = false;
1348 break;
1349 }
1350 }
1351
1352 S.Diag(FD->getLocation(), diag::note_access_natural)
1353 << (FD->getAccess() == AS_protected) << Implicit;
1354 return true;
1355 }
1356
1357 // Initialize the binding to Src.FD.
1358 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1359 if (E.isInvalid())
1360 return true;
1361 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1362 VK_LValue, &BasePath);
1363 if (E.isInvalid())
1364 return true;
1365 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1366 CXXScopeSpec(), FD,
1367 DeclAccessPair::make(FD, FD->getAccess()),
1368 DeclarationNameInfo(FD->getDeclName(), Loc));
1369 if (E.isInvalid())
1370 return true;
1371
1372 // If the type of the member is T, the referenced type is cv T, where cv is
1373 // the cv-qualification of the decomposition expression.
1374 //
1375 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1376 // 'const' to the type of the field.
1377 Qualifiers Q = DecompType.getQualifiers();
1378 if (FD->isMutable())
1379 Q.removeConst();
1380 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1381 }
1382
1383 if (I != Bindings.size())
1384 return DiagnoseBadNumberOfBindings();
1385
1386 return false;
1387}
1388
Richard Smith3997b1b2016-08-12 01:55:21 +00001389void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
Richard Smith7873de02016-08-11 22:25:46 +00001390 QualType DecompType = DD->getType();
1391
1392 // If the type of the decomposition is dependent, then so is the type of
1393 // each binding.
1394 if (DecompType->isDependentType()) {
1395 for (auto *B : DD->bindings())
1396 B->setType(Context.DependentTy);
1397 return;
1398 }
1399
1400 DecompType = DecompType.getNonReferenceType();
1401 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1402
1403 // C++1z [dcl.decomp]/2:
1404 // If E is an array type [...]
1405 // As an extension, we also support decomposition of built-in complex and
1406 // vector types.
1407 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1408 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1409 DD->setInvalidDecl();
1410 return;
1411 }
1412 if (auto *VT = DecompType->getAs<VectorType>()) {
1413 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1414 DD->setInvalidDecl();
1415 return;
1416 }
1417 if (auto *CT = DecompType->getAs<ComplexType>()) {
1418 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1419 DD->setInvalidDecl();
1420 return;
1421 }
1422
1423 // C++1z [dcl.decomp]/3:
1424 // if the expression std::tuple_size<E>::value is a well-formed integral
1425 // constant expression, [...]
1426 llvm::APSInt TupleSize(32);
1427 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1428 case IsTupleLike::Error:
1429 DD->setInvalidDecl();
1430 return;
1431
1432 case IsTupleLike::TupleLike:
Richard Smith3997b1b2016-08-12 01:55:21 +00001433 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
Richard Smith7873de02016-08-11 22:25:46 +00001434 DD->setInvalidDecl();
1435 return;
1436
1437 case IsTupleLike::NotTupleLike:
1438 break;
1439 }
1440
1441 // C++1z [dcl.dcl]/8:
1442 // [E shall be of array or non-union class type]
1443 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1444 if (!RD || RD->isUnion()) {
1445 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1446 << DD << !RD << DecompType;
1447 DD->setInvalidDecl();
1448 return;
1449 }
1450
1451 // C++1z [dcl.decomp]/4:
1452 // all of E's non-static data members shall be [...] direct members of
1453 // E or of the same unambiguous public base class of E, ...
1454 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1455 DD->setInvalidDecl();
1456}
1457
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001458/// \brief Merge the exception specifications of two variable declarations.
1459///
1460/// This is called when there's a redeclaration of a VarDecl. The function
1461/// checks if the redeclaration might have an exception specification and
1462/// validates compatibility and merges the specs if necessary.
1463void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1464 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001465 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001466 return;
1467
1468 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1469 "Should only be called if types are otherwise the same.");
1470
1471 QualType NewType = New->getType();
1472 QualType OldType = Old->getType();
1473
1474 // We're only interested in pointers and references to functions, as well
1475 // as pointers to member functions.
1476 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1477 NewType = R->getPointeeType();
1478 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1479 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1480 NewType = P->getPointeeType();
1481 OldType = OldType->getAs<PointerType>()->getPointeeType();
1482 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1483 NewType = M->getPointeeType();
1484 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1485 }
1486
1487 if (!NewType->isFunctionProtoType())
1488 return;
1489
1490 // There's lots of special cases for functions. For function pointers, system
1491 // libraries are hopefully not as broken so that we don't need these
1492 // workarounds.
1493 if (CheckEquivalentExceptionSpec(
1494 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1495 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1496 New->setInvalidDecl();
1497 }
1498}
1499
Chris Lattner199abbc2008-04-08 05:04:30 +00001500/// CheckCXXDefaultArguments - Verify that the default arguments for a
1501/// function declaration are well-formed according to C++
1502/// [dcl.fct.default].
1503void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1504 unsigned NumParams = FD->getNumParams();
1505 unsigned p;
1506
1507 // Find first parameter with a default argument
1508 for (p = 0; p < NumParams; ++p) {
1509 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +00001510 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +00001511 break;
1512 }
1513
Benjamin Kramerfe257592015-03-27 13:58:41 +00001514 // C++11 [dcl.fct.default]p4:
1515 // In a given function declaration, each parameter subsequent to a parameter
1516 // with a default argument shall have a default argument supplied in this or
1517 // a previous declaration or shall be a function parameter pack. A default
1518 // argument shall not be redefined by a later declaration (not even to the
1519 // same value).
Chris Lattner199abbc2008-04-08 05:04:30 +00001520 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001521 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +00001522 ParmVarDecl *Param = FD->getParamDecl(p);
Benjamin Kramerfe257592015-03-27 13:58:41 +00001523 if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00001524 if (Param->isInvalidDecl())
1525 /* We already complained about this parameter. */;
1526 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +00001527 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +00001528 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +00001529 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +00001530 else
Mike Stump11289f42009-09-09 15:08:12 +00001531 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +00001532 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +00001533
Chris Lattner199abbc2008-04-08 05:04:30 +00001534 LastMissingDefaultArg = p;
1535 }
1536 }
1537
1538 if (LastMissingDefaultArg > 0) {
1539 // Some default arguments were missing. Clear out all of the
1540 // default arguments up to (and including) the last missing
1541 // default argument, so that we leave the function parameters
1542 // in a semantically valid state.
1543 for (p = 0; p <= LastMissingDefaultArg; ++p) {
1544 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +00001545 if (Param->hasDefaultArg()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001546 Param->setDefaultArg(nullptr);
Chris Lattner199abbc2008-04-08 05:04:30 +00001547 }
1548 }
1549 }
1550}
Douglas Gregor556877c2008-04-13 21:30:24 +00001551
Richard Smitheb3c10c2011-10-01 02:31:28 +00001552// CheckConstexprParameterTypes - Check whether a function's parameter types
1553// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +00001554// diagnostic and return false.
1555static bool CheckConstexprParameterTypes(Sema &SemaRef,
1556 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001557 unsigned ArgIndex = 0;
1558 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001559 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1560 e = FT->param_type_end();
1561 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001562 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1563 SourceLocation ParamLoc = PD->getLocation();
1564 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +00001565 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +00001566 diag::err_constexpr_non_literal_param,
1567 ArgIndex+1, PD->getSourceRange(),
1568 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +00001569 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001570 }
Joao Matose9a3ed42012-08-31 22:18:20 +00001571 return true;
1572}
1573
1574/// \brief Get diagnostic %select index for tag kind for
1575/// record diagnostic message.
1576/// WARNING: Indexes apply to particular diagnostics only!
1577///
1578/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +00001579static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +00001580 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +00001581 case TTK_Struct: return 0;
1582 case TTK_Interface: return 1;
1583 case TTK_Class: return 2;
1584 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +00001585 }
Joao Matose9a3ed42012-08-31 22:18:20 +00001586}
1587
1588// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1589// the requirements of a constexpr function definition or a constexpr
1590// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +00001591// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +00001592//
Richard Smith3607ffe2012-02-13 03:54:03 +00001593// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1594bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +00001595 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1596 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +00001597 // C++11 [dcl.constexpr]p4:
1598 // The definition of a constexpr constructor shall satisfy the following
1599 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001600 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +00001601 const CXXRecordDecl *RD = MD->getParent();
1602 if (RD->getNumVBases()) {
1603 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1604 << isa<CXXConstructorDecl>(NewFD)
1605 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Aaron Ballman445a9392014-03-13 16:15:17 +00001606 for (const auto &I : RD->vbases())
1607 Diag(I.getLocStart(),
1608 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +00001609 return false;
1610 }
Richard Smith7971b692012-01-13 04:54:00 +00001611 }
1612
1613 if (!isa<CXXConstructorDecl>(NewFD)) {
1614 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001615 // The definition of a constexpr function shall satisfy the following
1616 // constraints:
1617 // - it shall not be virtual;
1618 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1619 if (Method && Method->isVirtual()) {
David Majnemerab6607a2015-05-22 05:49:41 +00001620 Method = Method->getCanonicalDecl();
1621 Diag(Method->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001622
Richard Smith3607ffe2012-02-13 03:54:03 +00001623 // If it's not obvious why this function is virtual, find an overridden
1624 // function which uses the 'virtual' keyword.
1625 const CXXMethodDecl *WrittenVirtual = Method;
1626 while (!WrittenVirtual->isVirtualAsWritten())
1627 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1628 if (WrittenVirtual != Method)
1629 Diag(WrittenVirtual->getLocation(),
1630 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001631 return false;
1632 }
1633
1634 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +00001635 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +00001636 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +00001637 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +00001638 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +00001639 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001640 }
1641
Richard Smith7971b692012-01-13 04:54:00 +00001642 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +00001643 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +00001644 return false;
1645
Richard Smitheb3c10c2011-10-01 02:31:28 +00001646 return true;
1647}
1648
1649/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +00001650/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +00001651///
Richard Smithd9f663b2013-04-22 15:31:51 +00001652/// \return true if the body is OK (maybe only as an extension), false if we
1653/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +00001654static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +00001655 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1656 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001657 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1658 // contain only
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001659 for (const auto *DclIt : DS->decls()) {
1660 switch (DclIt->getKind()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001661 case Decl::StaticAssert:
1662 case Decl::Using:
1663 case Decl::UsingShadow:
1664 case Decl::UsingDirective:
1665 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +00001666 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001667 // - static_assert-declarations
1668 // - using-declarations,
1669 // - using-directives,
1670 continue;
1671
1672 case Decl::Typedef:
1673 case Decl::TypeAlias: {
1674 // - typedef declarations and alias-declarations that do not define
1675 // classes or enumerations,
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001676 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001677 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1678 // Don't allow variably-modified types in constexpr functions.
1679 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1680 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1681 << TL.getSourceRange() << TL.getType()
1682 << isa<CXXConstructorDecl>(Dcl);
1683 return false;
1684 }
1685 continue;
1686 }
1687
1688 case Decl::Enum:
1689 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +00001690 // C++1y allows types to be defined, not just declared.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001691 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smithd9f663b2013-04-22 15:31:51 +00001692 SemaRef.Diag(DS->getLocStart(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001693 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001694 ? diag::warn_cxx11_compat_constexpr_type_definition
1695 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +00001696 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001697 continue;
1698
Richard Smithd9f663b2013-04-22 15:31:51 +00001699 case Decl::EnumConstant:
1700 case Decl::IndirectField:
1701 case Decl::ParmVar:
1702 // These can only appear with other declarations which are banned in
1703 // C++11 and permitted in C++1y, so ignore them.
1704 continue;
1705
Richard Smithdca60b42016-08-12 00:39:32 +00001706 case Decl::Var:
1707 case Decl::Decomposition: {
Richard Smithd9f663b2013-04-22 15:31:51 +00001708 // C++1y [dcl.constexpr]p3 allows anything except:
1709 // a definition of a variable of non-literal type or of static or
1710 // thread storage duration or for which no initialization is performed.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001711 const auto *VD = cast<VarDecl>(DclIt);
Richard Smithd9f663b2013-04-22 15:31:51 +00001712 if (VD->isThisDeclarationADefinition()) {
1713 if (VD->isStaticLocal()) {
1714 SemaRef.Diag(VD->getLocation(),
1715 diag::err_constexpr_local_var_static)
1716 << isa<CXXConstructorDecl>(Dcl)
1717 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1718 return false;
1719 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001720 if (!VD->getType()->isDependentType() &&
1721 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +00001722 VD->getLocation(), VD->getType(),
1723 diag::err_constexpr_local_var_non_literal_type,
1724 isa<CXXConstructorDecl>(Dcl)))
1725 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +00001726 if (!VD->getType()->isDependentType() &&
1727 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001728 SemaRef.Diag(VD->getLocation(),
1729 diag::err_constexpr_local_var_no_init)
1730 << isa<CXXConstructorDecl>(Dcl);
1731 return false;
1732 }
1733 }
1734 SemaRef.Diag(VD->getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001735 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001736 ? diag::warn_cxx11_compat_constexpr_local_var
1737 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +00001738 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +00001739 continue;
1740 }
1741
1742 case Decl::NamespaceAlias:
1743 case Decl::Function:
1744 // These are disallowed in C++11 and permitted in C++1y. Allow them
1745 // everywhere as an extension.
1746 if (!Cxx1yLoc.isValid())
1747 Cxx1yLoc = DS->getLocStart();
1748 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001749
1750 default:
1751 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1752 << isa<CXXConstructorDecl>(Dcl);
1753 return false;
1754 }
1755 }
1756
1757 return true;
1758}
1759
1760/// Check that the given field is initialized within a constexpr constructor.
1761///
1762/// \param Dcl The constexpr constructor being checked.
1763/// \param Field The field being checked. This may be a member of an anonymous
1764/// struct or union nested within the class being checked.
1765/// \param Inits All declarations, including anonymous struct/union members and
1766/// indirect members, for which any initialization was provided.
1767/// \param Diagnosed Set to true if an error is produced.
1768static void CheckConstexprCtorInitializer(Sema &SemaRef,
1769 const FunctionDecl *Dcl,
1770 FieldDecl *Field,
1771 llvm::SmallSet<Decl*, 16> &Inits,
1772 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00001773 if (Field->isInvalidDecl())
1774 return;
1775
Douglas Gregor556e5862011-10-10 17:22:13 +00001776 if (Field->isUnnamedBitfield())
1777 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +00001778
Richard Smithab44d5b2013-12-10 08:25:00 +00001779 // Anonymous unions with no variant members and empty anonymous structs do not
1780 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1781 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +00001782 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +00001783 (Field->getType()->isUnionType()
1784 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1785 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +00001786 return;
1787
Richard Smitheb3c10c2011-10-01 02:31:28 +00001788 if (!Inits.count(Field)) {
1789 if (!Diagnosed) {
1790 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1791 Diagnosed = true;
1792 }
1793 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1794 } else if (Field->isAnonymousStructOrUnion()) {
1795 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001796 for (auto *I : RD->fields())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001797 // If an anonymous union contains an anonymous struct of which any member
1798 // is initialized, all members must be initialized.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001799 if (!RD->isUnion() || Inits.count(I))
1800 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001801 }
1802}
1803
Richard Smithd9f663b2013-04-22 15:31:51 +00001804/// Check the provided statement is allowed in a constexpr function
1805/// definition.
1806static bool
1807CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00001808 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001809 SourceLocation &Cxx1yLoc) {
1810 // - its function-body shall be [...] a compound-statement that contains only
1811 switch (S->getStmtClass()) {
1812 case Stmt::NullStmtClass:
1813 // - null statements,
1814 return true;
1815
1816 case Stmt::DeclStmtClass:
1817 // - static_assert-declarations
1818 // - using-declarations,
1819 // - using-directives,
1820 // - typedef declarations and alias-declarations that do not define
1821 // classes or enumerations,
1822 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1823 return false;
1824 return true;
1825
1826 case Stmt::ReturnStmtClass:
1827 // - and exactly one return statement;
1828 if (isa<CXXConstructorDecl>(Dcl)) {
1829 // C++1y allows return statements in constexpr constructors.
1830 if (!Cxx1yLoc.isValid())
1831 Cxx1yLoc = S->getLocStart();
1832 return true;
1833 }
1834
1835 ReturnStmts.push_back(S->getLocStart());
1836 return true;
1837
1838 case Stmt::CompoundStmtClass: {
1839 // C++1y allows compound-statements.
1840 if (!Cxx1yLoc.isValid())
1841 Cxx1yLoc = S->getLocStart();
1842
1843 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001844 for (auto *BodyIt : CompStmt->body()) {
1845 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001846 Cxx1yLoc))
1847 return false;
1848 }
1849 return true;
1850 }
1851
1852 case Stmt::AttributedStmtClass:
1853 if (!Cxx1yLoc.isValid())
1854 Cxx1yLoc = S->getLocStart();
1855 return true;
1856
1857 case Stmt::IfStmtClass: {
1858 // C++1y allows if-statements.
1859 if (!Cxx1yLoc.isValid())
1860 Cxx1yLoc = S->getLocStart();
1861
1862 IfStmt *If = cast<IfStmt>(S);
1863 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1864 Cxx1yLoc))
1865 return false;
1866 if (If->getElse() &&
1867 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1868 Cxx1yLoc))
1869 return false;
1870 return true;
1871 }
1872
1873 case Stmt::WhileStmtClass:
1874 case Stmt::DoStmtClass:
1875 case Stmt::ForStmtClass:
1876 case Stmt::CXXForRangeStmtClass:
1877 case Stmt::ContinueStmtClass:
1878 // C++1y allows all of these. We don't allow them as extensions in C++11,
1879 // because they don't make sense without variable mutation.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001880 if (!SemaRef.getLangOpts().CPlusPlus14)
Richard Smithd9f663b2013-04-22 15:31:51 +00001881 break;
1882 if (!Cxx1yLoc.isValid())
1883 Cxx1yLoc = S->getLocStart();
Benjamin Kramer642f1732015-07-02 21:03:14 +00001884 for (Stmt *SubStmt : S->children())
1885 if (SubStmt &&
1886 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001887 Cxx1yLoc))
1888 return false;
1889 return true;
1890
1891 case Stmt::SwitchStmtClass:
1892 case Stmt::CaseStmtClass:
1893 case Stmt::DefaultStmtClass:
1894 case Stmt::BreakStmtClass:
1895 // C++1y allows switch-statements, and since they don't need variable
1896 // mutation, we can reasonably allow them in C++11 as an extension.
1897 if (!Cxx1yLoc.isValid())
1898 Cxx1yLoc = S->getLocStart();
Benjamin Kramer642f1732015-07-02 21:03:14 +00001899 for (Stmt *SubStmt : S->children())
1900 if (SubStmt &&
1901 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001902 Cxx1yLoc))
1903 return false;
1904 return true;
1905
1906 default:
1907 if (!isa<Expr>(S))
1908 break;
1909
1910 // C++1y allows expression-statements.
1911 if (!Cxx1yLoc.isValid())
1912 Cxx1yLoc = S->getLocStart();
1913 return true;
1914 }
1915
1916 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1917 << isa<CXXConstructorDecl>(Dcl);
1918 return false;
1919}
1920
Richard Smitheb3c10c2011-10-01 02:31:28 +00001921/// Check the body for the given constexpr function declaration only contains
1922/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1923///
1924/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001925bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001926 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001927 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001928 // The definition of a constexpr function shall satisfy the following
1929 // constraints: [...]
1930 // - its function-body shall be = delete, = default, or a
1931 // compound-statement
1932 //
Richard Smith74388b42012-02-04 00:33:54 +00001933 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001934 // In the definition of a constexpr constructor, [...]
1935 // - its function-body shall not be a function-try-block;
1936 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1937 << isa<CXXConstructorDecl>(Dcl);
1938 return false;
1939 }
1940
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001941 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001942
1943 // - its function-body shall be [...] a compound-statement that contains only
1944 // [... list of cases ...]
1945 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1946 SourceLocation Cxx1yLoc;
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001947 for (auto *BodyIt : CompBody->body()) {
1948 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smithd9f663b2013-04-22 15:31:51 +00001949 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001950 }
1951
Richard Smithd9f663b2013-04-22 15:31:51 +00001952 if (Cxx1yLoc.isValid())
1953 Diag(Cxx1yLoc,
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001954 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001955 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1956 : diag::ext_constexpr_body_invalid_stmt)
1957 << isa<CXXConstructorDecl>(Dcl);
1958
Richard Smitheb3c10c2011-10-01 02:31:28 +00001959 if (const CXXConstructorDecl *Constructor
1960 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1961 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001962 // DR1359:
1963 // - every non-variant non-static data member and base class sub-object
1964 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001965 // DR1460:
1966 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001967 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001968 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001969 if (Constructor->getNumCtorInitializers() == 0 &&
1970 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001971 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1972 return false;
1973 }
Richard Smithf368fb42011-10-10 16:38:04 +00001974 } else if (!Constructor->isDependentContext() &&
1975 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001976 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1977
1978 // Skip detailed checking if we have enough initializers, and we would
1979 // allow at most one initializer per member.
1980 bool AnyAnonStructUnionMembers = false;
1981 unsigned Fields = 0;
1982 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1983 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001984 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001985 AnyAnonStructUnionMembers = true;
1986 break;
1987 }
1988 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001989 // DR1460:
1990 // - if the class is a union-like class, but is not a union, for each of
1991 // its anonymous union members having variant members, exactly one of
1992 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001993 if (AnyAnonStructUnionMembers ||
1994 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1995 // Check initialization of non-static data members. Base classes are
1996 // always initialized so do not need to be checked. Dependent bases
1997 // might not have initializers in the member initializer list.
1998 llvm::SmallSet<Decl*, 16> Inits;
Aaron Ballman0ad78302014-03-13 17:34:31 +00001999 for (const auto *I: Constructor->inits()) {
2000 if (FieldDecl *FD = I->getMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00002001 Inits.insert(FD);
Aaron Ballman0ad78302014-03-13 17:34:31 +00002002 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00002003 Inits.insert(ID->chain_begin(), ID->chain_end());
2004 }
2005
2006 bool Diagnosed = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002007 for (auto *I : RD->fields())
2008 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00002009 if (Diagnosed)
2010 return false;
2011 }
2012 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00002013 } else {
2014 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002015 // C++1y doesn't require constexpr functions to contain a 'return'
Richard Smith06ffb452014-04-22 23:14:23 +00002016 // statement. We still do, unless the return type might be void, because
Richard Smithd9f663b2013-04-22 15:31:51 +00002017 // otherwise if there's no return statement, the function cannot
2018 // be used in a core constant expression.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002019 bool OK = getLangOpts().CPlusPlus14 &&
Richard Smith06ffb452014-04-22 23:14:23 +00002020 (Dcl->getReturnType()->isVoidType() ||
2021 Dcl->getReturnType()->isDependentType());
Richard Smithd9f663b2013-04-22 15:31:51 +00002022 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00002023 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2024 : diag::err_constexpr_body_no_return);
Richard Smithd35cb052015-08-28 22:33:53 +00002025 if (!OK)
2026 return false;
2027 } else if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002028 Diag(ReturnStmts.back(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002029 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00002030 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2031 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00002032 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2033 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00002034 }
2035 }
2036
Richard Smith74388b42012-02-04 00:33:54 +00002037 // C++11 [dcl.constexpr]p5:
2038 // if no function argument values exist such that the function invocation
2039 // substitution would produce a constant expression, the program is
2040 // ill-formed; no diagnostic required.
2041 // C++11 [dcl.constexpr]p3:
2042 // - every constructor call and implicit conversion used in initializing the
2043 // return value shall be one of those allowed in a constant expression.
2044 // C++11 [dcl.constexpr]p4:
2045 // - every constructor involved in initializing non-static data members and
2046 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002047 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00002048 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00002049 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00002050 << isa<CXXConstructorDecl>(Dcl);
2051 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2052 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00002053 // Don't return false here: we allow this for compatibility in
2054 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00002055 }
2056
Richard Smitheb3c10c2011-10-01 02:31:28 +00002057 return true;
2058}
2059
Douglas Gregor61956c42008-10-31 09:07:45 +00002060/// isCurrentClassName - Determine whether the identifier II is the
2061/// name of the class type currently being defined. In the case of
2062/// nested classes, this will only return true if II is the name of
2063/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00002064bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
2065 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002066 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002067
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00002068 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00002069 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00002070 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00002071 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2072 } else
2073 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2074
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00002075 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00002076 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002077 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00002078}
2079
Richard Smithfb8b7b92013-10-15 00:00:26 +00002080/// \brief Determine whether the identifier II is a typo for the name of
2081/// the class type currently being defined. If so, update it to the identifier
2082/// that should have been used.
2083bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2084 assert(getLangOpts().CPlusPlus && "No class names in C!");
2085
2086 if (!getLangOpts().SpellChecking)
2087 return false;
2088
2089 CXXRecordDecl *CurDecl;
2090 if (SS && SS->isSet() && !SS->isInvalid()) {
2091 DeclContext *DC = computeDeclContext(*SS, true);
2092 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2093 } else
2094 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2095
2096 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2097 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2098 < II->getLength()) {
2099 II = CurDecl->getIdentifier();
2100 return true;
2101 }
2102
2103 return false;
2104}
2105
Douglas Gregordc974572012-11-10 07:24:09 +00002106/// \brief Determine whether the given class is a base class of the given
2107/// class, including looking at dependent bases.
2108static bool findCircularInheritance(const CXXRecordDecl *Class,
2109 const CXXRecordDecl *Current) {
2110 SmallVector<const CXXRecordDecl*, 8> Queue;
2111
2112 Class = Class->getCanonicalDecl();
2113 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002114 for (const auto &I : Current->bases()) {
2115 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregordc974572012-11-10 07:24:09 +00002116 if (!Base)
2117 continue;
2118
2119 Base = Base->getDefinition();
2120 if (!Base)
2121 continue;
2122
2123 if (Base->getCanonicalDecl() == Class)
2124 return true;
2125
2126 Queue.push_back(Base);
2127 }
2128
2129 if (Queue.empty())
2130 return false;
2131
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002132 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00002133 }
2134
2135 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00002136}
2137
Mike Stump11289f42009-09-09 15:08:12 +00002138/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00002139///
2140/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2141/// and returns NULL otherwise.
2142CXXBaseSpecifier *
2143Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2144 SourceRange SpecifierRange,
2145 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00002146 TypeSourceInfo *TInfo,
2147 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00002148 QualType BaseType = TInfo->getType();
2149
Douglas Gregor463421d2009-03-03 04:44:36 +00002150 // C++ [class.union]p1:
2151 // A union shall not have base classes.
2152 if (Class->isUnion()) {
2153 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2154 << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00002155 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00002156 }
2157
Erich Keanebb863642017-09-20 22:28:24 +00002158 if (EllipsisLoc.isValid() &&
Douglas Gregor752a5952011-01-03 22:36:02 +00002159 !TInfo->getType()->containsUnexpandedParameterPack()) {
2160 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2161 << TInfo->getTypeLoc().getSourceRange();
2162 EllipsisLoc = SourceLocation();
2163 }
Douglas Gregor62004702012-11-10 01:18:17 +00002164
2165 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2166
2167 if (BaseType->isDependentType()) {
2168 // Make sure that we don't have circular inheritance among our dependent
2169 // bases. For non-dependent bases, the check for completeness below handles
2170 // this.
2171 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2172 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2173 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00002174 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00002175 Diag(BaseLoc, diag::err_circular_inheritance)
2176 << BaseType << Context.getTypeDeclType(Class);
2177
2178 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2179 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2180 << BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002181
2182 return nullptr;
Douglas Gregor62004702012-11-10 01:18:17 +00002183 }
2184 }
2185
Mike Stump11289f42009-09-09 15:08:12 +00002186 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00002187 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00002188 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00002189 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002190
2191 // Base specifiers must be record types.
2192 if (!BaseType->isRecordType()) {
2193 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00002194 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00002195 }
2196
2197 // C++ [class.union]p1:
2198 // A union shall not be used as a base class.
2199 if (BaseType->isUnionType()) {
2200 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00002201 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00002202 }
2203
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00002204 // For the MS ABI, propagate DLL attributes to base class templates.
2205 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2206 if (Attr *ClassAttr = getDLLAttr(Class)) {
2207 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2208 BaseType->getAsCXXRecordDecl())) {
Hans Wennborgfce87ca2015-06-09 00:39:09 +00002209 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2210 BaseLoc);
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00002211 }
2212 }
2213 }
2214
Douglas Gregor463421d2009-03-03 04:44:36 +00002215 // C++ [class.derived]p2:
2216 // The class-name in a base-specifier shall not be an incompletely
2217 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00002218 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002219 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00002220 Class->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00002221 return nullptr;
John McCall3696dcb2010-08-17 07:23:57 +00002222 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002223
Eli Friedmanc96d4962009-08-15 21:55:26 +00002224 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002225 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00002226 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002227 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00002228 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00002229 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00002230 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00002231
David Majnemer9b1754d2013-11-02 12:00:36 +00002232 // A class which contains a flexible array member is not suitable for use as a
2233 // base class:
2234 // - If the layout determines that a base comes before another base,
2235 // the flexible array member would index into the subsequent base.
2236 // - If the layout determines that base comes before the derived class,
2237 // the flexible array member would index into the derived class.
2238 if (CXXBaseDecl->hasFlexibleArrayMember()) {
2239 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2240 << CXXBaseDecl->getDeclName();
Craig Topperc3ec1492014-05-26 06:22:03 +00002241 return nullptr;
David Majnemer9b1754d2013-11-02 12:00:36 +00002242 }
2243
Anders Carlsson65c76d32011-03-25 14:55:14 +00002244 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00002245 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00002246 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00002247 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00002248 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00002249 << CXXBaseDecl->getDeclName()
2250 << FA->isSpelledAsSealed();
Alp Toker2afa8782014-05-28 12:20:14 +00002251 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2252 << CXXBaseDecl->getDeclName() << FA->getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00002253 return nullptr;
Anders Carlssonfc1eef42011-01-22 17:51:53 +00002254 }
2255
John McCall3696dcb2010-08-17 07:23:57 +00002256 if (BaseDecl->isInvalidDecl())
2257 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00002258
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00002259 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00002260 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00002261 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00002262 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00002263}
2264
Douglas Gregor556877c2008-04-13 21:30:24 +00002265/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2266/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00002267/// example:
2268/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00002269/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00002270BaseResult
John McCall48871652010-08-21 09:40:31 +00002271Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00002272 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00002273 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00002274 ParsedType basetype, SourceLocation BaseLoc,
2275 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002276 if (!classdecl)
2277 return true;
2278
Douglas Gregorc40290e2009-03-09 23:48:35 +00002279 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00002280 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00002281 if (!Class)
2282 return true;
2283
David Majnemer5ef4fe72014-06-13 06:43:46 +00002284 // We haven't yet attached the base specifiers.
2285 Class->setIsParsingBaseSpecifiers();
2286
Richard Smith4c96e992013-02-19 23:47:15 +00002287 // We do not support any C++11 attributes on base-specifiers yet.
2288 // Diagnose any attributes we see.
2289 if (!Attributes.empty()) {
2290 for (AttributeList *Attr = Attributes.getList(); Attr;
2291 Attr = Attr->getNext()) {
2292 if (Attr->isInvalid() ||
2293 Attr->getKind() == AttributeList::IgnoredAttribute)
2294 continue;
2295 Diag(Attr->getLoc(),
2296 Attr->getKind() == AttributeList::UnknownAttribute
2297 ? diag::warn_unknown_attribute_ignored
2298 : diag::err_base_specifier_attribute)
2299 << Attr->getName();
2300 }
2301 }
2302
Craig Topperc3ec1492014-05-26 06:22:03 +00002303 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00002304 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00002305
Douglas Gregor752a5952011-01-03 22:36:02 +00002306 if (EllipsisLoc.isInvalid() &&
Erich Keanebb863642017-09-20 22:28:24 +00002307 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00002308 UPPC_BaseType))
2309 return true;
Erich Keanebb863642017-09-20 22:28:24 +00002310
Douglas Gregor463421d2009-03-03 04:44:36 +00002311 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00002312 Virtual, Access, TInfo,
2313 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00002314 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002315 else
2316 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002317
Douglas Gregor463421d2009-03-03 04:44:36 +00002318 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00002319}
Douglas Gregor556877c2008-04-13 21:30:24 +00002320
Nathan Sidwell44b21742015-01-19 01:44:02 +00002321/// Use small set to collect indirect bases. As this is only used
2322/// locally, there's no need to abstract the small size parameter.
2323typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2324
2325/// \brief Recursively add the bases of Type. Don't add Type itself.
2326static void
2327NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2328 const QualType &Type)
2329{
2330 // Even though the incoming type is a base, it might not be
2331 // a class -- it could be a template parm, for instance.
2332 if (auto Rec = Type->getAs<RecordType>()) {
2333 auto Decl = Rec->getAsCXXRecordDecl();
2334
2335 // Iterate over its bases.
2336 for (const auto &BaseSpec : Decl->bases()) {
2337 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2338 .getUnqualifiedType();
2339 if (Set.insert(Base).second)
2340 // If we've not already seen it, recurse.
2341 NoteIndirectBases(Context, Set, Base);
2342 }
2343 }
2344}
2345
Douglas Gregor463421d2009-03-03 04:44:36 +00002346/// \brief Performs the actual work of attaching the given base class
2347/// specifiers to a C++ class.
Craig Topperaa700cb2015-12-27 21:55:19 +00002348bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2349 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2350 if (Bases.empty())
Douglas Gregor463421d2009-03-03 04:44:36 +00002351 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00002352
2353 // Used to keep track of which base types we have already seen, so
2354 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00002355 // that the key is always the unqualified canonical type of the base
2356 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00002357 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2358
Nathan Sidwell44b21742015-01-19 01:44:02 +00002359 // Used to track indirect bases so we can see if a direct base is
2360 // ambiguous.
2361 IndirectBaseSet IndirectBaseTypes;
2362
Douglas Gregor29a92472008-10-22 17:49:05 +00002363 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00002364 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00002365 bool Invalid = false;
Craig Topperaa700cb2015-12-27 21:55:19 +00002366 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00002367 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00002368 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002369 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00002370
2371 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2372 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00002373 // C++ [class.mi]p3:
2374 // A class shall not be specified as a direct base class of a
2375 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002376 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002377 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00002378 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00002379 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00002380
2381 // Delete the duplicate base class specifier; we're going to
2382 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00002383 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00002384
2385 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00002386 } else {
2387 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00002388 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00002389 Bases[NumGoodBases++] = Bases[idx];
Nathan Sidwell44b21742015-01-19 01:44:02 +00002390
2391 // Note this base's direct & indirect bases, if there could be ambiguity.
Craig Topperaa700cb2015-12-27 21:55:19 +00002392 if (Bases.size() > 1)
Nathan Sidwell44b21742015-01-19 01:44:02 +00002393 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
Erich Keanebb863642017-09-20 22:28:24 +00002394
John McCalldb632ac2012-09-25 07:32:39 +00002395 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2396 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2397 if (Class->isInterface() &&
Erich Keane58bd6032017-09-15 16:03:35 +00002398 (!RD->isInterfaceLike() ||
John McCalldb632ac2012-09-25 07:32:39 +00002399 KnownBase->getAccessSpecifier() != AS_public)) {
2400 // The Microsoft extension __interface does not permit bases that
2401 // are not themselves public interfaces.
2402 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
2403 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
2404 << RD->getSourceRange();
2405 Invalid = true;
2406 }
2407 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00002408 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00002409 }
Douglas Gregor29a92472008-10-22 17:49:05 +00002410 }
2411 }
2412
2413 // Attach the remaining base class specifiers to the derived class.
Craig Topperaa700cb2015-12-27 21:55:19 +00002414 Class->setBases(Bases.data(), NumGoodBases);
Erich Keanebb863642017-09-20 22:28:24 +00002415
Nathan Sidwell44b21742015-01-19 01:44:02 +00002416 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2417 // Check whether this direct base is inaccessible due to ambiguity.
2418 QualType BaseType = Bases[idx]->getType();
2419 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2420 .getUnqualifiedType();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00002421
Nathan Sidwell44b21742015-01-19 01:44:02 +00002422 if (IndirectBaseTypes.count(CanonicalBase)) {
2423 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2424 /*DetectVirtual=*/true);
2425 bool found
2426 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2427 assert(found);
NAKAMURA Takumi6a1565c2015-01-19 09:49:59 +00002428 (void)found;
Nathan Sidwell44b21742015-01-19 01:44:02 +00002429
2430 if (Paths.isAmbiguous(CanonicalBase))
2431 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
2432 << BaseType << getAmbiguousPathsDisplayString(Paths)
2433 << Bases[idx]->getSourceRange();
2434 else
2435 assert(Bases[idx]->isVirtual());
2436 }
2437
2438 // Delete the base class specifier, since its data has been copied
2439 // into the CXXRecordDecl.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00002440 Context.Deallocate(Bases[idx]);
Nathan Sidwell44b21742015-01-19 01:44:02 +00002441 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002442
2443 return Invalid;
2444}
2445
2446/// ActOnBaseSpecifiers - Attach the given base specifiers to the
2447/// class, after checking whether there are any duplicate base
2448/// classes.
Craig Topperaa700cb2015-12-27 21:55:19 +00002449void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2450 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2451 if (!ClassDecl || Bases.empty())
Douglas Gregor463421d2009-03-03 04:44:36 +00002452 return;
2453
2454 AdjustDeclIfTemplate(ClassDecl);
Craig Topperaa700cb2015-12-27 21:55:19 +00002455 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
Douglas Gregor556877c2008-04-13 21:30:24 +00002456}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002457
Douglas Gregor36d1b142009-10-06 17:59:45 +00002458/// \brief Determine whether the type \p Derived is a C++ class that is
2459/// derived from the type \p Base.
Richard Smith0f59cb32015-12-18 21:45:41 +00002460bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002461 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002462 return false;
Richard Smith0f59cb32015-12-18 21:45:41 +00002463
Douglas Gregor45bb4832013-03-26 23:36:30 +00002464 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00002465 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002466 return false;
Erich Keanebb863642017-09-20 22:28:24 +00002467
Douglas Gregor45bb4832013-03-26 23:36:30 +00002468 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00002469 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002470 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00002471
2472 // If either the base or the derived type is invalid, don't try to
2473 // check whether one is derived from the other.
2474 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2475 return false;
2476
Richard Smithdb0ac552015-12-18 22:40:25 +00002477 // FIXME: In a modules build, do we need the entire path to be visible for us
2478 // to be able to use the inheritance relationship?
2479 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2480 return false;
Erich Keanebb863642017-09-20 22:28:24 +00002481
Richard Smith0f59cb32015-12-18 21:45:41 +00002482 return DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00002483}
2484
2485/// \brief Determine whether the type \p Derived is a C++ class that is
2486/// derived from the type \p Base.
Richard Smith0f59cb32015-12-18 21:45:41 +00002487bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2488 CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002489 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002490 return false;
Erich Keanebb863642017-09-20 22:28:24 +00002491
Douglas Gregor45bb4832013-03-26 23:36:30 +00002492 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00002493 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002494 return false;
Erich Keanebb863642017-09-20 22:28:24 +00002495
Douglas Gregor45bb4832013-03-26 23:36:30 +00002496 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00002497 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002498 return false;
Erich Keanebb863642017-09-20 22:28:24 +00002499
Richard Smithdb0ac552015-12-18 22:40:25 +00002500 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2501 return false;
Erich Keanebb863642017-09-20 22:28:24 +00002502
Douglas Gregor36d1b142009-10-06 17:59:45 +00002503 return DerivedRD->isDerivedFrom(BaseRD, Paths);
2504}
2505
Erich Keanebb863642017-09-20 22:28:24 +00002506void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00002507 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00002508 assert(BasePathArray.empty() && "Base path array must be empty!");
2509 assert(Paths.isRecordingPaths() && "Must record paths!");
Erich Keanebb863642017-09-20 22:28:24 +00002510
Anders Carlssona70cff62010-04-24 19:06:50 +00002511 const CXXBasePath &Path = Paths.front();
Erich Keanebb863642017-09-20 22:28:24 +00002512
Anders Carlssona70cff62010-04-24 19:06:50 +00002513 // We first go backward and check if we have a virtual base.
2514 // FIXME: It would be better if CXXBasePath had the base specifier for
2515 // the nearest virtual base.
2516 unsigned Start = 0;
2517 for (unsigned I = Path.size(); I != 0; --I) {
2518 if (Path[I - 1].Base->isVirtual()) {
2519 Start = I - 1;
2520 break;
2521 }
2522 }
2523
2524 // Now add all bases.
2525 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00002526 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00002527}
2528
Douglas Gregor36d1b142009-10-06 17:59:45 +00002529/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2530/// conversion (where Derived and Base are class types) is
2531/// well-formed, meaning that the conversion is unambiguous (and
2532/// that all of the base classes are accessible). Returns true
2533/// and emits a diagnostic if the code is ill-formed, returns false
2534/// otherwise. Loc is the location where this routine should point to
2535/// if there is an error, and Range is the source range to highlight
2536/// if there is an error.
George Burgess IV60bc9722016-01-13 23:36:34 +00002537///
2538/// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2539/// diagnostic for the respective type of error will be suppressed, but the
2540/// check for ill-formed code will still be performed.
Douglas Gregor36d1b142009-10-06 17:59:45 +00002541bool
2542Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00002543 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002544 unsigned AmbigiousBaseConvID,
2545 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00002546 DeclarationName Name,
George Burgess IV60bc9722016-01-13 23:36:34 +00002547 CXXCastPath *BasePath,
2548 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00002549 // First, determine whether the path from Derived to Base is
2550 // ambiguous. This is slightly more expensive than checking whether
2551 // the Derived to Base conversion exists, because here we need to
2552 // explore multiple paths to determine if there is an ambiguity.
2553 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2554 /*DetectVirtual=*/false);
Richard Smith0f59cb32015-12-18 21:45:41 +00002555 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
Douglas Gregor36d1b142009-10-06 17:59:45 +00002556 assert(DerivationOkay &&
2557 "Can only be used with a derived-to-base conversion");
2558 (void)DerivationOkay;
Erich Keanebb863642017-09-20 22:28:24 +00002559
Douglas Gregor36d1b142009-10-06 17:59:45 +00002560 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
George Burgess IV60bc9722016-01-13 23:36:34 +00002561 if (!IgnoreAccess) {
Anders Carlssona70cff62010-04-24 19:06:50 +00002562 // Check that the base class can be accessed.
2563 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
2564 InaccessibleBaseID)) {
Erich Keanebb863642017-09-20 22:28:24 +00002565 case AR_inaccessible:
Anders Carlssona70cff62010-04-24 19:06:50 +00002566 return true;
Erich Keanebb863642017-09-20 22:28:24 +00002567 case AR_accessible:
Anders Carlssona70cff62010-04-24 19:06:50 +00002568 case AR_dependent:
2569 case AR_delayed:
2570 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00002571 }
John McCall5b0829a2010-02-10 09:31:12 +00002572 }
Erich Keanebb863642017-09-20 22:28:24 +00002573
Anders Carlssona70cff62010-04-24 19:06:50 +00002574 // Build a base path if necessary.
2575 if (BasePath)
2576 BuildBasePathArray(Paths, *BasePath);
2577 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00002578 }
Erich Keanebb863642017-09-20 22:28:24 +00002579
David Majnemer626032f2013-06-22 06:43:58 +00002580 if (AmbigiousBaseConvID) {
2581 // We know that the derived-to-base conversion is ambiguous, and
2582 // we're going to produce a diagnostic. Perform the derived-to-base
2583 // search just one more time to compute all of the possible paths so
2584 // that we can print them out. This is more expensive than any of
2585 // the previous derived-to-base checks we've done, but at this point
2586 // performance isn't as much of an issue.
2587 Paths.clear();
2588 Paths.setRecordingPaths(true);
Richard Smith0f59cb32015-12-18 21:45:41 +00002589 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
David Majnemer626032f2013-06-22 06:43:58 +00002590 assert(StillOkay && "Can only be used with a derived-to-base conversion");
2591 (void)StillOkay;
2592
2593 // Build up a textual representation of the ambiguous paths, e.g.,
2594 // D -> B -> A, that will be used to illustrate the ambiguous
2595 // conversions in the diagnostic. We only print one of the paths
2596 // to each base class subobject.
2597 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2598
2599 Diag(Loc, AmbigiousBaseConvID)
2600 << Derived << Base << PathDisplayStr << Range << Name;
2601 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00002602 return true;
2603}
2604
2605bool
2606Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00002607 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00002608 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002609 bool IgnoreAccess) {
George Burgess IV60bc9722016-01-13 23:36:34 +00002610 return CheckDerivedToBaseConversion(
2611 Derived, Base, diag::err_upcast_to_inaccessible_base,
2612 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2613 BasePath, IgnoreAccess);
Douglas Gregor36d1b142009-10-06 17:59:45 +00002614}
2615
2616
2617/// @brief Builds a string representing ambiguous paths from a
2618/// specific derived class to different subobjects of the same base
2619/// class.
2620///
2621/// This function builds a string that can be used in error messages
2622/// to show the different paths that one can take through the
2623/// inheritance hierarchy to go from the derived class to different
2624/// subobjects of a base class. The result looks something like this:
2625/// @code
2626/// struct D -> struct B -> struct A
2627/// struct D -> struct C -> struct A
2628/// @endcode
2629std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2630 std::string PathDisplayStr;
2631 std::set<unsigned> DisplayedPaths;
2632 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2633 Path != Paths.end(); ++Path) {
2634 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2635 // We haven't displayed a path to this particular base
2636 // class subobject yet.
2637 PathDisplayStr += "\n ";
2638 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2639 for (CXXBasePath::const_iterator Element = Path->begin();
2640 Element != Path->end(); ++Element)
2641 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2642 }
2643 }
Erich Keanebb863642017-09-20 22:28:24 +00002644
Douglas Gregor36d1b142009-10-06 17:59:45 +00002645 return PathDisplayStr;
2646}
2647
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002648//===----------------------------------------------------------------------===//
2649// C++ class member Handling
2650//===----------------------------------------------------------------------===//
2651
Abramo Bagnarad7340582010-06-05 05:09:32 +00002652/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002653bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
2654 SourceLocation ASLoc,
2655 SourceLocation ColonLoc,
2656 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00002657 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00002658 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00002659 ASLoc, ColonLoc);
2660 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002661 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00002662}
2663
Richard Smith18f07db2012-08-06 03:25:17 +00002664/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002665void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00002666 if (D->isInvalidDecl())
2667 return;
2668
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002669 // We only care about "override" and "final" declarations.
2670 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2671 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00002672
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002673 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00002674
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002675 // We can't check dependent instance methods.
2676 if (MD && MD->isInstance() &&
2677 (MD->getParent()->hasAnyDependentBases() ||
2678 MD->getType()->isDependentType()))
2679 return;
2680
2681 if (MD && !MD->isVirtual()) {
2682 // If we have a non-virtual method, check if if hides a virtual method.
2683 // (In that case, it's most likely the method has the wrong type.)
2684 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2685 FindHiddenVirtualMethods(MD, OverloadedMethods);
2686
2687 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00002688 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2689 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002690 diag::override_keyword_hides_virtual_member_function)
2691 << "override" << (OverloadedMethods.size() > 1);
2692 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00002693 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002694 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00002695 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2696 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00002697 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002698 NoteHiddenVirtualMethods(MD, OverloadedMethods);
2699 MD->setInvalidDecl();
2700 return;
2701 }
2702 // Fall through into the general case diagnostic.
2703 // FIXME: We might want to attempt typo correction here.
2704 }
2705
2706 if (!MD || !MD->isVirtual()) {
2707 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2708 Diag(OA->getLocation(),
2709 diag::override_keyword_only_allowed_on_virtual_member_functions)
2710 << "override" << FixItHint::CreateRemoval(OA->getLocation());
2711 D->dropAttr<OverrideAttr>();
2712 }
2713 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2714 Diag(FA->getLocation(),
2715 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00002716 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2717 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002718 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00002719 }
Anders Carlssonfd835532011-01-20 05:57:14 +00002720 return;
2721 }
Richard Smith18f07db2012-08-06 03:25:17 +00002722
Richard Smith18f07db2012-08-06 03:25:17 +00002723 // C++11 [class.virtual]p5:
David Blaikie1cbb9712014-11-14 19:09:44 +00002724 // If a function is marked with the virt-specifier override and
Richard Smith18f07db2012-08-06 03:25:17 +00002725 // does not override a member function of a base class, the program is
2726 // ill-formed.
2727 bool HasOverriddenMethods =
2728 MD->begin_overridden_methods() != MD->end_overridden_methods();
2729 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2730 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2731 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00002732}
2733
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00002734void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2735 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2736 return;
2737 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Richard Trieu07c93382017-03-01 03:07:55 +00002738 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00002739 return;
2740
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00002741 SourceLocation Loc = MD->getLocation();
2742 SourceLocation SpellingLoc = Loc;
2743 if (getSourceManager().isMacroArgExpansion(Loc))
2744 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
2745 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2746 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
Fariborz Jahanian6e213382014-10-31 19:56:27 +00002747 return;
Richard Trieu07c93382017-03-01 03:07:55 +00002748
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00002749 if (MD->size_overridden_methods() > 0) {
Richard Trieu07c93382017-03-01 03:07:55 +00002750 unsigned DiagID = isa<CXXDestructorDecl>(MD)
2751 ? diag::warn_destructor_marked_not_override_overriding
2752 : diag::warn_function_marked_not_override_overriding;
2753 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00002754 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2755 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2756 }
2757}
2758
Richard Smith18f07db2012-08-06 03:25:17 +00002759/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00002760/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00002761/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00002762bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2763 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00002764 FinalAttr *FA = Old->getAttr<FinalAttr>();
2765 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00002766 return false;
2767
2768 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00002769 << New->getDeclName()
2770 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00002771 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2772 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00002773}
2774
Daniel Jasper0baec5492012-06-06 08:32:04 +00002775static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00002776 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2777 // FIXME: Destruction of ObjC lifetime types has side-effects.
2778 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2779 return !RD->isCompleteDefinition() ||
2780 !RD->hasTrivialDefaultConstructor() ||
2781 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00002782 return false;
2783}
2784
John McCall5e77d762013-04-16 07:28:30 +00002785static AttributeList *getMSPropertyAttr(AttributeList *list) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002786 for (AttributeList *it = list; it != nullptr; it = it->getNext())
John McCall5e77d762013-04-16 07:28:30 +00002787 if (it->isDeclspecPropertyAttribute())
2788 return it;
Craig Topperc3ec1492014-05-26 06:22:03 +00002789 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +00002790}
2791
Saleem Abdulrasoola6ae0602017-02-08 03:30:13 +00002792// Check if there is a field shadowing.
2793void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2794 DeclarationName FieldName,
2795 const CXXRecordDecl *RD) {
2796 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2797 return;
2798
2799 // To record a shadowed field in a base
2800 std::map<CXXRecordDecl*, NamedDecl*> Bases;
2801 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2802 CXXBasePath &Path) {
2803 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2804 // Record an ambiguous path directly
2805 if (Bases.find(Base) != Bases.end())
2806 return true;
2807 for (const auto Field : Base->lookup(FieldName)) {
2808 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2809 Field->getAccess() != AS_private) {
2810 assert(Field->getAccess() != AS_none);
2811 assert(Bases.find(Base) == Bases.end());
2812 Bases[Base] = Field;
2813 return true;
2814 }
2815 }
2816 return false;
2817 };
2818
2819 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2820 /*DetectVirtual=*/true);
2821 if (!RD->lookupInBases(FieldShadowed, Paths))
2822 return;
2823
2824 for (const auto &P : Paths) {
2825 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2826 auto It = Bases.find(Base);
2827 // Skip duplicated bases
2828 if (It == Bases.end())
2829 continue;
2830 auto BaseField = It->second;
2831 assert(BaseField->getAccess() != AS_private);
2832 if (AS_none !=
2833 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2834 Diag(Loc, diag::warn_shadow_field)
2835 << FieldName.getAsString() << RD->getName() << Base->getName();
2836 Diag(BaseField->getLocation(), diag::note_shadow_field);
2837 Bases.erase(It);
2838 }
2839 }
2840}
2841
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002842/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2843/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00002844/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00002845/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2846/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002847NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002848Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00002849 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00002850 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00002851 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002852 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002853 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2854 DeclarationName Name = NameInfo.getName();
2855 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00002856
2857 // For anonymous bitfields, the location should point to the type.
2858 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002859 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00002860
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002861 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002862
John McCallb1cd7da2010-06-04 08:34:12 +00002863 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00002864 assert(!DS.isFriendSpecified());
2865
Richard Smithcfcdf3a2011-06-25 02:28:38 +00002866 bool isFunc = D.isDeclarationOfFunction();
Erich Keanebb863642017-09-20 22:28:24 +00002867 AttributeList *MSPropertyAttr =
2868 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
John McCallb1cd7da2010-06-04 08:34:12 +00002869
John McCalldb632ac2012-09-25 07:32:39 +00002870 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2871 // The Microsoft extension __interface only permits public member functions
2872 // and prohibits constructors, destructors, operators, non-public member
2873 // functions, static methods and data members.
2874 unsigned InvalidDecl;
2875 bool ShowDeclName = true;
Erich Keanebb863642017-09-20 22:28:24 +00002876 if (!isFunc &&
2877 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
2878 InvalidDecl = 0;
2879 else if (!isFunc)
2880 InvalidDecl = 1;
John McCalldb632ac2012-09-25 07:32:39 +00002881 else if (AS != AS_public)
2882 InvalidDecl = 2;
2883 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2884 InvalidDecl = 3;
2885 else switch (Name.getNameKind()) {
2886 case DeclarationName::CXXConstructorName:
2887 InvalidDecl = 4;
2888 ShowDeclName = false;
2889 break;
2890
2891 case DeclarationName::CXXDestructorName:
2892 InvalidDecl = 5;
2893 ShowDeclName = false;
2894 break;
2895
2896 case DeclarationName::CXXOperatorName:
2897 case DeclarationName::CXXConversionFunctionName:
2898 InvalidDecl = 6;
2899 break;
2900
2901 default:
2902 InvalidDecl = 0;
2903 break;
2904 }
2905
2906 if (InvalidDecl) {
2907 if (ShowDeclName)
2908 Diag(Loc, diag::err_invalid_member_in_interface)
2909 << (InvalidDecl-1) << Name;
2910 else
2911 Diag(Loc, diag::err_invalid_member_in_interface)
2912 << (InvalidDecl-1) << "";
Craig Topperc3ec1492014-05-26 06:22:03 +00002913 return nullptr;
John McCalldb632ac2012-09-25 07:32:39 +00002914 }
2915 }
2916
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002917 // C++ 9.2p6: A member shall not be declared to have automatic storage
2918 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002919 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2920 // data members and cannot be applied to names declared const or static,
2921 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002922 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00002923 case DeclSpec::SCS_unspecified:
2924 case DeclSpec::SCS_typedef:
2925 case DeclSpec::SCS_static:
2926 break;
2927 case DeclSpec::SCS_mutable:
2928 if (isFunc) {
2929 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00002930
Richard Smithb4a9e862013-04-12 22:46:28 +00002931 // FIXME: It would be nicer if the keyword was ignored only for this
2932 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002933 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00002934 }
2935 break;
2936 default:
2937 Diag(DS.getStorageClassSpecLoc(),
2938 diag::err_storageclass_invalid_for_member);
2939 D.getMutableDeclSpec().ClearStorageClassSpecs();
2940 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002941 }
2942
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002943 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2944 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00002945 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002946
David Blaikie35506f82013-01-30 01:22:18 +00002947 if (DS.isConstexprSpecified() && isInstField) {
2948 SemaDiagnosticBuilder B =
2949 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2950 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2951 if (InitStyle == ICIS_NoInit) {
Richard Smith82dce552014-04-14 21:00:40 +00002952 B << 0 << 0;
2953 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2954 B << FixItHint::CreateRemoval(ConstexprLoc);
2955 else {
2956 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2957 D.getMutableDeclSpec().ClearConstexprSpec();
2958 const char *PrevSpec;
2959 unsigned DiagID;
2960 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2961 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2962 (void)Failed;
2963 assert(!Failed && "Making a constexpr member const shouldn't fail");
2964 }
David Blaikie35506f82013-01-30 01:22:18 +00002965 } else {
2966 B << 1;
2967 const char *PrevSpec;
2968 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00002969 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002970 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2971 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00002972 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00002973 "This is the only DeclSpec that should fail to be applied");
2974 B << 1;
2975 } else {
2976 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2977 isInstField = false;
2978 }
2979 }
2980 }
2981
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002982 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00002983 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00002984 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002985
2986 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00002987 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002988 Diag(Loc, diag::err_bad_variable_name)
2989 << Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002990 return nullptr;
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002991 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002992
Benjamin Kramer365082d2012-05-19 16:34:46 +00002993 IdentifierInfo *II = Name.getAsIdentifierInfo();
2994
Douglas Gregor7c26c042011-09-21 14:40:46 +00002995 // Member field could not be with "template" keyword.
2996 // So TemplateParameterLists should be empty in this case.
2997 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002998 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002999 if (TemplateParams->size()) {
3000 // There is no such thing as a member field template.
3001 Diag(D.getIdentifierLoc(), diag::err_template_member)
3002 << II
3003 << SourceRange(TemplateParams->getTemplateLoc(),
3004 TemplateParams->getRAngleLoc());
3005 } else {
3006 // There is an extraneous 'template<>' for this member.
3007 Diag(TemplateParams->getTemplateLoc(),
3008 diag::err_template_member_noparams)
3009 << II
3010 << SourceRange(TemplateParams->getTemplateLoc(),
3011 TemplateParams->getRAngleLoc());
3012 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003013 return nullptr;
Douglas Gregor7c26c042011-09-21 14:40:46 +00003014 }
3015
Douglas Gregora007d362010-10-13 22:19:53 +00003016 if (SS.isSet() && !SS.isInvalid()) {
3017 // The user provided a superfluous scope specifier inside a class
3018 // definition:
3019 //
3020 // class X {
3021 // int X::member;
3022 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00003023 if (DeclContext *DC = computeDeclContext(SS, false))
3024 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00003025 else
3026 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3027 << Name << SS.getRange();
Erich Keanebb863642017-09-20 22:28:24 +00003028
Douglas Gregora007d362010-10-13 22:19:53 +00003029 SS.clear();
3030 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00003031
Eli Friedmanc37dbf72013-06-28 20:48:34 +00003032 if (MSPropertyAttr) {
3033 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3034 BitWidth, InitStyle, AS, MSPropertyAttr);
3035 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00003036 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00003037 isInstField = false;
3038 } else {
3039 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3040 BitWidth, InitStyle, AS);
Richard Smithbdb84f32016-07-22 23:36:59 +00003041 if (!Member)
3042 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00003043 }
Saleem Abdulrasoola6ae0602017-02-08 03:30:13 +00003044
Saleem Abdulrasoolb893ed22017-02-11 17:24:04 +00003045 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
Eli Friedmanc37dbf72013-06-28 20:48:34 +00003046 } else {
Eli Friedmanc37dbf72013-06-28 20:48:34 +00003047 Member = HandleDeclarator(S, D, TemplateParameterLists);
3048 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00003049 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00003050
3051 // Non-instance-fields can't have a bitfield.
3052 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00003053 if (Member->isInvalidDecl()) {
3054 // don't emit another diagnostic.
David Majnemer380443a2014-12-28 22:51:45 +00003055 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00003056 // C++ 9.6p3: A bit-field shall not be a static member.
3057 // "static member 'A' cannot be a bit-field"
3058 Diag(Loc, diag::err_static_not_bitfield)
3059 << Name << BitWidth->getSourceRange();
3060 } else if (isa<TypedefDecl>(Member)) {
3061 // "typedef member 'x' cannot be a bit-field"
3062 Diag(Loc, diag::err_typedef_not_bitfield)
3063 << Name << BitWidth->getSourceRange();
3064 } else {
3065 // A function typedef ("typedef int f(); f a;").
3066 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3067 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00003068 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00003069 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00003070 }
Mike Stump11289f42009-09-09 15:08:12 +00003071
Craig Topperc3ec1492014-05-26 06:22:03 +00003072 BitWidth = nullptr;
Chris Lattnerd26760a2009-03-05 23:01:03 +00003073 Member->setInvalidDecl();
3074 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00003075
3076 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00003077
Larisse Voufo39a1e502013-08-06 01:03:05 +00003078 // If we have declared a member function template or static data member
3079 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00003080 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3081 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003082 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3083 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00003084 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003085
Richard Smith18f07db2012-08-06 03:25:17 +00003086 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00003087 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00003088 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00003089 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3090 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00003091
Douglas Gregorf2f08062011-03-08 17:10:18 +00003092 if (VS.getLastLocation().isValid()) {
3093 // Update the end location of a method that has a virt-specifiers.
3094 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3095 MD->setRangeEnd(VS.getLastLocation());
3096 }
Richard Smith18f07db2012-08-06 03:25:17 +00003097
Anders Carlssonc87f8612011-01-20 06:29:02 +00003098 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00003099
Douglas Gregor92751d42008-11-17 22:58:34 +00003100 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003101
Daniel Jasper0baec5492012-06-06 08:32:04 +00003102 if (isInstField) {
3103 FieldDecl *FD = cast<FieldDecl>(Member);
3104 FieldCollector->Add(FD);
3105
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00003106 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
Daniel Jasper0baec5492012-06-06 08:32:04 +00003107 // Remember all explicit private FieldDecls that have a name, no side
3108 // effects and are not part of a dependent type declaration.
3109 if (!FD->isImplicit() && FD->getDeclName() &&
3110 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00003111 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00003112 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00003113 !InitializationHasSideEffects(*FD))
3114 UnusedPrivateFields.insert(FD);
3115 }
3116 }
3117
John McCall48871652010-08-21 09:40:31 +00003118 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003119}
3120
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003121namespace {
3122 class UninitializedFieldVisitor
3123 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3124 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00003125 // List of Decls to generate a warning on. Also remove Decls that become
3126 // initialized.
Craig Topper4dd9b432014-08-17 23:49:53 +00003127 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
Richard Trieu3630c392014-11-21 03:10:30 +00003128 // List of base classes of the record. Classes are removed after their
3129 // initializers.
3130 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
Richard Trieu8d08a272014-08-28 03:23:47 +00003131 // Vector of decls to be removed from the Decl set prior to visiting the
3132 // nodes. These Decls may have been initialized in the prior initializer.
3133 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
Richard Trieu406e65c2013-09-20 03:03:06 +00003134 // If non-null, add a note to the warning pointing back to the constructor.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00003135 const CXXConstructorDecl *Constructor;
Nick Lewycky314a4492014-10-17 22:45:44 +00003136 // Variables to hold state when processing an initializer list. When
Richard Trieufa1d0a72014-10-17 20:56:10 +00003137 // InitList is true, special case initialization of FieldDecls matching
3138 // InitListFieldDecl.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00003139 bool InitList;
3140 FieldDecl *InitListFieldDecl;
Richard Trieufa1d0a72014-10-17 20:56:10 +00003141 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3142
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003143 public:
3144 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00003145 UninitializedFieldVisitor(Sema &S,
Richard Trieu3630c392014-11-21 03:10:30 +00003146 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3147 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3148 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3149 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003150
Richard Trieufa1d0a72014-10-17 20:56:10 +00003151 // Returns true if the use of ME is not an uninitialized use.
3152 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3153 bool CheckReferenceOnly) {
3154 llvm::SmallVector<FieldDecl*, 4> Fields;
3155 bool ReferenceField = false;
3156 while (ME) {
3157 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3158 if (!FD)
3159 return false;
3160 Fields.push_back(FD);
3161 if (FD->getType()->isReferenceType())
3162 ReferenceField = true;
3163 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3164 }
3165
3166 // Binding a reference to an unintialized field is not an
3167 // uninitialized use.
3168 if (CheckReferenceOnly && !ReferenceField)
3169 return true;
3170
3171 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3172 // Discard the first field since it is the field decl that is being
3173 // initialized.
3174 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3175 UsedFieldIndex.push_back((*I)->getFieldIndex());
3176 }
3177
3178 for (auto UsedIter = UsedFieldIndex.begin(),
3179 UsedEnd = UsedFieldIndex.end(),
3180 OrigIter = InitFieldIndex.begin(),
3181 OrigEnd = InitFieldIndex.end();
3182 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3183 if (*UsedIter < *OrigIter)
3184 return true;
3185 if (*UsedIter > *OrigIter)
3186 break;
3187 }
3188
3189 return false;
3190 }
3191
Richard Trieu2d779b92014-10-01 03:44:58 +00003192 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3193 bool AddressOf) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00003194 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3195 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003196
Richard Trieu1bc22c12013-09-13 03:20:53 +00003197 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3198 // or union.
3199 MemberExpr *FieldME = ME;
3200
Richard Trieu2d779b92014-10-01 03:44:58 +00003201 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3202
Richard Trieu1bc22c12013-09-13 03:20:53 +00003203 Expr *Base = ME;
Richard Trieu3630c392014-11-21 03:10:30 +00003204 while (MemberExpr *SubME =
3205 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00003206
Richard Trieufa1d0a72014-10-17 20:56:10 +00003207 if (isa<VarDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00003208 return;
3209
Richard Trieufa1d0a72014-10-17 20:56:10 +00003210 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00003211 if (!FD->isAnonymousStructOrUnion())
Richard Trieufa1d0a72014-10-17 20:56:10 +00003212 FieldME = SubME;
Richard Trieu1bc22c12013-09-13 03:20:53 +00003213
Richard Trieu2d779b92014-10-01 03:44:58 +00003214 if (!FieldME->getType().isPODType(S.Context))
3215 AllPODFields = false;
3216
Richard Trieu3630c392014-11-21 03:10:30 +00003217 Base = SubME->getBase();
Richard Trieu1bc22c12013-09-13 03:20:53 +00003218 }
3219
Richard Trieu3630c392014-11-21 03:10:30 +00003220 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
Richard Trieufd687772013-09-16 20:46:50 +00003221 return;
3222
Richard Trieu2d779b92014-10-01 03:44:58 +00003223 if (AddressOf && AllPODFields)
3224 return;
3225
Richard Trieu406e65c2013-09-20 03:03:06 +00003226 ValueDecl* FoundVD = FieldME->getMemberDecl();
3227
Richard Trieu3630c392014-11-21 03:10:30 +00003228 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3229 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3230 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3231 }
3232
3233 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3234 QualType T = BaseCast->getType();
3235 if (T->isPointerType() &&
3236 BaseClasses.count(T->getPointeeType())) {
3237 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3238 << T->getPointeeType() << FoundVD;
3239 }
3240 }
3241 }
3242
Richard Trieuef64e942013-10-25 00:56:00 +00003243 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00003244 return;
3245
Richard Trieuef64e942013-10-25 00:56:00 +00003246 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00003247
Richard Trieufa1d0a72014-10-17 20:56:10 +00003248 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3249 // Special checking for initializer lists.
3250 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3251 return;
3252 }
3253 } else {
3254 // Prevent double warnings on use of unbounded references.
3255 if (CheckReferenceOnly && !IsReference)
3256 return;
3257 }
Richard Trieuef64e942013-10-25 00:56:00 +00003258
3259 unsigned diag = IsReference
3260 ? diag::warn_reference_field_is_uninit
3261 : diag::warn_field_is_uninit;
3262 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3263 if (Constructor)
3264 S.Diag(Constructor->getLocation(),
3265 diag::note_uninit_in_this_constructor)
3266 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3267
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003268 }
3269
Richard Trieu2d779b92014-10-01 03:44:58 +00003270 void HandleValue(Expr *E, bool AddressOf) {
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003271 E = E->IgnoreParens();
3272
3273 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003274 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3275 AddressOf /*AddressOf*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00003276 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003277 }
3278
3279 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003280 Visit(CO->getCond());
3281 HandleValue(CO->getTrueExpr(), AddressOf);
3282 HandleValue(CO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003283 return;
3284 }
3285
3286 if (BinaryConditionalOperator *BCO =
3287 dyn_cast<BinaryConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003288 Visit(BCO->getCond());
3289 HandleValue(BCO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003290 return;
3291 }
3292
Richard Trieuabf6ec42014-08-27 22:15:10 +00003293 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003294 HandleValue(OVE->getSourceExpr(), AddressOf);
Richard Trieuabf6ec42014-08-27 22:15:10 +00003295 return;
3296 }
3297
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003298 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3299 switch (BO->getOpcode()) {
3300 default:
Richard Trieu2d779b92014-10-01 03:44:58 +00003301 break;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003302 case(BO_PtrMemD):
3303 case(BO_PtrMemI):
Richard Trieu2d779b92014-10-01 03:44:58 +00003304 HandleValue(BO->getLHS(), AddressOf);
3305 Visit(BO->getRHS());
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003306 return;
3307 case(BO_Comma):
Richard Trieu2d779b92014-10-01 03:44:58 +00003308 Visit(BO->getLHS());
3309 HandleValue(BO->getRHS(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003310 return;
3311 }
3312 }
Richard Trieu2d779b92014-10-01 03:44:58 +00003313
3314 Visit(E);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003315 }
3316
Richard Trieufa1d0a72014-10-17 20:56:10 +00003317 void CheckInitListExpr(InitListExpr *ILE) {
3318 InitFieldIndex.push_back(0);
3319 for (auto Child : ILE->children()) {
3320 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3321 CheckInitListExpr(SubList);
3322 } else {
3323 Visit(Child);
3324 }
3325 ++InitFieldIndex.back();
3326 }
3327 InitFieldIndex.pop_back();
3328 }
3329
Richard Trieu8d08a272014-08-28 03:23:47 +00003330 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
Richard Trieu3630c392014-11-21 03:10:30 +00003331 FieldDecl *Field, const Type *BaseClass) {
Richard Trieu8d08a272014-08-28 03:23:47 +00003332 // Remove Decls that may have been initialized in the previous
3333 // initializer.
3334 for (ValueDecl* VD : DeclsToRemove)
3335 Decls.erase(VD);
Richard Trieu8d08a272014-08-28 03:23:47 +00003336 DeclsToRemove.clear();
Richard Trieufa1d0a72014-10-17 20:56:10 +00003337
Richard Trieu8d08a272014-08-28 03:23:47 +00003338 Constructor = FieldConstructor;
Richard Trieufa1d0a72014-10-17 20:56:10 +00003339 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3340
3341 if (ILE && Field) {
3342 InitList = true;
3343 InitListFieldDecl = Field;
3344 InitFieldIndex.clear();
3345 CheckInitListExpr(ILE);
3346 } else {
3347 InitList = false;
3348 Visit(E);
3349 }
3350
Richard Trieu8d08a272014-08-28 03:23:47 +00003351 if (Field)
3352 Decls.erase(Field);
Richard Trieu3630c392014-11-21 03:10:30 +00003353 if (BaseClass)
3354 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
Richard Trieu8d08a272014-08-28 03:23:47 +00003355 }
3356
Richard Trieu1bc22c12013-09-13 03:20:53 +00003357 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00003358 // All uses of unbounded reference fields will warn.
Richard Trieu2d779b92014-10-01 03:44:58 +00003359 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00003360 }
3361
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003362 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003363 if (E->getCastKind() == CK_LValueToRValue) {
3364 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3365 return;
3366 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003367
3368 Inherited::VisitImplicitCastExpr(E);
3369 }
3370
Richard Trieu1bc22c12013-09-13 03:20:53 +00003371 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu4834ad22014-08-12 21:05:04 +00003372 if (E->getConstructor()->isCopyConstructor()) {
3373 Expr *ArgExpr = E->getArg(0);
Richard Trieu2d779b92014-10-01 03:44:58 +00003374 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3375 if (ILE->getNumInits() == 1)
3376 ArgExpr = ILE->getInit(0);
3377 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3378 if (ICE->getCastKind() == CK_NoOp)
Richard Trieu4834ad22014-08-12 21:05:04 +00003379 ArgExpr = ICE->getSubExpr();
Richard Trieu2d779b92014-10-01 03:44:58 +00003380 HandleValue(ArgExpr, false /*AddressOf*/);
3381 return;
Richard Trieu4834ad22014-08-12 21:05:04 +00003382 }
Richard Trieu1bc22c12013-09-13 03:20:53 +00003383 Inherited::VisitCXXConstructExpr(E);
3384 }
3385
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003386 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3387 Expr *Callee = E->getCallee();
Richard Trieu2d779b92014-10-01 03:44:58 +00003388 if (isa<MemberExpr>(Callee)) {
3389 HandleValue(Callee, false /*AddressOf*/);
Richard Trieu46847422014-11-01 00:46:54 +00003390 for (auto Arg : E->arguments())
3391 Visit(Arg);
Richard Trieu2d779b92014-10-01 03:44:58 +00003392 return;
3393 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003394
3395 Inherited::VisitCXXMemberCallExpr(E);
3396 }
Richard Trieu406e65c2013-09-20 03:03:06 +00003397
Richard Trieu11fd0792014-08-26 04:30:55 +00003398 void VisitCallExpr(CallExpr *E) {
3399 // Treat std::move as a use.
Nico Weberb688d132017-09-28 16:16:39 +00003400 if (E->isCallToStdMove()) {
3401 HandleValue(E->getArg(0), /*AddressOf=*/false);
3402 return;
Richard Trieu11fd0792014-08-26 04:30:55 +00003403 }
3404
3405 Inherited::VisitCallExpr(E);
3406 }
3407
Richard Trieud4a01362014-10-31 21:10:22 +00003408 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3409 Expr *Callee = E->getCallee();
3410
3411 if (isa<UnresolvedLookupExpr>(Callee))
3412 return Inherited::VisitCXXOperatorCallExpr(E);
3413
3414 Visit(Callee);
3415 for (auto Arg : E->arguments())
3416 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3417 }
3418
Richard Trieu406e65c2013-09-20 03:03:06 +00003419 void VisitBinaryOperator(BinaryOperator *E) {
3420 // If a field assignment is detected, remove the field from the
3421 // uninitiailized field set.
3422 if (E->getOpcode() == BO_Assign)
3423 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3424 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00003425 if (!FD->getType()->isReferenceType())
Richard Trieu8d08a272014-08-28 03:23:47 +00003426 DeclsToRemove.push_back(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00003427
Richard Trieu52b8b602014-09-25 01:15:40 +00003428 if (E->isCompoundAssignmentOp()) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003429 HandleValue(E->getLHS(), false /*AddressOf*/);
3430 Visit(E->getRHS());
3431 return;
Richard Trieu52b8b602014-09-25 01:15:40 +00003432 }
3433
Richard Trieu406e65c2013-09-20 03:03:06 +00003434 Inherited::VisitBinaryOperator(E);
3435 }
Richard Trieu52b8b602014-09-25 01:15:40 +00003436
3437 void VisitUnaryOperator(UnaryOperator *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003438 if (E->isIncrementDecrementOp()) {
3439 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3440 return;
3441 }
3442 if (E->getOpcode() == UO_AddrOf) {
3443 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3444 HandleValue(ME->getBase(), true /*AddressOf*/);
3445 return;
3446 }
3447 }
Richard Trieu52b8b602014-09-25 01:15:40 +00003448
3449 Inherited::VisitUnaryOperator(E);
3450 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003451 };
Richard Trieuef64e942013-10-25 00:56:00 +00003452
3453 // Diagnose value-uses of fields to initialize themselves, e.g.
3454 // foo(foo)
3455 // where foo is not also a parameter to the constructor.
3456 // Also diagnose across field uninitialized use such as
3457 // x(y), y(x)
3458 // TODO: implement -Wuninitialized and fold this into that framework.
3459 static void DiagnoseUninitializedFields(
3460 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3461
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00003462 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3463 Constructor->getLocation())) {
Richard Trieuef64e942013-10-25 00:56:00 +00003464 return;
3465 }
3466
3467 if (Constructor->isInvalidDecl())
3468 return;
3469
3470 const CXXRecordDecl *RD = Constructor->getParent();
3471
Richard Trieu353a4b42014-10-22 05:21:59 +00003472 if (RD->getDescribedClassTemplate())
Richard Trieu277ace02014-10-22 02:52:00 +00003473 return;
3474
Richard Trieuef64e942013-10-25 00:56:00 +00003475 // Holds fields that are uninitialized.
3476 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3477
3478 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00003479 for (auto *I : RD->decls()) {
3480 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00003481 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00003482 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00003483 UninitializedFields.insert(IFD->getAnonField());
3484 }
3485 }
3486
Richard Trieu3630c392014-11-21 03:10:30 +00003487 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3488 for (auto I : RD->bases())
3489 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3490
3491 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00003492 return;
3493
3494 UninitializedFieldVisitor UninitializedChecker(SemaRef,
Richard Trieu3630c392014-11-21 03:10:30 +00003495 UninitializedFields,
3496 UninitializedBaseClasses);
Richard Trieu8d08a272014-08-28 03:23:47 +00003497
Aaron Ballman0ad78302014-03-13 17:34:31 +00003498 for (const auto *FieldInit : Constructor->inits()) {
Richard Trieu3630c392014-11-21 03:10:30 +00003499 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00003500 break;
3501
Aaron Ballman0ad78302014-03-13 17:34:31 +00003502 Expr *InitExpr = FieldInit->getInit();
Richard Trieu8d08a272014-08-28 03:23:47 +00003503 if (!InitExpr)
3504 continue;
Richard Trieuef64e942013-10-25 00:56:00 +00003505
Richard Trieu8d08a272014-08-28 03:23:47 +00003506 if (CXXDefaultInitExpr *Default =
3507 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3508 InitExpr = Default->getExpr();
3509 if (!InitExpr)
3510 continue;
3511 // In class initializers will point to the constructor.
3512 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
Richard Trieu3630c392014-11-21 03:10:30 +00003513 FieldInit->getAnyMember(),
3514 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00003515 } else {
3516 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
Richard Trieu3630c392014-11-21 03:10:30 +00003517 FieldInit->getAnyMember(),
3518 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00003519 }
Richard Trieuef64e942013-10-25 00:56:00 +00003520 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003521 }
3522} // namespace
3523
Richard Smith74108172014-01-17 03:11:34 +00003524/// \brief Enter a new C++ default initializer scope. After calling this, the
3525/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3526/// parsing or instantiating the initializer failed.
3527void Sema::ActOnStartCXXInClassMemberInitializer() {
3528 // Create a synthetic function scope to represent the call to the constructor
3529 // that notionally surrounds a use of this initializer.
3530 PushFunctionScope();
3531}
3532
3533/// \brief This is invoked after parsing an in-class initializer for a
3534/// non-static C++ class member, and after instantiating an in-class initializer
3535/// in a class template. Such actions are deferred until the class is complete.
3536void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3537 SourceLocation InitLoc,
3538 Expr *InitExpr) {
3539 // Pop the notional constructor scope we created earlier.
Craig Topperc3ec1492014-05-26 06:22:03 +00003540 PopFunctionScopeInfo(nullptr, D);
Richard Smith74108172014-01-17 03:11:34 +00003541
David Majnemer87ff66c2014-12-13 11:34:16 +00003542 FieldDecl *FD = dyn_cast<FieldDecl>(D);
3543 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
Richard Smith2b013182012-06-10 03:12:00 +00003544 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00003545
3546 if (!InitExpr) {
David Majnemer87ff66c2014-12-13 11:34:16 +00003547 D->setInvalidDecl();
3548 if (FD)
3549 FD->removeInClassInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00003550 return;
3551 }
3552
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00003553 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3554 FD->setInvalidDecl();
3555 FD->removeInClassInitializer();
3556 return;
3557 }
3558
Richard Smith938f40b2011-06-11 17:19:42 +00003559 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00003560 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00003561 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00003562 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00003563 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00003564 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003565 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3566 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00003567 if (Init.isInvalid()) {
3568 FD->setInvalidDecl();
3569 return;
3570 }
Richard Smith938f40b2011-06-11 17:19:42 +00003571 }
3572
Richard Smith945f8d32013-01-14 22:39:08 +00003573 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00003574 // The initialization of each base and member constitutes a
3575 // full-expression.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003576 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00003577 if (Init.isInvalid()) {
3578 FD->setInvalidDecl();
3579 return;
3580 }
3581
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003582 InitExpr = Init.get();
Richard Smith938f40b2011-06-11 17:19:42 +00003583
3584 FD->setInClassInitializer(InitExpr);
3585}
3586
Douglas Gregor15e77a22009-12-31 09:10:24 +00003587/// \brief Find the direct and/or virtual base specifiers that
3588/// correspond to the given base type, for use in base initialization
3589/// within a constructor.
Erich Keanebb863642017-09-20 22:28:24 +00003590static bool FindBaseInitializer(Sema &SemaRef,
Douglas Gregor15e77a22009-12-31 09:10:24 +00003591 CXXRecordDecl *ClassDecl,
3592 QualType BaseType,
3593 const CXXBaseSpecifier *&DirectBaseSpec,
3594 const CXXBaseSpecifier *&VirtualBaseSpec) {
3595 // First, check for a direct base class.
Craig Topperc3ec1492014-05-26 06:22:03 +00003596 DirectBaseSpec = nullptr;
Aaron Ballman574705e2014-03-13 15:41:46 +00003597 for (const auto &Base : ClassDecl->bases()) {
3598 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00003599 // We found a direct base of this type. That's what we're
3600 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00003601 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00003602 break;
3603 }
3604 }
3605
3606 // Check for a virtual base class.
3607 // FIXME: We might be able to short-circuit this if we know in advance that
3608 // there are no virtual bases.
Craig Topperc3ec1492014-05-26 06:22:03 +00003609 VirtualBaseSpec = nullptr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00003610 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3611 // We haven't found a base yet; search the class hierarchy for a
3612 // virtual base class.
3613 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3614 /*DetectVirtual=*/false);
Richard Smith0f59cb32015-12-18 21:45:41 +00003615 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3616 SemaRef.Context.getTypeDeclType(ClassDecl),
Douglas Gregor15e77a22009-12-31 09:10:24 +00003617 BaseType, Paths)) {
3618 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3619 Path != Paths.end(); ++Path) {
3620 if (Path->back().Base->isVirtual()) {
3621 VirtualBaseSpec = Path->back().Base;
3622 break;
3623 }
3624 }
3625 }
3626 }
3627
3628 return DirectBaseSpec || VirtualBaseSpec;
3629}
3630
Sebastian Redla74948d2011-09-24 17:48:25 +00003631/// \brief Handle a C++ member initializer using braced-init-list syntax.
3632MemInitResult
3633Sema::ActOnMemInitializer(Decl *ConstructorD,
3634 Scope *S,
3635 CXXScopeSpec &SS,
3636 IdentifierInfo *MemberOrBase,
3637 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00003638 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00003639 SourceLocation IdLoc,
3640 Expr *InitList,
3641 SourceLocation EllipsisLoc) {
3642 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00003643 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00003644 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003645}
3646
3647/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00003648MemInitResult
John McCall48871652010-08-21 09:40:31 +00003649Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00003650 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003651 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00003652 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00003653 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00003654 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00003655 SourceLocation IdLoc,
3656 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00003657 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00003658 SourceLocation RParenLoc,
3659 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003660 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00003661 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003662 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00003663 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003664}
3665
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003666namespace {
3667
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00003668// Callback to only accept typo corrections that can be a valid C++ member
3669// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003670class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003671public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003672 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3673 : ClassDecl(ClassDecl) {}
3674
Craig Toppera798a9d2014-03-02 09:32:10 +00003675 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003676 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3677 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3678 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003679 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003680 }
3681 return false;
3682 }
3683
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003684private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003685 CXXRecordDecl *ClassDecl;
3686};
3687
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003688}
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003689
Sebastian Redla74948d2011-09-24 17:48:25 +00003690/// \brief Handle a C++ member initializer.
3691MemInitResult
3692Sema::BuildMemInitializer(Decl *ConstructorD,
3693 Scope *S,
3694 CXXScopeSpec &SS,
3695 IdentifierInfo *MemberOrBase,
3696 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00003697 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00003698 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00003699 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00003700 SourceLocation EllipsisLoc) {
Kaelyn Takataa15a6dc2014-12-08 22:41:42 +00003701 ExprResult Res = CorrectDelayedTyposInExpr(Init);
3702 if (!Res.isUsable())
3703 return true;
3704 Init = Res.get();
3705
Douglas Gregor71a57182009-06-22 23:20:33 +00003706 if (!ConstructorD)
3707 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003708
Douglas Gregorc8c277a2009-08-24 11:57:43 +00003709 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00003710
3711 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003712 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00003713 if (!Constructor) {
3714 // The user wrote a constructor initializer on a function that is
3715 // not a C++ constructor. Ignore the error for now, because we may
3716 // have more member initializers coming; we'll diagnose it just
3717 // once in ActOnMemInitializers.
3718 return true;
3719 }
3720
3721 CXXRecordDecl *ClassDecl = Constructor->getParent();
3722
3723 // C++ [class.base.init]p2:
3724 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00003725 // constructor's class and, if not found in that scope, are looked
3726 // up in the scope containing the constructor's definition.
3727 // [Note: if the constructor's class contains a member with the
3728 // same name as a direct or virtual base class of the class, a
3729 // mem-initializer-id naming the member or base class and composed
3730 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00003731 // mem-initializer-id for the hidden base class may be specified
3732 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003733 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00003734 // Look for a member, first.
Nico Weberaa0117c2014-11-12 03:44:43 +00003735 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00003736 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00003737 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00003738 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3739 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00003740 if (EllipsisLoc.isValid())
3741 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00003742 << MemberOrBase
3743 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00003744
Sebastian Redla9351792012-02-11 23:51:47 +00003745 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00003746 }
Francois Pichetd583da02010-12-04 09:14:42 +00003747 }
Douglas Gregore8381c02008-11-05 04:29:56 +00003748 }
Douglas Gregore8381c02008-11-05 04:29:56 +00003749 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00003750 QualType BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00003751 TypeSourceInfo *TInfo = nullptr;
John McCallb5a0d312009-12-21 10:41:20 +00003752
3753 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00003754 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00003755 } else if (DS.getTypeSpecType() == TST_decltype) {
3756 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
Richard Smithef2cd8f2017-02-08 20:39:08 +00003757 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3758 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3759 return true;
John McCallb5a0d312009-12-21 10:41:20 +00003760 } else {
3761 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3762 LookupParsedName(R, S, &SS);
3763
3764 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3765 if (!TyD) {
3766 if (R.isAmbiguous()) return true;
3767
John McCallda6841b2010-04-09 19:01:14 +00003768 // We don't want access-control diagnostics here.
3769 R.suppressDiagnostics();
3770
Douglas Gregora3b624a2010-01-19 06:46:48 +00003771 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3772 bool NotUnknownSpecialization = false;
3773 DeclContext *DC = computeDeclContext(SS, false);
Erich Keanebb863642017-09-20 22:28:24 +00003774 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
Douglas Gregora3b624a2010-01-19 06:46:48 +00003775 NotUnknownSpecialization = !Record->hasAnyDependentBases();
3776
3777 if (!NotUnknownSpecialization) {
3778 // When the scope specifier can refer to a member of an unknown
3779 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00003780 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3781 SS.getWithLocInContext(Context),
3782 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00003783 if (BaseType.isNull())
3784 return true;
3785
Alex Lorenz99bee7f2017-06-27 10:35:30 +00003786 TInfo = Context.CreateTypeSourceInfo(BaseType);
3787 DependentNameTypeLoc TL =
3788 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
3789 if (!TL.isNull()) {
3790 TL.setNameLoc(IdLoc);
3791 TL.setElaboratedKeywordLoc(SourceLocation());
3792 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3793 }
3794
Douglas Gregora3b624a2010-01-19 06:46:48 +00003795 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00003796 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00003797 }
3798 }
3799
Douglas Gregor15e77a22009-12-31 09:10:24 +00003800 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003801 TypoCorrection Corr;
Douglas Gregora3b624a2010-01-19 06:46:48 +00003802 if (R.empty() && BaseType.isNull() &&
Kaelyn Takata89c881b2014-10-27 18:07:29 +00003803 (Corr = CorrectTypo(
3804 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3805 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3806 CTK_ErrorRecovery, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003807 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003808 // We have found a non-static data member with a similar
3809 // name to what was typed; complain and initialize that
3810 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00003811 diagnoseTypo(Corr,
3812 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3813 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00003814 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003815 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00003816 const CXXBaseSpecifier *DirectBaseSpec;
3817 const CXXBaseSpecifier *VirtualBaseSpec;
Erich Keanebb863642017-09-20 22:28:24 +00003818 if (FindBaseInitializer(*this, ClassDecl,
Douglas Gregor15e77a22009-12-31 09:10:24 +00003819 Context.getTypeDeclType(Type),
3820 DirectBaseSpec, VirtualBaseSpec)) {
3821 // We have found a direct or virtual base class with a
3822 // similar name to what was typed; complain and initialize
3823 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00003824 diagnoseTypo(Corr,
3825 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3826 << MemberOrBase << false,
3827 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00003828
Richard Smithf9b15102013-08-17 00:46:16 +00003829 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3830 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003831 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00003832 diag::note_base_class_specified_here)
3833 << BaseSpec->getType()
3834 << BaseSpec->getSourceRange();
3835
Douglas Gregor15e77a22009-12-31 09:10:24 +00003836 TyD = Type;
3837 }
3838 }
3839 }
3840
Douglas Gregora3b624a2010-01-19 06:46:48 +00003841 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00003842 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00003843 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00003844 return true;
3845 }
John McCallb5a0d312009-12-21 10:41:20 +00003846 }
3847
Douglas Gregora3b624a2010-01-19 06:46:48 +00003848 if (BaseType.isNull()) {
3849 BaseType = Context.getTypeDeclType(TyD);
Nico Weber28309182014-11-12 03:52:25 +00003850 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
Richard Smith97047d82015-12-12 02:17:54 +00003851 if (SS.isSet()) {
Aaron Ballman4a979672014-01-03 13:56:08 +00003852 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3853 BaseType);
Richard Smith97047d82015-12-12 02:17:54 +00003854 TInfo = Context.CreateTypeSourceInfo(BaseType);
3855 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3856 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3857 TL.setElaboratedKeywordLoc(SourceLocation());
3858 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3859 }
John McCallb5a0d312009-12-21 10:41:20 +00003860 }
3861 }
Mike Stump11289f42009-09-09 15:08:12 +00003862
John McCallbcd03502009-12-07 02:54:59 +00003863 if (!TInfo)
3864 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003865
Sebastian Redla9351792012-02-11 23:51:47 +00003866 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00003867}
3868
Chandler Carruth599deef2011-09-03 01:14:15 +00003869/// Checks a member initializer expression for cases where reference (or
3870/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00003871static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3872 Expr *Init,
3873 SourceLocation IdLoc) {
3874 QualType MemberTy = Member->getType();
3875
3876 // We only handle pointers and references currently.
3877 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3878 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3879 return;
3880
3881 const bool IsPointer = MemberTy->isPointerType();
3882 if (IsPointer) {
3883 if (const UnaryOperator *Op
3884 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3885 // The only case we're worried about with pointers requires taking the
3886 // address.
3887 if (Op->getOpcode() != UO_AddrOf)
3888 return;
3889
3890 Init = Op->getSubExpr();
3891 } else {
3892 // We only handle address-of expression initializers for pointers.
3893 return;
3894 }
3895 }
3896
Richard Smithe3b28bc2013-06-12 21:51:50 +00003897 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003898 // We only warn when referring to a non-reference parameter declaration.
3899 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3900 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00003901 return;
3902
3903 S.Diag(Init->getExprLoc(),
3904 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3905 : diag::warn_bind_ref_member_to_parameter)
3906 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003907 } else {
3908 // Other initializers are fine.
3909 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00003910 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003911
3912 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3913 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00003914}
3915
John McCallfaf5fb42010-08-26 23:41:50 +00003916MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003917Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00003918 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00003919 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3920 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3921 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00003922 "Member must be a FieldDecl or IndirectFieldDecl");
3923
Sebastian Redla9351792012-02-11 23:51:47 +00003924 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00003925 return true;
3926
Douglas Gregor266bb5f2010-11-05 22:21:31 +00003927 if (Member->isInvalidDecl())
3928 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00003929
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003930 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00003931 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003932 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00003933 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003934 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00003935 } else {
3936 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003937 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003938 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00003939
Sebastian Redla9351792012-02-11 23:51:47 +00003940 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00003941
Sebastian Redla9351792012-02-11 23:51:47 +00003942 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003943 // Can't check initialization for a member of dependent type or when
3944 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00003945 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00003946 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00003947 bool InitList = false;
3948 if (isa<InitListExpr>(Init)) {
3949 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003950 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003951 }
3952
Chandler Carruthd44c3102010-12-06 09:23:57 +00003953 // Initialize the member.
3954 InitializedEntity MemberEntity =
Craig Topperc3ec1492014-05-26 06:22:03 +00003955 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3956 : InitializedEntity::InitializeMember(IndirectMember,
3957 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003958 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003959 InitList ? InitializationKind::CreateDirectList(IdLoc)
3960 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3961 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00003962
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003963 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003964 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3965 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003966 if (MemberInit.isInvalid())
3967 return true;
3968
Richard Smith736a9472013-06-12 20:42:33 +00003969 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3970
Richard Smith945f8d32013-01-14 22:39:08 +00003971 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00003972 // The initialization of each base and member constitutes a
3973 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003974 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003975 if (MemberInit.isInvalid())
3976 return true;
3977
Richard Smithd59b8322012-12-19 01:39:02 +00003978 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003979 }
3980
Chandler Carruthd44c3102010-12-06 09:23:57 +00003981 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00003982 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3983 InitRange.getBegin(), Init,
3984 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003985 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00003986 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3987 InitRange.getBegin(), Init,
3988 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003989 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00003990}
3991
John McCallfaf5fb42010-08-26 23:41:50 +00003992MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003993Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00003994 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003995 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003996 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003997 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003998 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003999 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00004000
Sebastian Redl0501c632012-02-12 16:37:36 +00004001 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004002 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00004003 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4004 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004005 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00004006 }
4007
Sebastian Redla9351792012-02-11 23:51:47 +00004008 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00004009 // Initialize the object.
4010 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4011 QualType(ClassDecl->getTypeForDecl(), 0));
4012 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00004013 InitList ? InitializationKind::CreateDirectList(NameLoc)
4014 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4015 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004016 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00004017 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Craig Topperc3ec1492014-05-26 06:22:03 +00004018 Args, nullptr);
Alexis Huntc5575cc2011-02-26 19:13:13 +00004019 if (DelegationInit.isInvalid())
4020 return true;
4021
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00004022 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4023 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00004024
Richard Smith945f8d32013-01-14 22:39:08 +00004025 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00004026 // The initialization of each base and member constitutes a
4027 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00004028 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
4029 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00004030 if (DelegationInit.isInvalid())
4031 return true;
4032
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00004033 // If we are in a dependent context, template instantiation will
4034 // perform this type-checking again. Just save the arguments that we
4035 // received in a ParenListExpr.
4036 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4037 // of the information that we have about the base
4038 // initializer. However, deconstructing the ASTs is a dicey process,
4039 // and this approach is far more likely to get the corner cases right.
4040 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004041 DelegationInit = Init;
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00004042
Erich Keanebb863642017-09-20 22:28:24 +00004043 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004044 DelegationInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00004045 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00004046}
4047
4048MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00004049Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00004050 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00004051 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00004052 SourceLocation BaseLoc
4053 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00004054
Douglas Gregor1c69bf02010-06-16 16:03:14 +00004055 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4056 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4057 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4058
4059 // C++ [class.base.init]p2:
4060 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00004061 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00004062 // of that class, the mem-initializer is ill-formed. A
4063 // mem-initializer-list can initialize a base class using any
4064 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00004065 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00004066
Sebastian Redla9351792012-02-11 23:51:47 +00004067 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00004068 if (EllipsisLoc.isValid()) {
4069 // This is a pack expansion.
4070 if (!BaseType->containsUnexpandedParameterPack()) {
4071 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00004072 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00004073
Douglas Gregor44e7df62011-01-04 00:32:56 +00004074 EllipsisLoc = SourceLocation();
4075 }
4076 } else {
4077 // Check for any unexpanded parameter packs.
4078 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4079 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00004080
Sebastian Redla9351792012-02-11 23:51:47 +00004081 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00004082 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00004083 }
Sebastian Redla74948d2011-09-24 17:48:25 +00004084
Douglas Gregor1c69bf02010-06-16 16:03:14 +00004085 // Check for direct and virtual base classes.
Craig Topperc3ec1492014-05-26 06:22:03 +00004086 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4087 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
Erich Keanebb863642017-09-20 22:28:24 +00004088 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00004089 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4090 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00004091 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00004092
Erich Keanebb863642017-09-20 22:28:24 +00004093 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
Douglas Gregor1c69bf02010-06-16 16:03:14 +00004094 VirtualBaseSpec);
4095
4096 // C++ [base.class.init]p2:
4097 // Unless the mem-initializer-id names a nonstatic data member of the
4098 // constructor's class or a direct or virtual base of that class, the
4099 // mem-initializer is ill-formed.
4100 if (!DirectBaseSpec && !VirtualBaseSpec) {
4101 // If the class has any dependent bases, then it's possible that
4102 // one of those types will resolve to the same type as
4103 // BaseType. Therefore, just treat this as a dependent base
4104 // class initialization. FIXME: Should we try to check the
4105 // initialization anyway? It seems odd.
4106 if (ClassDecl->hasAnyDependentBases())
4107 Dependent = true;
4108 else
4109 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4110 << BaseType << Context.getTypeDeclType(ClassDecl)
4111 << BaseTInfo->getTypeLoc().getLocalSourceRange();
4112 }
4113 }
4114
4115 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00004116 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00004117
Sebastian Redla74948d2011-09-24 17:48:25 +00004118 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4119 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00004120 InitRange.getBegin(), Init,
4121 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00004122 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004123
4124 // C++ [base.class.init]p2:
4125 // If a mem-initializer-id is ambiguous because it designates both
4126 // a direct non-virtual base class and an inherited virtual base
4127 // class, the mem-initializer is ill-formed.
4128 if (DirectBaseSpec && VirtualBaseSpec)
4129 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00004130 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004131
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004132 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004133 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004134 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004135
4136 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00004137 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004138 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00004139 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00004140 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004141 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00004142 }
Sebastian Redl0501c632012-02-12 16:37:36 +00004143
4144 InitializedEntity BaseEntity =
4145 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4146 InitializationKind Kind =
4147 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4148 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4149 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004150 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00004151 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004152 if (BaseInit.isInvalid())
4153 return true;
John McCallacf0ee52010-10-08 02:01:28 +00004154
Richard Smith945f8d32013-01-14 22:39:08 +00004155 // C++11 [class.base.init]p7:
4156 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004157 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00004158 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004159 if (BaseInit.isInvalid())
4160 return true;
4161
4162 // If we are in a dependent context, template instantiation will
4163 // perform this type-checking again. Just save the arguments that we
4164 // received in a ParenListExpr.
4165 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4166 // of the information that we have about the base
4167 // initializer. However, deconstructing the ASTs is a dicey process,
4168 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00004169 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004170 BaseInit = Init;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004171
Alexis Hunt1d792652011-01-08 20:30:50 +00004172 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00004173 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00004174 InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004175 BaseInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00004176 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00004177}
4178
Sebastian Redl22653ba2011-08-30 19:58:05 +00004179// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00004180static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4181 if (T.isNull()) T = E->getType();
4182 QualType TargetType = SemaRef.BuildReferenceType(
4183 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004184 SourceLocation ExprLoc = E->getLocStart();
4185 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4186 TargetType, ExprLoc);
4187
4188 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4189 SourceRange(ExprLoc, ExprLoc),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004190 E->getSourceRange()).get();
Sebastian Redl22653ba2011-08-30 19:58:05 +00004191}
4192
Anders Carlsson1b00e242010-04-23 03:10:23 +00004193/// ImplicitInitializerKind - How an implicit base or member initializer should
4194/// initialize its base or member.
4195enum ImplicitInitializerKind {
4196 IIK_Default,
4197 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00004198 IIK_Move,
4199 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00004200};
4201
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004202static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00004203BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00004204 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00004205 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004206 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00004207 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004208 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00004209 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4210 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004211
John McCalldadc5752010-08-24 06:29:42 +00004212 ExprResult BaseInit;
Erich Keanebb863642017-09-20 22:28:24 +00004213
Anders Carlsson1b00e242010-04-23 03:10:23 +00004214 switch (ImplicitInitKind) {
Richard Smith5179eb72016-06-28 19:03:57 +00004215 case IIK_Inherit:
Anders Carlsson1b00e242010-04-23 03:10:23 +00004216 case IIK_Default: {
4217 InitializationKind InitKind
4218 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00004219 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4220 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00004221 break;
4222 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004223
Sebastian Redl22653ba2011-08-30 19:58:05 +00004224 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00004225 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004226 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00004227 ParmVarDecl *Param = Constructor->getParamDecl(0);
4228 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00004229
Erich Keanebb863642017-09-20 22:28:24 +00004230 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00004231 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00004232 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00004233 Constructor->getLocation(), ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00004234 VK_LValue, nullptr);
Sebastian Redl22653ba2011-08-30 19:58:05 +00004235
Eli Friedmanfa0df832012-02-02 03:46:19 +00004236 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4237
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00004238 // Cast to the base class to avoid ambiguities.
Erich Keanebb863642017-09-20 22:28:24 +00004239 QualType ArgTy =
4240 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
Anders Carlsson79111502010-05-01 16:39:01 +00004241 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00004242
Sebastian Redl22653ba2011-08-30 19:58:05 +00004243 if (Moving) {
4244 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4245 }
4246
John McCallcf142162010-08-07 06:22:56 +00004247 CXXCastPath BasePath;
4248 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00004249 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4250 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00004251 Moving ? VK_XValue : VK_LValue,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004252 &BasePath).get();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00004253
Anders Carlsson1b00e242010-04-23 03:10:23 +00004254 InitializationKind InitKind
4255 = InitializationKind::CreateDirect(Constructor->getLocation(),
4256 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004257 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4258 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00004259 break;
4260 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00004261 }
John McCallb268a282010-08-23 23:25:46 +00004262
Douglas Gregora40433a2010-12-07 00:41:46 +00004263 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004264 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004265 return true;
Erich Keanebb863642017-09-20 22:28:24 +00004266
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004267 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00004268 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Erich Keanebb863642017-09-20 22:28:24 +00004269 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004270 SourceLocation()),
4271 BaseSpec->isVirtual(),
4272 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004273 BaseInit.getAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004274 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004275 SourceLocation());
4276
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004277 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004278}
4279
Sebastian Redl22653ba2011-08-30 19:58:05 +00004280static bool RefersToRValueRef(Expr *MemRef) {
4281 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4282 return Referenced->getType()->isRValueReferenceType();
4283}
4284
Anders Carlsson3c1db572010-04-23 02:15:47 +00004285static bool
4286BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00004287 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00004288 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00004289 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004290 if (Field->isInvalidDecl())
4291 return true;
4292
Chandler Carruth9c9286b2010-06-29 23:50:44 +00004293 SourceLocation Loc = Constructor->getLocation();
4294
Sebastian Redl22653ba2011-08-30 19:58:05 +00004295 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4296 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00004297 ParmVarDecl *Param = Constructor->getParamDecl(0);
4298 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00004299
4300 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00004301 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
4302 return false;
Erich Keanebb863642017-09-20 22:28:24 +00004303
4304 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00004305 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00004306 SourceLocation(), Param, false,
Craig Topperc3ec1492014-05-26 06:22:03 +00004307 Loc, ParamType, VK_LValue, nullptr);
Douglas Gregor94f9a482010-05-05 05:51:00 +00004308
Eli Friedmanfa0df832012-02-02 03:46:19 +00004309 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4310
Sebastian Redl22653ba2011-08-30 19:58:05 +00004311 if (Moving) {
4312 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4313 }
4314
Douglas Gregor94f9a482010-05-05 05:51:00 +00004315 // Build a reference to this field within the parameter.
4316 CXXScopeSpec SS;
4317 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4318 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00004319 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4320 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00004321 MemberLookup.resolveKind();
Erich Keanebb863642017-09-20 22:28:24 +00004322 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00004323 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00004324 ParamType, Loc,
4325 /*IsArrow=*/false,
4326 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004327 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00004328 /*FirstQualifierInScope=*/nullptr,
Douglas Gregor94f9a482010-05-05 05:51:00 +00004329 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00004330 /*TemplateArgs=*/nullptr,
4331 /*S*/nullptr);
Sebastian Redle9c4e842011-09-04 18:14:28 +00004332 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00004333 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004334
4335 // C++11 [class.copy]p15:
4336 // - if a member m has rvalue reference type T&&, it is direct-initialized
4337 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00004338 if (RefersToRValueRef(CtorArg.get())) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004339 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004340 }
4341
Richard Smith30e304e2016-12-14 00:03:17 +00004342 InitializedEntity Entity =
4343 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4344 /*Implicit*/ true)
4345 : InitializedEntity::InitializeMember(Field, nullptr,
4346 /*Implicit*/ true);
Sebastian Redle9c4e842011-09-04 18:14:28 +00004347
Douglas Gregor94f9a482010-05-05 05:51:00 +00004348 // Direct-initialize to use the copy constructor.
4349 InitializationKind InitKind =
4350 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
Erich Keanebb863642017-09-20 22:28:24 +00004351
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004352 Expr *CtorArgE = CtorArg.getAs<Expr>();
Richard Smith30e304e2016-12-14 00:03:17 +00004353 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4354 ExprResult MemberInit =
4355 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00004356 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00004357 if (MemberInit.isInvalid())
4358 return true;
4359
Richard Smith30e304e2016-12-14 00:03:17 +00004360 if (Indirect)
4361 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4362 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4363 else
4364 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4365 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
Anders Carlsson1b00e242010-04-23 03:10:23 +00004366 return false;
4367 }
4368
Richard Smithc2bc61b2013-03-18 21:12:30 +00004369 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4370 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00004371
Erich Keanebb863642017-09-20 22:28:24 +00004372 QualType FieldBaseElementType =
Anders Carlsson3c1db572010-04-23 02:15:47 +00004373 SemaRef.Context.getBaseElementType(Field->getType());
Erich Keanebb863642017-09-20 22:28:24 +00004374
Anders Carlsson3c1db572010-04-23 02:15:47 +00004375 if (FieldBaseElementType->isRecordType()) {
Richard Smith30e304e2016-12-14 00:03:17 +00004376 InitializedEntity InitEntity =
4377 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4378 /*Implicit*/ true)
4379 : InitializedEntity::InitializeMember(Field, nullptr,
4380 /*Implicit*/ true);
Erich Keanebb863642017-09-20 22:28:24 +00004381 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00004382 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00004383
4384 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4385 ExprResult MemberInit =
4386 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00004387
Douglas Gregora40433a2010-12-07 00:41:46 +00004388 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00004389 if (MemberInit.isInvalid())
4390 return true;
Erich Keanebb863642017-09-20 22:28:24 +00004391
Douglas Gregor493627b2011-08-10 15:22:55 +00004392 if (Indirect)
4393 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Erich Keanebb863642017-09-20 22:28:24 +00004394 Indirect, Loc,
Douglas Gregor493627b2011-08-10 15:22:55 +00004395 Loc,
4396 MemberInit.get(),
4397 Loc);
4398 else
4399 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4400 Field, Loc, Loc,
4401 MemberInit.get(),
4402 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00004403 return false;
4404 }
Anders Carlssondca6be02010-04-23 03:07:47 +00004405
Alexis Hunt8b455182011-05-17 00:19:05 +00004406 if (!Field->getParent()->isUnion()) {
4407 if (FieldBaseElementType->isReferenceType()) {
Erich Keanebb863642017-09-20 22:28:24 +00004408 SemaRef.Diag(Constructor->getLocation(),
Alexis Hunt8b455182011-05-17 00:19:05 +00004409 diag::err_uninitialized_member_in_ctor)
Erich Keanebb863642017-09-20 22:28:24 +00004410 << (int)Constructor->isImplicit()
Alexis Hunt8b455182011-05-17 00:19:05 +00004411 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4412 << 0 << Field->getDeclName();
4413 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4414 return true;
4415 }
Anders Carlssondca6be02010-04-23 03:07:47 +00004416
Alexis Hunt8b455182011-05-17 00:19:05 +00004417 if (FieldBaseElementType.isConstQualified()) {
Erich Keanebb863642017-09-20 22:28:24 +00004418 SemaRef.Diag(Constructor->getLocation(),
Alexis Hunt8b455182011-05-17 00:19:05 +00004419 diag::err_uninitialized_member_in_ctor)
Erich Keanebb863642017-09-20 22:28:24 +00004420 << (int)Constructor->isImplicit()
Alexis Hunt8b455182011-05-17 00:19:05 +00004421 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4422 << 1 << Field->getDeclName();
4423 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4424 return true;
4425 }
Anders Carlssondca6be02010-04-23 03:07:47 +00004426 }
Erich Keanebb863642017-09-20 22:28:24 +00004427
Brian Kelley036603a2017-03-29 17:31:42 +00004428 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4429 // ARC and Weak:
John McCall31168b02011-06-15 23:02:42 +00004430 // Default-initialize Objective-C pointers to NULL.
4431 CXXMemberInit
Erich Keanebb863642017-09-20 22:28:24 +00004432 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4433 Loc, Loc,
4434 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
John McCall31168b02011-06-15 23:02:42 +00004435 Loc);
4436 return false;
4437 }
Erich Keanebb863642017-09-20 22:28:24 +00004438
Anders Carlsson3c1db572010-04-23 02:15:47 +00004439 // Nothing to initialize.
Craig Topperc3ec1492014-05-26 06:22:03 +00004440 CXXMemberInit = nullptr;
Anders Carlsson3c1db572010-04-23 02:15:47 +00004441 return false;
4442}
John McCallbc83b3f2010-05-20 23:23:51 +00004443
4444namespace {
4445struct BaseAndFieldInfo {
4446 Sema &S;
4447 CXXConstructorDecl *Ctor;
4448 bool AnyErrorsInInits;
4449 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00004450 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004451 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00004452 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00004453
4454 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4455 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004456 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
Richard Smith5179eb72016-06-28 19:03:57 +00004457 if (Ctor->getInheritedConstructor())
4458 IIK = IIK_Inherit;
4459 else if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00004460 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004461 else if (Generated && Ctor->isMoveConstructor())
4462 IIK = IIK_Move;
John McCallbc83b3f2010-05-20 23:23:51 +00004463 else
4464 IIK = IIK_Default;
4465 }
Erich Keanebb863642017-09-20 22:28:24 +00004466
Douglas Gregor7db3e952011-11-28 20:03:15 +00004467 bool isImplicitCopyOrMove() const {
4468 switch (IIK) {
4469 case IIK_Copy:
4470 case IIK_Move:
4471 return true;
Erich Keanebb863642017-09-20 22:28:24 +00004472
Douglas Gregor7db3e952011-11-28 20:03:15 +00004473 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00004474 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00004475 return false;
4476 }
David Blaikiee4d798f2012-01-20 21:50:17 +00004477
4478 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00004479 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00004480
4481 bool addFieldInitializer(CXXCtorInitializer *Init) {
4482 AllToInit.push_back(Init);
4483
4484 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00004485 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00004486 S.UnusedPrivateFields.remove(Init->getAnyMember());
4487
4488 return false;
4489 }
John McCallbc83b3f2010-05-20 23:23:51 +00004490
Richard Smithab44d5b2013-12-10 08:25:00 +00004491 bool isInactiveUnionMember(FieldDecl *Field) {
4492 RecordDecl *Record = Field->getParent();
4493 if (!Record->isUnion())
4494 return false;
4495
Richard Smith8d183852013-12-10 20:56:03 +00004496 if (FieldDecl *Active =
4497 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00004498 return Active != Field->getCanonicalDecl();
4499
4500 // In an implicit copy or move constructor, ignore any in-class initializer.
4501 if (isImplicitCopyOrMove())
4502 return true;
4503
4504 // If there's no explicit initialization, the field is active only if it
4505 // has an in-class initializer...
4506 if (Field->hasInClassInitializer())
4507 return false;
4508 // ... or it's an anonymous struct or union whose class has an in-class
4509 // initializer.
4510 if (!Field->isAnonymousStructOrUnion())
4511 return true;
4512 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4513 return !FieldRD->hasInClassInitializer();
4514 }
4515
4516 /// \brief Determine whether the given field is, or is within, a union member
4517 /// that is inactive (because there was an initializer given for a different
4518 /// member of the union, or because the union was not initialized at all).
4519 bool isWithinInactiveUnionMember(FieldDecl *Field,
4520 IndirectFieldDecl *Indirect) {
4521 if (!Indirect)
4522 return isInactiveUnionMember(Field);
4523
Aaron Ballman29c94602014-03-07 18:36:15 +00004524 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004525 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00004526 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00004527 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00004528 }
4529 return false;
4530 }
4531};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004532}
Richard Smithc94ec842011-09-19 13:34:43 +00004533
Douglas Gregor10f939c2011-11-02 23:04:16 +00004534/// \brief Determine whether the given type is an incomplete or zero-lenfgth
4535/// array type.
4536static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4537 if (T->isIncompleteArrayType())
4538 return true;
Erich Keanebb863642017-09-20 22:28:24 +00004539
Douglas Gregor10f939c2011-11-02 23:04:16 +00004540 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4541 if (!ArrayT->getSize())
4542 return true;
Erich Keanebb863642017-09-20 22:28:24 +00004543
Douglas Gregor10f939c2011-11-02 23:04:16 +00004544 T = ArrayT->getElementType();
4545 }
Erich Keanebb863642017-09-20 22:28:24 +00004546
Douglas Gregor10f939c2011-11-02 23:04:16 +00004547 return false;
4548}
4549
Richard Smith938f40b2011-06-11 17:19:42 +00004550static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Erich Keanebb863642017-09-20 22:28:24 +00004551 FieldDecl *Field,
Craig Topperc3ec1492014-05-26 06:22:03 +00004552 IndirectFieldDecl *Indirect = nullptr) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00004553 if (Field->isInvalidDecl())
4554 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00004555
Chandler Carruth139e9622010-06-30 02:59:29 +00004556 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smithcd45dbc2014-04-19 03:48:30 +00004557 if (CXXCtorInitializer *Init =
4558 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
Richard Smith0a8cfc72012-08-07 21:30:42 +00004559 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00004560
Richard Smithab44d5b2013-12-10 08:25:00 +00004561 // C++11 [class.base.init]p8:
4562 // if the entity is a non-static data member that has a
4563 // brace-or-equal-initializer and either
4564 // -- the constructor's class is a union and no other variant member of that
4565 // union is designated by a mem-initializer-id or
4566 // -- the constructor's class is not a union, and, if the entity is a member
4567 // of an anonymous union, no other member of that union is designated by
4568 // a mem-initializer-id,
4569 // the entity is initialized as specified in [dcl.init].
4570 //
4571 // We also apply the same rules to handle anonymous structs within anonymous
4572 // unions.
4573 if (Info.isWithinInactiveUnionMember(Field, Indirect))
4574 return false;
4575
Douglas Gregor7db3e952011-11-28 20:03:15 +00004576 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Reid Klecknerd60b82f2014-11-17 23:36:45 +00004577 ExprResult DIE =
4578 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4579 if (DIE.isInvalid())
4580 return true;
Douglas Gregor493627b2011-08-10 15:22:55 +00004581 CXXCtorInitializer *Init;
4582 if (Indirect)
Reid Klecknerd60b82f2014-11-17 23:36:45 +00004583 Init = new (SemaRef.Context)
4584 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4585 SourceLocation(), DIE.get(), SourceLocation());
Douglas Gregor493627b2011-08-10 15:22:55 +00004586 else
Reid Klecknerd60b82f2014-11-17 23:36:45 +00004587 Init = new (SemaRef.Context)
4588 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4589 SourceLocation(), DIE.get(), SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00004590 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00004591 }
4592
Douglas Gregor10f939c2011-11-02 23:04:16 +00004593 // Don't initialize incomplete or zero-length arrays.
4594 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4595 return false;
4596
John McCallbc83b3f2010-05-20 23:23:51 +00004597 // Don't try to build an implicit initializer if there were semantic
4598 // errors in any of the initializers (and therefore we might be
4599 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00004600 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00004601 return false;
4602
Craig Topperc3ec1492014-05-26 06:22:03 +00004603 CXXCtorInitializer *Init = nullptr;
Douglas Gregor493627b2011-08-10 15:22:55 +00004604 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4605 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00004606 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00004607
Richard Smith0a8cfc72012-08-07 21:30:42 +00004608 if (!Init)
4609 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00004610
Richard Smith0a8cfc72012-08-07 21:30:42 +00004611 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00004612}
Alexis Hunt61bc1732011-05-01 07:04:31 +00004613
4614bool
4615Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4616 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00004617 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00004618 Constructor->setNumCtorInitializers(1);
4619 CXXCtorInitializer **initializer =
4620 new (Context) CXXCtorInitializer*[1];
4621 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4622 Constructor->setCtorInitializers(initializer);
4623
Alexis Hunt9d47faf2011-05-03 23:05:34 +00004624 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00004625 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00004626 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4627 }
4628
Alexis Hunte2622992011-05-05 00:05:47 +00004629 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00004630
Richard Trieu8a0c9e62014-09-12 22:47:58 +00004631 DiagnoseUninitializedFields(*this, Constructor);
4632
Alexis Hunt61bc1732011-05-01 07:04:31 +00004633 return false;
4634}
Douglas Gregor493627b2011-08-10 15:22:55 +00004635
David Blaikie3fc2f912013-01-17 05:26:25 +00004636bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4637 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00004638 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004639 // Just store the initializers as written, they will be checked during
4640 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00004641 if (!Initializers.empty()) {
4642 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00004643 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00004644 new (Context) CXXCtorInitializer*[Initializers.size()];
4645 memcpy(baseOrMemberInitializers, Initializers.data(),
4646 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00004647 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00004648 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00004649
4650 // Let template instantiation know whether we had errors.
4651 if (AnyErrors)
4652 Constructor->setInvalidDecl();
4653
Anders Carlssondb0a9652010-04-02 06:26:44 +00004654 return false;
4655 }
4656
John McCallbc83b3f2010-05-20 23:23:51 +00004657 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00004658
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004659 // We need to build the initializer AST according to order of construction
4660 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004661 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00004662 if (!ClassDecl)
4663 return true;
Erich Keanebb863642017-09-20 22:28:24 +00004664
Eli Friedman9cf6b592009-11-09 19:20:36 +00004665 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00004666
David Blaikie3fc2f912013-01-17 05:26:25 +00004667 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004668 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00004669
Anders Carlssondb0a9652010-04-02 06:26:44 +00004670 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00004671 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00004672 else {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004673 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00004674
4675 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00004676 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004677 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00004678 if (FD && FD->getParent()->isUnion())
4679 Info.ActiveUnionMember.insert(std::make_pair(
4680 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4681 }
4682 } else if (FieldDecl *FD = Member->getMember()) {
4683 if (FD->getParent()->isUnion())
4684 Info.ActiveUnionMember.insert(std::make_pair(
4685 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4686 }
4687 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00004688 }
4689
Anders Carlsson43c64af2010-04-21 19:52:01 +00004690 // Keep track of the direct virtual bases.
4691 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00004692 for (auto &I : ClassDecl->bases()) {
4693 if (I.isVirtual())
4694 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00004695 }
4696
Anders Carlssondb0a9652010-04-02 06:26:44 +00004697 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00004698 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004699 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00004700 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00004701 // [class.base.init]p7, per DR257:
4702 // A mem-initializer where the mem-initializer-id names a virtual base
4703 // class is ignored during execution of a constructor of any class that
4704 // is not the most derived class.
4705 if (ClassDecl->isAbstract()) {
4706 // FIXME: Provide a fixit to remove the base specifier. This requires
4707 // tracking the location of the associated comma for a base specifier.
4708 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00004709 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00004710 DiagnoseAbstractType(ClassDecl);
4711 }
4712
John McCallbc83b3f2010-05-20 23:23:51 +00004713 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00004714 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4715 // [class.base.init]p8, per DR257:
4716 // If a given [...] base class is not named by a mem-initializer-id
4717 // [...] and the entity is not a virtual base class of an abstract
4718 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00004719 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00004720 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00004721 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00004722 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00004723 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004724 HadError = true;
4725 continue;
4726 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004727
John McCallbc83b3f2010-05-20 23:23:51 +00004728 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004729 }
4730 }
Mike Stump11289f42009-09-09 15:08:12 +00004731
John McCallbc83b3f2010-05-20 23:23:51 +00004732 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004733 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004734 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00004735 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00004736 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004737
Alexis Hunt1d792652011-01-08 20:30:50 +00004738 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00004739 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00004740 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00004741 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004742 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00004743 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00004744 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004745 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004746 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004747 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00004748 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00004749
John McCallbc83b3f2010-05-20 23:23:51 +00004750 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004751 }
4752 }
Mike Stump11289f42009-09-09 15:08:12 +00004753
John McCallbc83b3f2010-05-20 23:23:51 +00004754 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00004755 for (auto *Mem : ClassDecl->decls()) {
4756 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004757 // C++ [class.bit]p2:
4758 // A declaration for a bit-field that omits the identifier declares an
4759 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
4760 // initialized.
4761 if (F->isUnnamedBitfield())
4762 continue;
Erich Keanebb863642017-09-20 22:28:24 +00004763
Sebastian Redl22653ba2011-08-30 19:58:05 +00004764 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00004765 // handle anonymous struct/union fields based on their individual
4766 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00004767 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00004768 continue;
Erich Keanebb863642017-09-20 22:28:24 +00004769
Douglas Gregor493627b2011-08-10 15:22:55 +00004770 if (CollectFieldInitializer(*this, Info, F))
4771 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004772 continue;
4773 }
Erich Keanebb863642017-09-20 22:28:24 +00004774
Douglas Gregor493627b2011-08-10 15:22:55 +00004775 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00004776 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00004777 continue;
Erich Keanebb863642017-09-20 22:28:24 +00004778
Aaron Ballman629afae2014-03-07 19:56:05 +00004779 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00004780 if (F->getType()->isIncompleteArrayType()) {
4781 assert(ClassDecl->hasFlexibleArrayMember() &&
4782 "Incomplete array type is not valid");
4783 continue;
4784 }
Erich Keanebb863642017-09-20 22:28:24 +00004785
Douglas Gregor493627b2011-08-10 15:22:55 +00004786 // Initialize each field of an anonymous struct individually.
4787 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4788 HadError = true;
Erich Keanebb863642017-09-20 22:28:24 +00004789
4790 continue;
Douglas Gregor493627b2011-08-10 15:22:55 +00004791 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004792 }
Mike Stump11289f42009-09-09 15:08:12 +00004793
David Blaikie3fc2f912013-01-17 05:26:25 +00004794 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004795 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004796 Constructor->setNumCtorInitializers(NumInitializers);
4797 CXXCtorInitializer **baseOrMemberInitializers =
4798 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00004799 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00004800 NumInitializers * sizeof(CXXCtorInitializer*));
4801 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00004802
John McCalla6309952010-03-16 21:39:52 +00004803 // Constructors implicitly reference the base and member
4804 // destructors.
4805 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4806 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004807 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00004808
4809 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004810}
4811
David Blaikieb61b8152013-01-17 08:49:22 +00004812static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004813 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00004814 const RecordDecl *RD = RT->getDecl();
4815 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004816 for (auto *Field : RD->fields())
4817 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00004818 return;
4819 }
Eli Friedman952c15d2009-07-21 19:28:10 +00004820 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00004821 IdealInits.push_back(Field->getCanonicalDecl());
Eli Friedman952c15d2009-07-21 19:28:10 +00004822}
4823
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004824static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4825 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00004826}
4827
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004828static const void *GetKeyForMember(ASTContext &Context,
4829 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00004830 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004831 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Erich Keanebb863642017-09-20 22:28:24 +00004832
Richard Smithcd45dbc2014-04-19 03:48:30 +00004833 return Member->getAnyMember()->getCanonicalDecl();
Eli Friedman952c15d2009-07-21 19:28:10 +00004834}
4835
David Blaikie3fc2f912013-01-17 05:26:25 +00004836static void DiagnoseBaseOrMemInitializerOrder(
4837 Sema &SemaRef, const CXXConstructorDecl *Constructor,
4838 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00004839 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00004840 return;
Mike Stump11289f42009-09-09 15:08:12 +00004841
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004842 // Don't check initializers order unless the warning is enabled at the
Erich Keanebb863642017-09-20 22:28:24 +00004843 // location of at least one initializer.
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004844 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004845 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004846 CXXCtorInitializer *Init = Inits[InitIndex];
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004847 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4848 Init->getSourceLocation())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004849 ShouldCheckOrder = true;
4850 break;
4851 }
4852 }
4853 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00004854 return;
Erich Keanebb863642017-09-20 22:28:24 +00004855
John McCallbb7b6582010-04-10 07:37:23 +00004856 // Build the list of bases and members in the order that they'll
4857 // actually be initialized. The explicit initializers should be in
4858 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004859 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00004860
Anders Carlsson96b8fc62010-04-02 03:38:04 +00004861 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4862
John McCallbb7b6582010-04-10 07:37:23 +00004863 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004864 for (const auto &VBase : ClassDecl->vbases())
4865 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00004866
John McCallbb7b6582010-04-10 07:37:23 +00004867 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004868 for (const auto &Base : ClassDecl->bases()) {
4869 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00004870 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00004871 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00004872 }
Mike Stump11289f42009-09-09 15:08:12 +00004873
John McCallbb7b6582010-04-10 07:37:23 +00004874 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004875 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004876 if (Field->isUnnamedBitfield())
4877 continue;
Erich Keanebb863642017-09-20 22:28:24 +00004878
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004879 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00004880 }
Erich Keanebb863642017-09-20 22:28:24 +00004881
John McCallbb7b6582010-04-10 07:37:23 +00004882 unsigned NumIdealInits = IdealInitKeys.size();
4883 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00004884
Craig Topperc3ec1492014-05-26 06:22:03 +00004885 CXXCtorInitializer *PrevInit = nullptr;
David Blaikie3fc2f912013-01-17 05:26:25 +00004886 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004887 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004888 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00004889
4890 // Scan forward to try to find this initializer in the idealized
4891 // initializers list.
4892 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4893 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004894 break;
John McCallbb7b6582010-04-10 07:37:23 +00004895
4896 // If we didn't find this initializer, it must be because we
4897 // scanned past it on a previous iteration. That can only
4898 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00004899 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00004900 Sema::SemaDiagnosticBuilder D =
4901 SemaRef.Diag(PrevInit->getSourceLocation(),
4902 diag::warn_initializer_out_of_order);
4903
Francois Pichetd583da02010-12-04 09:14:42 +00004904 if (PrevInit->isAnyMemberInitializer())
4905 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004906 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004907 D << 1 << PrevInit->getTypeSourceInfo()->getType();
Erich Keanebb863642017-09-20 22:28:24 +00004908
Francois Pichetd583da02010-12-04 09:14:42 +00004909 if (Init->isAnyMemberInitializer())
4910 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004911 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004912 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004913
4914 // Move back to the initializer's location in the ideal list.
4915 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4916 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004917 break;
John McCallbb7b6582010-04-10 07:37:23 +00004918
Aaron Ballmanddd2ece2015-07-20 13:36:07 +00004919 assert(IdealIndex < NumIdealInits &&
John McCallbb7b6582010-04-10 07:37:23 +00004920 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004921 }
John McCallbb7b6582010-04-10 07:37:23 +00004922
4923 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004924 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00004925}
4926
John McCall23eebd92010-04-10 09:28:51 +00004927namespace {
4928bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004929 CXXCtorInitializer *Init,
4930 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00004931 if (!PrevInit) {
4932 PrevInit = Init;
4933 return false;
4934 }
4935
Douglas Gregorea306a12013-03-25 23:28:23 +00004936 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00004937 S.Diag(Init->getSourceLocation(),
4938 diag::err_multiple_mem_initialization)
4939 << Field->getDeclName()
4940 << Init->getSourceRange();
4941 else {
John McCall424cec92011-01-19 06:33:43 +00004942 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00004943 assert(BaseClass && "neither field nor base");
4944 S.Diag(Init->getSourceLocation(),
4945 diag::err_multiple_base_initialization)
4946 << QualType(BaseClass, 0)
4947 << Init->getSourceRange();
4948 }
4949 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4950 << 0 << PrevInit->getSourceRange();
4951
4952 return true;
4953}
4954
Alexis Hunt1d792652011-01-08 20:30:50 +00004955typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00004956typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4957
4958bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004959 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00004960 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00004961 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00004962 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00004963 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00004964
4965 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00004966 if (Parent->isUnion()) {
4967 UnionEntry &En = Unions[Parent];
4968 if (En.first && En.first != Child) {
4969 S.Diag(Init->getSourceLocation(),
4970 diag::err_multiple_mem_union_initialization)
4971 << Field->getDeclName()
4972 << Init->getSourceRange();
4973 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4974 << 0 << En.second->getSourceRange();
4975 return true;
Erich Keanebb863642017-09-20 22:28:24 +00004976 }
David Blaikie256ee192011-11-12 20:54:14 +00004977 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00004978 En.first = Child;
4979 En.second = Init;
4980 }
David Blaikie0f65d592011-11-17 06:01:57 +00004981 if (!Parent->isAnonymousStructOrUnion())
4982 return false;
John McCall23eebd92010-04-10 09:28:51 +00004983 }
4984
4985 Child = Parent;
4986 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00004987 }
John McCall23eebd92010-04-10 09:28:51 +00004988
4989 return false;
4990}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004991}
John McCall23eebd92010-04-10 09:28:51 +00004992
Anders Carlssone857b292010-04-02 03:37:03 +00004993/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00004994void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00004995 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00004996 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00004997 bool AnyErrors) {
4998 if (!ConstructorDecl)
4999 return;
5000
5001 AdjustDeclIfTemplate(ConstructorDecl);
5002
5003 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00005004 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00005005
5006 if (!Constructor) {
5007 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5008 return;
5009 }
Erich Keanebb863642017-09-20 22:28:24 +00005010
John McCall23eebd92010-04-10 09:28:51 +00005011 // Mapping for the duplicate initializers check.
5012 // For member initializers, this is keyed with a FieldDecl*.
5013 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00005014 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00005015
5016 // Mapping for the inconsistent anonymous-union initializers check.
5017 RedundantUnionMap MemberUnions;
5018
Anders Carlsson7b3f2782010-04-02 05:42:15 +00005019 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00005020 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00005021 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00005022
Abramo Bagnara341d7832010-05-26 18:09:23 +00005023 // Set the source order index.
5024 Init->setSourceOrder(i);
5025
Francois Pichetd583da02010-12-04 09:14:42 +00005026 if (Init->isAnyMemberInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00005027 const void *Key = GetKeyForMember(Context, Init);
5028 if (CheckRedundantInit(*this, Init, Members[Key]) ||
John McCall23eebd92010-04-10 09:28:51 +00005029 CheckRedundantUnionInit(*this, Init, MemberUnions))
5030 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00005031 } else if (Init->isBaseInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00005032 const void *Key = GetKeyForMember(Context, Init);
John McCall23eebd92010-04-10 09:28:51 +00005033 if (CheckRedundantInit(*this, Init, Members[Key]))
5034 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00005035 } else {
5036 assert(Init->isDelegatingInitializer());
5037 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00005038 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00005039 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00005040 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00005041 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00005042 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00005043 }
Alexis Hunt6118d662011-05-04 05:57:24 +00005044 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00005045 // Return immediately as the initializer is set.
5046 return;
Anders Carlssone857b292010-04-02 03:37:03 +00005047 }
Anders Carlssone857b292010-04-02 03:37:03 +00005048 }
5049
Anders Carlsson7b3f2782010-04-02 05:42:15 +00005050 if (HadError)
5051 return;
5052
David Blaikie3fc2f912013-01-17 05:26:25 +00005053 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00005054
David Blaikie3fc2f912013-01-17 05:26:25 +00005055 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00005056
Richard Trieuef64e942013-10-25 00:56:00 +00005057 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00005058}
5059
Fariborz Jahanian37d06562009-09-03 23:18:17 +00005060void
John McCalla6309952010-03-16 21:39:52 +00005061Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5062 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00005063 // Ignore dependent contexts. Also ignore unions, since their members never
5064 // have destructors implicitly called.
5065 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00005066 return;
John McCall1064d7e2010-03-16 05:22:47 +00005067
5068 // FIXME: all the access-control diagnostics are positioned on the
5069 // field/base declaration. That's probably good; that said, the
5070 // user might reasonably want to know why the destructor is being
5071 // emitted, and we currently don't say.
Erich Keanebb863642017-09-20 22:28:24 +00005072
Anders Carlssondee9a302009-11-17 04:44:12 +00005073 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005074 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00005075 if (Field->isInvalidDecl())
5076 continue;
Erich Keanebb863642017-09-20 22:28:24 +00005077
Douglas Gregor10f939c2011-11-02 23:04:16 +00005078 // Don't destroy incomplete or zero-length arrays.
5079 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5080 continue;
5081
Anders Carlssondee9a302009-11-17 04:44:12 +00005082 QualType FieldType = Context.getBaseElementType(Field->getType());
Erich Keanebb863642017-09-20 22:28:24 +00005083
Anders Carlssondee9a302009-11-17 04:44:12 +00005084 const RecordType* RT = FieldType->getAs<RecordType>();
5085 if (!RT)
5086 continue;
Erich Keanebb863642017-09-20 22:28:24 +00005087
Anders Carlssondee9a302009-11-17 04:44:12 +00005088 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005089 if (FieldClassDecl->isInvalidDecl())
5090 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00005091 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00005092 continue;
Richard Smith921bd202012-02-26 09:11:52 +00005093 // The destructor for an implicit anonymous union member is never invoked.
5094 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5095 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00005096
Douglas Gregore71edda2010-07-01 22:47:18 +00005097 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005098 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00005099 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00005100 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00005101 << Field->getDeclName()
5102 << FieldType);
5103
Benjamin Kramer8bf44352013-07-24 15:28:33 +00005104 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00005105 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00005106 }
5107
Richard Smithdf054d32017-02-25 23:53:05 +00005108 // We only potentially invoke the destructors of potentially constructed
5109 // subobjects.
5110 bool VisitVirtualBases = !ClassDecl->isAbstract();
5111
John McCall1064d7e2010-03-16 05:22:47 +00005112 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5113
Anders Carlssondee9a302009-11-17 04:44:12 +00005114 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00005115 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00005116 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00005117 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00005118
5119 // Remember direct virtual bases.
Richard Smithdf054d32017-02-25 23:53:05 +00005120 if (Base.isVirtual()) {
5121 if (!VisitVirtualBases)
5122 continue;
John McCall1064d7e2010-03-16 05:22:47 +00005123 DirectVirtualBases.insert(RT);
Richard Smithdf054d32017-02-25 23:53:05 +00005124 }
Anders Carlssondee9a302009-11-17 04:44:12 +00005125
John McCall1064d7e2010-03-16 05:22:47 +00005126 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005127 // If our base class is invalid, we probably can't get its dtor anyway.
5128 if (BaseClassDecl->isInvalidDecl())
5129 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00005130 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00005131 continue;
John McCall1064d7e2010-03-16 05:22:47 +00005132
Douglas Gregore71edda2010-07-01 22:47:18 +00005133 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005134 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00005135
5136 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00005137 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00005138 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00005139 << Base.getType()
5140 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00005141 Context.getTypeDeclType(ClassDecl));
Erich Keanebb863642017-09-20 22:28:24 +00005142
Benjamin Kramer8bf44352013-07-24 15:28:33 +00005143 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00005144 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00005145 }
Richard Smithdf054d32017-02-25 23:53:05 +00005146
5147 if (!VisitVirtualBases)
5148 return;
Erich Keanebb863642017-09-20 22:28:24 +00005149
Anders Carlssondee9a302009-11-17 04:44:12 +00005150 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00005151 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00005152 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00005153 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00005154
5155 // Ignore direct virtual bases.
5156 if (DirectVirtualBases.count(RT))
5157 continue;
5158
John McCall1064d7e2010-03-16 05:22:47 +00005159 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005160 // If our base class is invalid, we probably can't get its dtor anyway.
5161 if (BaseClassDecl->isInvalidDecl())
5162 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00005163 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00005164 continue;
John McCall1064d7e2010-03-16 05:22:47 +00005165
Douglas Gregore71edda2010-07-01 22:47:18 +00005166 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005167 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00005168 if (CheckDestructorAccess(
5169 ClassDecl->getLocation(), Dtor,
5170 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00005171 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00005172 Context.getTypeDeclType(ClassDecl)) ==
5173 AR_accessible) {
5174 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00005175 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00005176 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005177 SourceRange(), DeclarationName(), nullptr);
David Majnemer626032f2013-06-22 06:43:58 +00005178 }
John McCall1064d7e2010-03-16 05:22:47 +00005179
Benjamin Kramer8bf44352013-07-24 15:28:33 +00005180 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00005181 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00005182 }
5183}
5184
John McCall48871652010-08-21 09:40:31 +00005185void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00005186 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00005187 return;
Mike Stump11289f42009-09-09 15:08:12 +00005188
Mike Stump11289f42009-09-09 15:08:12 +00005189 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00005190 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00005191 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00005192 DiagnoseUninitializedFields(*this, Constructor);
5193 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00005194}
5195
Richard Smithdb0ac552015-12-18 22:40:25 +00005196bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005197 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005198 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005199
Richard Smithdb0ac552015-12-18 22:40:25 +00005200 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5201 if (!RD)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005202 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005203
Richard Smithdb0ac552015-12-18 22:40:25 +00005204 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5205 // class template specialization here, but doing so breaks a lot of code.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005206
John McCall02db245d2010-08-18 09:41:07 +00005207 // We can't answer whether something is abstract until it has a
Richard Smithdb0ac552015-12-18 22:40:25 +00005208 // definition. If it's currently being defined, we'll walk back
John McCall02db245d2010-08-18 09:41:07 +00005209 // over all the declarations when we have a full definition.
5210 const CXXRecordDecl *Def = RD->getDefinition();
5211 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00005212 return false;
5213
Richard Smithdb0ac552015-12-18 22:40:25 +00005214 return RD->isAbstract();
5215}
5216
5217bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5218 TypeDiagnoser &Diagnoser) {
5219 if (!isAbstractType(Loc, T))
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005220 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005221
Richard Smithdb0ac552015-12-18 22:40:25 +00005222 T = Context.getBaseElementType(T);
Douglas Gregorae298422012-05-04 17:09:59 +00005223 Diagnoser.diagnose(*this, Loc, T);
Richard Smithdb0ac552015-12-18 22:40:25 +00005224 DiagnoseAbstractType(T->getAsCXXRecordDecl());
John McCall02db245d2010-08-18 09:41:07 +00005225 return true;
5226}
5227
5228void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5229 // Check if we've already emitted the list of pure virtual functions
5230 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005231 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00005232 return;
Mike Stump11289f42009-09-09 15:08:12 +00005233
Richard Smithbc46e432013-07-22 02:56:56 +00005234 // If the diagnostic is suppressed, don't emit the notes. We're only
5235 // going to emit them once, so try to attach them to a diagnostic we're
5236 // actually going to show.
5237 if (Diags.isLastDiagnosticIgnored())
5238 return;
5239
Douglas Gregor4165bd62010-03-23 23:47:56 +00005240 CXXFinalOverriderMap FinalOverriders;
5241 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00005242
Anders Carlssona2f74f32010-06-03 01:00:02 +00005243 // Keep a set of seen pure methods so we won't diagnose the same method
5244 // more than once.
5245 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
Erich Keanebb863642017-09-20 22:28:24 +00005246
5247 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
Douglas Gregor4165bd62010-03-23 23:47:56 +00005248 MEnd = FinalOverriders.end();
Erich Keanebb863642017-09-20 22:28:24 +00005249 M != MEnd;
Douglas Gregor4165bd62010-03-23 23:47:56 +00005250 ++M) {
Erich Keanebb863642017-09-20 22:28:24 +00005251 for (OverridingMethods::iterator SO = M->second.begin(),
Douglas Gregor4165bd62010-03-23 23:47:56 +00005252 SOEnd = M->second.end();
5253 SO != SOEnd; ++SO) {
5254 // C++ [class.abstract]p4:
5255 // A class is abstract if it contains or inherits at least one
5256 // pure virtual function for which the final overrider is pure
5257 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00005258
Erich Keanebb863642017-09-20 22:28:24 +00005259 //
Douglas Gregor4165bd62010-03-23 23:47:56 +00005260 if (SO->second.size() != 1)
5261 continue;
5262
5263 if (!SO->second.front().Method->isPure())
5264 continue;
5265
David Blaikie82e95a32014-11-19 07:49:47 +00005266 if (!SeenPureMethods.insert(SO->second.front().Method).second)
Anders Carlssona2f74f32010-06-03 01:00:02 +00005267 continue;
5268
Erich Keanebb863642017-09-20 22:28:24 +00005269 Diag(SO->second.front().Method->getLocation(),
5270 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00005271 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00005272 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005273 }
5274
5275 if (!PureVirtualClassDiagSet)
5276 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5277 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005278}
5279
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005280namespace {
John McCall02db245d2010-08-18 09:41:07 +00005281struct AbstractUsageInfo {
5282 Sema &S;
5283 CXXRecordDecl *Record;
5284 CanQualType AbstractType;
5285 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00005286
John McCall02db245d2010-08-18 09:41:07 +00005287 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5288 : S(S), Record(Record),
5289 AbstractType(S.Context.getCanonicalType(
5290 S.Context.getTypeDeclType(Record))),
5291 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005292
John McCall02db245d2010-08-18 09:41:07 +00005293 void DiagnoseAbstractType() {
5294 if (Invalid) return;
5295 S.DiagnoseAbstractType(Record);
5296 Invalid = true;
5297 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00005298
John McCall02db245d2010-08-18 09:41:07 +00005299 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5300};
5301
5302struct CheckAbstractUsage {
5303 AbstractUsageInfo &Info;
5304 const NamedDecl *Ctx;
5305
5306 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5307 : Info(Info), Ctx(Ctx) {}
5308
5309 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5310 switch (TL.getTypeLocClass()) {
5311#define ABSTRACT_TYPELOC(CLASS, PARENT)
5312#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00005313 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00005314#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005315 }
John McCall02db245d2010-08-18 09:41:07 +00005316 }
Mike Stump11289f42009-09-09 15:08:12 +00005317
John McCall02db245d2010-08-18 09:41:07 +00005318 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00005319 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005320 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5321 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00005322 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005323
5324 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00005325 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00005326 }
John McCall02db245d2010-08-18 09:41:07 +00005327 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005328
John McCall02db245d2010-08-18 09:41:07 +00005329 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5330 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5331 }
Mike Stump11289f42009-09-09 15:08:12 +00005332
John McCall02db245d2010-08-18 09:41:07 +00005333 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5334 // Visit the type parameters from a permissive context.
5335 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5336 TemplateArgumentLoc TAL = TL.getArgLoc(I);
5337 if (TAL.getArgument().getKind() == TemplateArgument::Type)
5338 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5339 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5340 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005341 }
John McCall02db245d2010-08-18 09:41:07 +00005342 }
Mike Stump11289f42009-09-09 15:08:12 +00005343
John McCall02db245d2010-08-18 09:41:07 +00005344 // Visit pointee types from a permissive context.
5345#define CheckPolymorphic(Type) \
5346 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5347 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5348 }
5349 CheckPolymorphic(PointerTypeLoc)
5350 CheckPolymorphic(ReferenceTypeLoc)
5351 CheckPolymorphic(MemberPointerTypeLoc)
5352 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00005353 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00005354
John McCall02db245d2010-08-18 09:41:07 +00005355 /// Handle all the types we haven't given a more specific
5356 /// implementation for above.
5357 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5358 // Every other kind of type that we haven't called out already
5359 // that has an inner type is either (1) sugar or (2) contains that
5360 // inner type in some way as a subobject.
5361 if (TypeLoc Next = TL.getNextTypeLoc())
5362 return Visit(Next, Sel);
5363
5364 // If there's no inner type and we're in a permissive context,
5365 // don't diagnose.
5366 if (Sel == Sema::AbstractNone) return;
5367
5368 // Check whether the type matches the abstract type.
5369 QualType T = TL.getType();
5370 if (T->isArrayType()) {
5371 Sel = Sema::AbstractArrayType;
5372 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00005373 }
John McCall02db245d2010-08-18 09:41:07 +00005374 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5375 if (CT != Info.AbstractType) return;
5376
5377 // It matched; do some magic.
5378 if (Sel == Sema::AbstractArrayType) {
5379 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5380 << T << TL.getSourceRange();
5381 } else {
5382 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5383 << Sel << T << TL.getSourceRange();
5384 }
5385 Info.DiagnoseAbstractType();
5386 }
5387};
5388
5389void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5390 Sema::AbstractDiagSelID Sel) {
5391 CheckAbstractUsage(*this, D).Visit(TL, Sel);
5392}
5393
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005394}
John McCall02db245d2010-08-18 09:41:07 +00005395
5396/// Check for invalid uses of an abstract type in a method declaration.
5397static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5398 CXXMethodDecl *MD) {
5399 // No need to do the check on definitions, which require that
5400 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00005401 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00005402 return;
5403
5404 // For safety's sake, just ignore it if we don't have type source
5405 // information. This should never happen for non-implicit methods,
5406 // but...
5407 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5408 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5409}
5410
5411/// Check for invalid uses of an abstract type within a class definition.
5412static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5413 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00005414 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00005415 if (D->isImplicit()) continue;
5416
5417 // Methods and method templates.
5418 if (isa<CXXMethodDecl>(D)) {
5419 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5420 } else if (isa<FunctionTemplateDecl>(D)) {
5421 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5422 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5423
5424 // Fields and static variables.
5425 } else if (isa<FieldDecl>(D)) {
5426 FieldDecl *FD = cast<FieldDecl>(D);
5427 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5428 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5429 } else if (isa<VarDecl>(D)) {
5430 VarDecl *VD = cast<VarDecl>(D);
5431 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5432 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5433
5434 // Nested classes and class templates.
5435 } else if (isa<CXXRecordDecl>(D)) {
5436 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5437 } else if (isa<ClassTemplateDecl>(D)) {
5438 CheckAbstractClassUsage(Info,
5439 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5440 }
5441 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005442}
5443
Hans Wennborg99000c22015-08-15 01:18:16 +00005444static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) {
5445 Attr *ClassAttr = getDLLAttr(Class);
5446 if (!ClassAttr)
5447 return;
5448
5449 assert(ClassAttr->getKind() == attr::DLLExport);
5450
5451 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5452
5453 if (TSK == TSK_ExplicitInstantiationDeclaration)
5454 // Don't go any further if this is just an explicit instantiation
5455 // declaration.
5456 return;
5457
5458 for (Decl *Member : Class->decls()) {
5459 auto *MD = dyn_cast<CXXMethodDecl>(Member);
5460 if (!MD)
5461 continue;
5462
5463 if (Member->getAttr<DLLExportAttr>()) {
5464 if (MD->isUserProvided()) {
5465 // Instantiate non-default class member functions ...
5466
5467 // .. except for certain kinds of template specializations.
5468 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5469 continue;
5470
5471 S.MarkFunctionReferenced(Class->getLocation(), MD);
5472
5473 // The function will be passed to the consumer when its definition is
5474 // encountered.
5475 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5476 MD->isCopyAssignmentOperator() ||
5477 MD->isMoveAssignmentOperator()) {
5478 // Synthesize and instantiate non-trivial implicit methods, explicitly
5479 // defaulted methods, and the copy and move assignment operators. The
5480 // latter are exported even if they are trivial, because the address of
Simon Pilgrim2c518802017-03-30 14:13:19 +00005481 // an operator can be taken and should compare equal across libraries.
Hans Wennborg99000c22015-08-15 01:18:16 +00005482 DiagnosticErrorTrap Trap(S.Diags);
5483 S.MarkFunctionReferenced(Class->getLocation(), MD);
5484 if (Trap.hasErrorOccurred()) {
5485 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5486 << Class->getName() << !S.getLangOpts().CPlusPlus11;
5487 break;
5488 }
5489
5490 // There is no later point when we will see the definition of this
5491 // function, so pass it to the consumer now.
5492 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5493 }
5494 }
5495 }
5496}
5497
Reid Kleckner82713bf2017-01-09 17:27:17 +00005498static void checkForMultipleExportedDefaultConstructors(Sema &S,
5499 CXXRecordDecl *Class) {
5500 // Only the MS ABI has default constructor closures, so we don't need to do
5501 // this semantic checking anywhere else.
5502 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5503 return;
5504
Reid Kleckner61195e12017-01-05 01:08:22 +00005505 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5506 for (Decl *Member : Class->decls()) {
5507 // Look for exported default constructors.
5508 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
Reid Kleckner82713bf2017-01-09 17:27:17 +00005509 if (!CD || !CD->isDefaultConstructor())
Reid Kleckner61195e12017-01-05 01:08:22 +00005510 continue;
Reid Kleckner82713bf2017-01-09 17:27:17 +00005511 auto *Attr = CD->getAttr<DLLExportAttr>();
5512 if (!Attr)
5513 continue;
5514
5515 // If the class is non-dependent, mark the default arguments as ODR-used so
5516 // that we can properly codegen the constructor closure.
5517 if (!Class->isDependentContext()) {
5518 for (ParmVarDecl *PD : CD->parameters()) {
5519 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5520 S.DiscardCleanupsInEvaluationContext();
5521 }
5522 }
Reid Kleckner61195e12017-01-05 01:08:22 +00005523
5524 if (LastExportedDefaultCtor) {
5525 S.Diag(LastExportedDefaultCtor->getLocation(),
5526 diag::err_attribute_dll_ambiguous_default_ctor)
5527 << Class;
5528 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5529 << CD->getDeclName();
5530 return;
5531 }
5532 LastExportedDefaultCtor = CD;
5533 }
5534}
5535
Hans Wennborg853ae942014-05-30 16:59:42 +00005536/// \brief Check class-level dllimport/dllexport attribute.
Hans Wennborg17f9b442015-05-27 00:06:45 +00005537void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
Hans Wennborg853ae942014-05-30 16:59:42 +00005538 Attr *ClassAttr = getDLLAttr(Class);
Hans Wennborg205c39b2014-08-23 22:34:43 +00005539
5540 // MSVC inherits DLL attributes to partial class template specializations.
Hans Wennborg17f9b442015-05-27 00:06:45 +00005541 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
Hans Wennborg205c39b2014-08-23 22:34:43 +00005542 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5543 if (Attr *TemplateAttr =
5544 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
Hans Wennborg17f9b442015-05-27 00:06:45 +00005545 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
Hans Wennborg205c39b2014-08-23 22:34:43 +00005546 A->setInherited(true);
5547 ClassAttr = A;
5548 }
5549 }
5550 }
5551
Hans Wennborg853ae942014-05-30 16:59:42 +00005552 if (!ClassAttr)
5553 return;
5554
Hans Wennborg8313c762014-11-03 16:09:16 +00005555 if (!Class->isExternallyVisible()) {
Hans Wennborg17f9b442015-05-27 00:06:45 +00005556 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
Hans Wennborg8313c762014-11-03 16:09:16 +00005557 << Class << ClassAttr;
5558 return;
5559 }
5560
Hans Wennborg17f9b442015-05-27 00:06:45 +00005561 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00005562 !ClassAttr->isInherited()) {
5563 // Diagnose dll attributes on members of class with dll attribute.
5564 for (Decl *Member : Class->decls()) {
5565 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5566 continue;
5567 InheritableAttr *MemberAttr = getDLLAttr(Member);
5568 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5569 continue;
5570
Hans Wennborg17f9b442015-05-27 00:06:45 +00005571 Diag(MemberAttr->getLocation(),
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00005572 diag::err_attribute_dll_member_of_dll_class)
5573 << MemberAttr << ClassAttr;
Hans Wennborg17f9b442015-05-27 00:06:45 +00005574 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00005575 Member->setInvalidDecl();
5576 }
5577 }
5578
5579 if (Class->getDescribedClassTemplate())
5580 // Don't inherit dll attribute until the template is instantiated.
5581 return;
5582
Hans Wennborg606bd6d2014-11-03 14:24:45 +00005583 // The class is either imported or exported.
5584 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
Hans Wennborg853ae942014-05-30 16:59:42 +00005585
Hans Wennborgfd76d912015-01-15 21:18:30 +00005586 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5587
Hans Wennborgbb1983c2015-06-09 00:39:03 +00005588 // Ignore explicit dllexport on explicit class template instantiation declarations.
5589 if (ClassExported && !ClassAttr->isInherited() &&
5590 TSK == TSK_ExplicitInstantiationDeclaration) {
Hans Wennborgfd76d912015-01-15 21:18:30 +00005591 Class->dropAttr<DLLExportAttr>();
5592 return;
5593 }
5594
Hans Wennborg853ae942014-05-30 16:59:42 +00005595 // Force declaration of implicit members so they can inherit the attribute.
Hans Wennborg17f9b442015-05-27 00:06:45 +00005596 ForceDeclarationOfImplicitMembers(Class);
Hans Wennborg853ae942014-05-30 16:59:42 +00005597
5598 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5599 // seem to be true in practice?
5600
Hans Wennborg853ae942014-05-30 16:59:42 +00005601 for (Decl *Member : Class->decls()) {
Hans Wennborge8ad3832014-06-11 22:44:39 +00005602 VarDecl *VD = dyn_cast<VarDecl>(Member);
5603 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5604
5605 // Only methods and static fields inherit the attributes.
5606 if (!VD && !MD)
Hans Wennborg853ae942014-05-30 16:59:42 +00005607 continue;
Hans Wennborge8ad3832014-06-11 22:44:39 +00005608
Hans Wennborg606bd6d2014-11-03 14:24:45 +00005609 if (MD) {
5610 // Don't process deleted methods.
5611 if (MD->isDeleted())
5612 continue;
Hans Wennborg853ae942014-05-30 16:59:42 +00005613
David Majnemer30f058a2015-05-11 03:00:22 +00005614 if (MD->isInlined()) {
Hans Wennborg97cbed42015-02-19 22:39:24 +00005615 // MinGW does not import or export inline methods.
Saleem Abdulrasool8bbc3152016-10-14 22:25:46 +00005616 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5617 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
David Majnemer30f058a2015-05-11 03:00:22 +00005618 continue;
5619
Dmitry Polukhin41581522016-05-13 09:03:56 +00005620 // MSVC versions before 2015 don't export the move assignment operators
5621 // and move constructor, so don't attempt to import/export them if
5622 // we have a definition.
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005623 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
Dmitry Polukhin41581522016-05-13 09:03:56 +00005624 if ((MD->isMoveAssignmentOperator() ||
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005625 (Ctor && Ctor->isMoveConstructor())) &&
Hans Wennborg17f9b442015-05-27 00:06:45 +00005626 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
David Majnemer30f058a2015-05-11 03:00:22 +00005627 continue;
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005628
5629 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5630 // operator is exported anyway.
5631 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5632 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5633 continue;
Hans Wennborg606bd6d2014-11-03 14:24:45 +00005634 }
Hans Wennborge8ad3832014-06-11 22:44:39 +00005635 }
5636
Hans Wennborg287231c2015-04-22 04:05:17 +00005637 if (!cast<NamedDecl>(Member)->isExternallyVisible())
5638 continue;
5639
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00005640 if (!getDLLAttr(Member)) {
Hans Wennborg496524b2014-05-31 02:08:49 +00005641 auto *NewAttr =
Hans Wennborg17f9b442015-05-27 00:06:45 +00005642 cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
Hans Wennborg496524b2014-05-31 02:08:49 +00005643 NewAttr->setInherited(true);
5644 Member->addAttr(NewAttr);
5645 }
Hans Wennborg853ae942014-05-30 16:59:42 +00005646 }
Hans Wennborg99000c22015-08-15 01:18:16 +00005647
5648 if (ClassExported)
5649 DelayedDllExportClasses.push_back(Class);
Hans Wennborg853ae942014-05-30 16:59:42 +00005650}
5651
Hans Wennborgfce87ca2015-06-09 00:39:09 +00005652/// \brief Perform propagation of DLL attributes from a derived class to a
5653/// templated base class for MS compatibility.
5654void Sema::propagateDLLAttrToBaseClassTemplate(
5655 CXXRecordDecl *Class, Attr *ClassAttr,
5656 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5657 if (getDLLAttr(
5658 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5659 // If the base class template has a DLL attribute, don't try to change it.
5660 return;
5661 }
5662
5663 auto TSK = BaseTemplateSpec->getSpecializationKind();
5664 if (!getDLLAttr(BaseTemplateSpec) &&
5665 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5666 TSK == TSK_ImplicitInstantiation)) {
5667 // The template hasn't been instantiated yet (or it has, but only as an
5668 // explicit instantiation declaration or implicit instantiation, which means
5669 // we haven't codegenned any members yet), so propagate the attribute.
5670 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5671 NewAttr->setInherited(true);
5672 BaseTemplateSpec->addAttr(NewAttr);
5673
5674 // If the template is already instantiated, checkDLLAttributeRedeclaration()
5675 // needs to be run again to work see the new attribute. Otherwise this will
5676 // get run whenever the template is instantiated.
5677 if (TSK != TSK_Undeclared)
5678 checkClassLevelDLLAttribute(BaseTemplateSpec);
5679
5680 return;
5681 }
5682
5683 if (getDLLAttr(BaseTemplateSpec)) {
5684 // The template has already been specialized or instantiated with an
5685 // attribute, explicitly or through propagation. We should not try to change
5686 // it.
5687 return;
5688 }
5689
5690 // The template was previously instantiated or explicitly specialized without
5691 // a dll attribute, It's too late for us to add an attribute, so warn that
5692 // this is unsupported.
5693 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5694 << BaseTemplateSpec->isExplicitSpecialization();
5695 Diag(ClassAttr->getLocation(), diag::note_attribute);
5696 if (BaseTemplateSpec->isExplicitSpecialization()) {
5697 Diag(BaseTemplateSpec->getLocation(),
5698 diag::note_template_class_explicit_specialization_was_here)
5699 << BaseTemplateSpec;
5700 } else {
5701 Diag(BaseTemplateSpec->getPointOfInstantiation(),
5702 diag::note_template_class_instantiation_was_here)
5703 << BaseTemplateSpec;
5704 }
5705}
5706
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005707static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5708 SourceLocation DefaultLoc) {
5709 switch (S.getSpecialMember(MD)) {
5710 case Sema::CXXDefaultConstructor:
5711 S.DefineImplicitDefaultConstructor(DefaultLoc,
5712 cast<CXXConstructorDecl>(MD));
5713 break;
5714 case Sema::CXXCopyConstructor:
5715 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5716 break;
5717 case Sema::CXXCopyAssignment:
5718 S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5719 break;
5720 case Sema::CXXDestructor:
5721 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5722 break;
5723 case Sema::CXXMoveConstructor:
5724 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5725 break;
5726 case Sema::CXXMoveAssignment:
5727 S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5728 break;
5729 case Sema::CXXInvalid:
5730 llvm_unreachable("Invalid special member.");
5731 }
5732}
5733
Richard Smith96cd6712017-08-16 01:49:53 +00005734/// Determine whether a type is permitted to be passed or returned in
5735/// registers, per C++ [class.temporary]p3.
5736static bool computeCanPassInRegisters(Sema &S, CXXRecordDecl *D) {
5737 if (D->isDependentType() || D->isInvalidDecl())
5738 return false;
5739
5740 // Per C++ [class.temporary]p3, the relevant condition is:
5741 // each copy constructor, move constructor, and destructor of X is
5742 // either trivial or deleted, and X has at least one non-deleted copy
5743 // or move constructor
5744 bool HasNonDeletedCopyOrMove = false;
5745
5746 if (D->needsImplicitCopyConstructor() &&
5747 !D->defaultedCopyConstructorIsDeleted()) {
5748 if (!D->hasTrivialCopyConstructor())
5749 return false;
Erich Keanebb863642017-09-20 22:28:24 +00005750 HasNonDeletedCopyOrMove = true;
Richard Smith96cd6712017-08-16 01:49:53 +00005751 }
5752
5753 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
5754 !D->defaultedMoveConstructorIsDeleted()) {
5755 if (!D->hasTrivialMoveConstructor())
5756 return false;
5757 HasNonDeletedCopyOrMove = true;
5758 }
5759
5760 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
5761 !D->hasTrivialDestructor())
5762 return false;
5763
5764 for (const CXXMethodDecl *MD : D->methods()) {
5765 if (MD->isDeleted())
5766 continue;
5767
5768 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
5769 if (CD && CD->isCopyOrMoveConstructor())
5770 HasNonDeletedCopyOrMove = true;
5771 else if (!isa<CXXDestructorDecl>(MD))
5772 continue;
5773
5774 if (!MD->isTrivial())
5775 return false;
5776 }
5777
5778 return HasNonDeletedCopyOrMove;
5779}
5780
Douglas Gregorc99f1552009-12-03 18:33:45 +00005781/// \brief Perform semantic checks on a class definition that has been
5782/// completing, introducing implicitly-declared members, checking for
5783/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00005784void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00005785 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00005786 return;
5787
John McCall02db245d2010-08-18 09:41:07 +00005788 if (Record->isAbstract() && !Record->isInvalidDecl()) {
5789 AbstractUsageInfo Info(*this, Record);
5790 CheckAbstractClassUsage(Info, Record);
5791 }
Erich Keanebb863642017-09-20 22:28:24 +00005792
Douglas Gregor454a5b62010-04-15 00:00:53 +00005793 // If this is not an aggregate type and has no user-declared constructor,
5794 // complain about any non-static data members of reference or const scalar
5795 // type, since they will never get initializers.
5796 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00005797 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
5798 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00005799 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005800 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00005801 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00005802 continue;
5803
Douglas Gregor454a5b62010-04-15 00:00:53 +00005804 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00005805 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00005806 if (!Complained) {
5807 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
5808 << Record->getTagKind() << Record;
5809 Complained = true;
5810 }
Erich Keanebb863642017-09-20 22:28:24 +00005811
Douglas Gregor454a5b62010-04-15 00:00:53 +00005812 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
5813 << F->getType()->isReferenceType()
5814 << F->getDeclName();
5815 }
5816 }
5817 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00005818
Douglas Gregor36c22a22010-10-15 13:21:21 +00005819 if (Record->getIdentifier()) {
5820 // C++ [class.mem]p13:
Erich Keanebb863642017-09-20 22:28:24 +00005821 // If T is the name of a class, then each of the following shall have a
Douglas Gregor36c22a22010-10-15 13:21:21 +00005822 // name different from T:
5823 // - every member of every anonymous union that is a member of class T.
5824 //
5825 // C++ [class.mem]p14:
Erich Keanebb863642017-09-20 22:28:24 +00005826 // In addition, if class T has a user-declared constructor (12.1), every
Douglas Gregor36c22a22010-10-15 13:21:21 +00005827 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00005828 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
5829 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
5830 ++I) {
5831 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00005832 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
5833 isa<IndirectFieldDecl>(D)) {
5834 Diag(D->getLocation(), diag::err_member_name_of_class)
5835 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00005836 break;
5837 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00005838 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00005839 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00005840
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00005841 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00005842 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00005843 CXXDestructorDecl *dtor = Record->getDestructor();
David Blaikie04e2e662014-05-09 22:02:28 +00005844 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
5845 !Record->hasAttr<FinalAttr>())
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00005846 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
5847 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
5848 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005849
David Majnemera5433082013-10-18 00:33:31 +00005850 if (Record->isAbstract()) {
5851 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
5852 Diag(Record->getLocation(), diag::warn_abstract_final_class)
5853 << FA->isSpelledAsSealed();
5854 DiagnoseAbstractType(Record);
5855 }
David Blaikie348df502012-09-21 03:21:07 +00005856 }
5857
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00005858 bool HasMethodWithOverrideControl = false,
5859 HasOverridingMethodWithoutOverrideControl = false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005860 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005861 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00005862 // See if a method overloads virtual methods in a base
5863 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005864 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00005865 DiagnoseHiddenVirtualMethods(M);
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00005866 if (M->hasAttr<OverrideAttr>())
5867 HasMethodWithOverrideControl = true;
5868 else if (M->size_overridden_methods() > 0)
5869 HasOverridingMethodWithoutOverrideControl = true;
Richard Smithbd305122012-12-11 01:14:52 +00005870 // Check whether the explicitly-defaulted special members are valid.
5871 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00005872 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00005873
5874 // For an explicitly defaulted or deleted special member, we defer
5875 // determining triviality until the class is complete. That time is now!
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005876 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00005877 if (!M->isImplicit() && !M->isUserProvided()) {
Richard Smithbd305122012-12-11 01:14:52 +00005878 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005879 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00005880
5881 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005882 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00005883 }
5884 }
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005885
5886 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
5887 M->hasAttr<DLLExportAttr>()) {
5888 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5889 M->isTrivial() &&
5890 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
5891 CSM == CXXDestructor))
5892 M->dropAttr<DLLExportAttr>();
5893
5894 if (M->hasAttr<DLLExportAttr>()) {
5895 DefineImplicitSpecialMember(*this, M, M->getLocation());
5896 ActOnFinishInlineFunctionDef(M);
5897 }
5898 }
Richard Smithbd305122012-12-11 01:14:52 +00005899 }
5900 }
5901
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00005902 if (HasMethodWithOverrideControl &&
5903 HasOverridingMethodWithoutOverrideControl) {
5904 // At least one method has the 'override' control declared.
5905 // Diagnose all other overridden methods which do not have 'override' specified on them.
5906 for (auto *M : Record->methods())
5907 DiagnoseAbsenceOfOverrideControl(M);
5908 }
Sebastian Redl08905022011-02-05 19:23:19 +00005909
John McCall95833f32014-02-27 20:30:49 +00005910 // ms_struct is a request to use the same ABI rules as MSVC. Check
5911 // whether this class uses any C++ features that are implemented
5912 // completely differently in MSVC, and if so, emit a diagnostic.
5913 // That diagnostic defaults to an error, but we allow projects to
5914 // map it down to a warning (or ignore it). It's a fairly common
5915 // practice among users of the ms_struct pragma to mass-annotate
5916 // headers, sweeping up a bunch of types that the project doesn't
5917 // really rely on MSVC-compatible layout for. We must therefore
5918 // support "ms_struct except for C++ stuff" as a secondary ABI.
5919 if (Record->isMsStruct(Context) &&
5920 (Record->isPolymorphic() || Record->getNumBases())) {
5921 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00005922 }
5923
Hans Wennborg17f9b442015-05-27 00:06:45 +00005924 checkClassLevelDLLAttribute(Record);
Richard Smith96cd6712017-08-16 01:49:53 +00005925
5926 Record->setCanPassInRegisters(computeCanPassInRegisters(*this, Record));
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005927}
5928
Richard Smith41c35d62013-11-27 03:39:20 +00005929/// Look up the special member function that would be called by a special
5930/// member function for a subobject of class type.
5931///
5932/// \param Class The class type of the subobject.
5933/// \param CSM The kind of special member function.
5934/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5935/// \param ConstRHS True if this is a copy operation with a const object
5936/// on its RHS, that is, if the argument to the outer special member
5937/// function is 'const' and this is not a field marked 'mutable'.
Richard Smith8bae1be2017-02-24 02:07:20 +00005938static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
Richard Smith41c35d62013-11-27 03:39:20 +00005939 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5940 unsigned FieldQuals, bool ConstRHS) {
5941 unsigned LHSQuals = 0;
5942 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5943 LHSQuals = FieldQuals;
5944
5945 unsigned RHSQuals = FieldQuals;
5946 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5947 RHSQuals = 0;
5948 else if (ConstRHS)
5949 RHSQuals |= Qualifiers::Const;
5950
5951 return S.LookupSpecialMember(Class, CSM,
5952 RHSQuals & Qualifiers::Const,
5953 RHSQuals & Qualifiers::Volatile,
5954 false,
5955 LHSQuals & Qualifiers::Const,
5956 LHSQuals & Qualifiers::Volatile);
5957}
5958
Richard Smith80a47022016-06-29 01:10:27 +00005959class Sema::InheritedConstructorInfo {
Richard Smith5179eb72016-06-28 19:03:57 +00005960 Sema &S;
5961 SourceLocation UseLoc;
Richard Smith5179eb72016-06-28 19:03:57 +00005962
5963 /// A mapping from the base classes through which the constructor was
5964 /// inherited to the using shadow declaration in that base class (or a null
5965 /// pointer if the constructor was declared in that base class).
5966 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
5967 InheritedFromBases;
5968
Richard Smith80a47022016-06-29 01:10:27 +00005969public:
Richard Smith5179eb72016-06-28 19:03:57 +00005970 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
5971 ConstructorUsingShadowDecl *Shadow)
Richard Smith80a47022016-06-29 01:10:27 +00005972 : S(S), UseLoc(UseLoc) {
Richard Smith5179eb72016-06-28 19:03:57 +00005973 bool DiagnosedMultipleConstructedBases = false;
5974 CXXRecordDecl *ConstructedBase = nullptr;
5975 UsingDecl *ConstructedBaseUsing = nullptr;
5976
5977 // Find the set of such base class subobjects and check that there's a
5978 // unique constructed subobject.
5979 for (auto *D : Shadow->redecls()) {
5980 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
5981 auto *DNominatedBase = DShadow->getNominatedBaseClass();
5982 auto *DConstructedBase = DShadow->getConstructedBaseClass();
5983
5984 InheritedFromBases.insert(
5985 std::make_pair(DNominatedBase->getCanonicalDecl(),
5986 DShadow->getNominatedBaseClassShadowDecl()));
5987 if (DShadow->constructsVirtualBase())
5988 InheritedFromBases.insert(
5989 std::make_pair(DConstructedBase->getCanonicalDecl(),
5990 DShadow->getConstructedBaseClassShadowDecl()));
5991 else
5992 assert(DNominatedBase == DConstructedBase);
5993
5994 // [class.inhctor.init]p2:
5995 // If the constructor was inherited from multiple base class subobjects
5996 // of type B, the program is ill-formed.
5997 if (!ConstructedBase) {
5998 ConstructedBase = DConstructedBase;
5999 ConstructedBaseUsing = D->getUsingDecl();
6000 } else if (ConstructedBase != DConstructedBase &&
6001 !Shadow->isInvalidDecl()) {
6002 if (!DiagnosedMultipleConstructedBases) {
6003 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6004 << Shadow->getTargetDecl();
6005 S.Diag(ConstructedBaseUsing->getLocation(),
6006 diag::note_ambiguous_inherited_constructor_using)
6007 << ConstructedBase;
6008 DiagnosedMultipleConstructedBases = true;
6009 }
6010 S.Diag(D->getUsingDecl()->getLocation(),
6011 diag::note_ambiguous_inherited_constructor_using)
6012 << DConstructedBase;
6013 }
6014 }
6015
6016 if (DiagnosedMultipleConstructedBases)
6017 Shadow->setInvalidDecl();
6018 }
6019
6020 /// Find the constructor to use for inherited construction of a base class,
6021 /// and whether that base class constructor inherits the constructor from a
6022 /// virtual base class (in which case it won't actually invoke it).
6023 std::pair<CXXConstructorDecl *, bool>
6024 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6025 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6026 if (It == InheritedFromBases.end())
6027 return std::make_pair(nullptr, false);
6028
6029 // This is an intermediary class.
6030 if (It->second)
6031 return std::make_pair(
6032 S.findInheritingConstructor(UseLoc, Ctor, It->second),
6033 It->second->constructsVirtualBase());
6034
6035 // This is the base class from which the constructor was inherited.
6036 return std::make_pair(Ctor, false);
6037 }
6038};
Richard Smith5179eb72016-06-28 19:03:57 +00006039
Richard Smithb5800092012-06-10 05:43:50 +00006040/// Is the special member function which would be selected to perform the
6041/// specified operation on the specified class type a constexpr constructor?
Richard Smith5179eb72016-06-28 19:03:57 +00006042static bool
6043specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6044 Sema::CXXSpecialMember CSM, unsigned Quals,
6045 bool ConstRHS,
6046 CXXConstructorDecl *InheritedCtor = nullptr,
Richard Smith80a47022016-06-29 01:10:27 +00006047 Sema::InheritedConstructorInfo *Inherited = nullptr) {
Richard Smith5179eb72016-06-28 19:03:57 +00006048 // If we're inheriting a constructor, see if we need to call it for this base
6049 // class.
6050 if (InheritedCtor) {
6051 assert(CSM == Sema::CXXDefaultConstructor);
6052 auto BaseCtor =
6053 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6054 if (BaseCtor)
6055 return BaseCtor->isConstexpr();
6056 }
6057
6058 if (CSM == Sema::CXXDefaultConstructor)
6059 return ClassDecl->hasConstexprDefaultConstructor();
6060
Richard Smith8bae1be2017-02-24 02:07:20 +00006061 Sema::SpecialMemberOverloadResult SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00006062 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smith8bae1be2017-02-24 02:07:20 +00006063 if (!SMOR.getMethod())
Richard Smithb5800092012-06-10 05:43:50 +00006064 // A constructor we wouldn't select can't be "involved in initializing"
6065 // anything.
6066 return true;
Richard Smith8bae1be2017-02-24 02:07:20 +00006067 return SMOR.getMethod()->isConstexpr();
Richard Smithb5800092012-06-10 05:43:50 +00006068}
6069
6070/// Determine whether the specified special member function would be constexpr
6071/// if it were implicitly defined.
Richard Smith5179eb72016-06-28 19:03:57 +00006072static bool defaultedSpecialMemberIsConstexpr(
6073 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6074 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
Richard Smith80a47022016-06-29 01:10:27 +00006075 Sema::InheritedConstructorInfo *Inherited = nullptr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006076 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00006077 return false;
6078
6079 // C++11 [dcl.constexpr]p4:
6080 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00006081 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00006082 switch (CSM) {
6083 case Sema::CXXDefaultConstructor:
Richard Smith5179eb72016-06-28 19:03:57 +00006084 if (Inherited)
6085 break;
Richard Smith4086a132012-06-10 07:07:24 +00006086 // Since default constructor lookup is essentially trivial (and cannot
6087 // involve, for instance, template instantiation), we compute whether a
6088 // defaulted default constructor is constexpr directly within CXXRecordDecl.
6089 //
6090 // This is important for performance; we need to know whether the default
6091 // constructor is constexpr to determine whether the type is a literal type.
6092 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6093
Richard Smithb5800092012-06-10 05:43:50 +00006094 case Sema::CXXCopyConstructor:
6095 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00006096 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00006097 break;
6098
6099 case Sema::CXXCopyAssignment:
6100 case Sema::CXXMoveAssignment:
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006101 if (!S.getLangOpts().CPlusPlus14)
Richard Smith99005e62013-05-07 03:19:20 +00006102 return false;
6103 // In C++1y, we need to perform overload resolution.
6104 Ctor = false;
6105 break;
6106
Richard Smithb5800092012-06-10 05:43:50 +00006107 case Sema::CXXDestructor:
6108 case Sema::CXXInvalid:
6109 return false;
6110 }
6111
6112 // -- if the class is a non-empty union, or for each non-empty anonymous
6113 // union member of a non-union class, exactly one non-static data member
6114 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00006115 //
6116 // If we squint, this is guaranteed, since exactly one non-static data member
6117 // will be initialized (if the constructor isn't deleted), we just don't know
6118 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00006119 if (Ctor && ClassDecl->isUnion())
Richard Smith5179eb72016-06-28 19:03:57 +00006120 return CSM == Sema::CXXDefaultConstructor
6121 ? ClassDecl->hasInClassInitializer() ||
6122 !ClassDecl->hasVariantMembers()
6123 : true;
Richard Smithb5800092012-06-10 05:43:50 +00006124
6125 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00006126 if (Ctor && ClassDecl->getNumVBases())
6127 return false;
6128
6129 // C++1y [class.copy]p26:
6130 // -- [the class] is a literal type, and
6131 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00006132 return false;
6133
6134 // -- every constructor involved in initializing [...] base class
6135 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00006136 // -- the assignment operator selected to copy/move each direct base
6137 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00006138 for (const auto &B : ClassDecl->bases()) {
6139 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00006140 if (!BaseType) continue;
6141
6142 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith5179eb72016-06-28 19:03:57 +00006143 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6144 InheritedCtor, Inherited))
Richard Smithb5800092012-06-10 05:43:50 +00006145 return false;
6146 }
6147
6148 // -- every constructor involved in initializing non-static data members
6149 // [...] shall be a constexpr constructor;
6150 // -- every non-static data member and base class sub-object shall be
6151 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00006152 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00006153 // thereof), the assignment operator selected to copy/move that member is
6154 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006155 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00006156 if (F->isInvalidDecl())
6157 continue;
Richard Smith5179eb72016-06-28 19:03:57 +00006158 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6159 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00006160 QualType BaseType = S.Context.getBaseElementType(F->getType());
6161 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00006162 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00006163 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6164 BaseType.getCVRQualifiers(),
6165 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00006166 return false;
Richard Smith5179eb72016-06-28 19:03:57 +00006167 } else if (CSM == Sema::CXXDefaultConstructor) {
6168 return false;
Richard Smithb5800092012-06-10 05:43:50 +00006169 }
6170 }
6171
6172 // All OK, it's constexpr!
6173 return true;
6174}
6175
Richard Smithd3b5c9082012-07-27 04:22:15 +00006176static Sema::ImplicitExceptionSpecification
Richard Smith2246c832017-02-24 01:29:42 +00006177ComputeDefaultedSpecialMemberExceptionSpec(
6178 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6179 Sema::InheritedConstructorInfo *ICI);
6180
6181static Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00006182computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
Richard Smith55118002017-02-24 01:36:58 +00006183 auto CSM = S.getSpecialMember(MD);
6184 if (CSM != Sema::CXXInvalid)
6185 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
Richard Smith2246c832017-02-24 01:29:42 +00006186
6187 auto *CD = cast<CXXConstructorDecl>(MD);
6188 assert(CD->getInheritedConstructor() &&
Richard Smithc2bc61b2013-03-18 21:12:30 +00006189 "only special members have implicit exception specs");
Richard Smith2246c832017-02-24 01:29:42 +00006190 Sema::InheritedConstructorInfo ICI(
6191 S, Loc, CD->getInheritedConstructor().getShadowDecl());
6192 return ComputeDefaultedSpecialMemberExceptionSpec(
6193 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00006194}
6195
Reid Kleckner78af0702013-08-27 23:08:25 +00006196static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6197 CXXMethodDecl *MD) {
6198 FunctionProtoType::ExtProtoInfo EPI;
6199
6200 // Build an exception specification pointing back at this member.
Richard Smith8acb4282014-07-31 21:57:55 +00006201 EPI.ExceptionSpec.Type = EST_Unevaluated;
6202 EPI.ExceptionSpec.SourceDecl = MD;
Reid Kleckner78af0702013-08-27 23:08:25 +00006203
6204 // Set the calling convention to the default for C++ instance methods.
6205 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6206 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6207 /*IsCXXMethod=*/true));
6208 return EPI;
6209}
6210
Richard Smithd3b5c9082012-07-27 04:22:15 +00006211void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6212 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6213 if (FPT->getExceptionSpecType() != EST_Unevaluated)
6214 return;
6215
Richard Smith7f782272012-07-30 23:48:14 +00006216 // Evaluate the exception specification.
Vitaly Bukaac10dcc2016-12-05 18:30:22 +00006217 auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6218 auto ESI = IES.getExceptionSpec();
Richard Smith564417a2014-03-20 21:47:22 +00006219
Richard Smith7f782272012-07-30 23:48:14 +00006220 // Update the type of the special member to use it.
Richard Smith8acb4282014-07-31 21:57:55 +00006221 UpdateExceptionSpec(MD, ESI);
Richard Smith7f782272012-07-30 23:48:14 +00006222
6223 // A user-provided destructor can be defined outside the class. When that
6224 // happens, be sure to update the exception specification on both
6225 // declarations.
6226 const FunctionProtoType *CanonicalFPT =
6227 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6228 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smith8acb4282014-07-31 21:57:55 +00006229 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00006230}
6231
Richard Smithb9e90b12012-05-15 04:39:51 +00006232void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6233 CXXRecordDecl *RD = MD->getParent();
6234 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00006235
Richard Smithb9e90b12012-05-15 04:39:51 +00006236 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6237 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00006238
6239 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00006240 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00006241 bool First = MD == MD->getCanonicalDecl();
6242
6243 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00006244
6245 // C++11 [dcl.fct.def.default]p1:
6246 // A function that is explicitly defaulted shall
6247 // -- be a special member function (checked elsewhere),
6248 // -- have the same type (except for ref-qualifiers, and except that a
6249 // copy operation can take a non-const reference) as an implicit
6250 // declaration, and
6251 // -- not have default arguments.
6252 unsigned ExpectedParams = 1;
6253 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6254 ExpectedParams = 0;
6255 if (MD->getNumParams() != ExpectedParams) {
6256 // This also checks for default arguments: a copy or move constructor with a
6257 // default argument is classified as a default constructor, and assignment
6258 // operations and destructors can't have default arguments.
6259 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6260 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00006261 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00006262 } else if (MD->isVariadic()) {
6263 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6264 << CSM << MD->getSourceRange();
6265 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00006266 }
6267
Richard Smithb9e90b12012-05-15 04:39:51 +00006268 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00006269
Richard Smithb5800092012-06-10 05:43:50 +00006270 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00006271 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00006272 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00006273 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00006274 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00006275
Richard Smithb9e90b12012-05-15 04:39:51 +00006276 QualType ReturnType = Context.VoidTy;
6277 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6278 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00006279 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00006280 QualType ExpectedReturnType =
6281 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
6282 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6283 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6284 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6285 HadError = true;
6286 }
6287
6288 // A defaulted special member cannot have cv-qualifiers.
6289 if (Type->getTypeQuals()) {
6290 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006291 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
Richard Smithb9e90b12012-05-15 04:39:51 +00006292 HadError = true;
6293 }
6294 }
6295
6296 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00006297 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00006298 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00006299 if (ExpectedParams && ArgType->isReferenceType()) {
6300 // Argument must be reference to possibly-const T.
6301 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00006302 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00006303
6304 if (ReferentType.isVolatileQualified()) {
6305 Diag(MD->getLocation(),
6306 diag::err_defaulted_special_member_volatile_param) << CSM;
6307 HadError = true;
6308 }
6309
Richard Smithb5800092012-06-10 05:43:50 +00006310 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00006311 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6312 Diag(MD->getLocation(),
6313 diag::err_defaulted_special_member_copy_const_param)
6314 << (CSM == CXXCopyAssignment);
6315 // FIXME: Explain why this special member can't be const.
6316 } else {
6317 Diag(MD->getLocation(),
6318 diag::err_defaulted_special_member_move_const_param)
6319 << (CSM == CXXMoveAssignment);
6320 }
6321 HadError = true;
6322 }
Richard Smithb9e90b12012-05-15 04:39:51 +00006323 } else if (ExpectedParams) {
6324 // A copy assignment operator can take its argument by value, but a
6325 // defaulted one cannot.
6326 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00006327 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00006328 HadError = true;
6329 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00006330
Richard Smithcc36f692011-12-22 02:22:31 +00006331 // C++11 [dcl.fct.def.default]p2:
6332 // An explicitly-defaulted function may be declared constexpr only if it
6333 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00006334 // Do not apply this rule to members of class templates, since core issue 1358
6335 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00006336 // functions which cannot be constexpr (for non-constructors in C++11 and for
6337 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00006338 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6339 HasConstParam);
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006340 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
Richard Smith99005e62013-05-07 03:19:20 +00006341 : isa<CXXConstructorDecl>(MD)) &&
6342 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00006343 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6344 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00006345 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00006346 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00006347 }
Richard Smithbd305122012-12-11 01:14:52 +00006348
Richard Smithcc36f692011-12-22 02:22:31 +00006349 // and may have an explicit exception-specification only if it is compatible
6350 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00006351 if (Type->hasExceptionSpec()) {
6352 // Delay the check if this is the first declaration of the special member,
6353 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00006354 if (First) {
6355 // If the exception specification needs to be instantiated, do so now,
6356 // before we clobber it with an EST_Unevaluated specification below.
6357 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6358 InstantiateExceptionSpec(MD->getLocStart(), MD);
6359 Type = MD->getType()->getAs<FunctionProtoType>();
6360 }
Richard Smithbd305122012-12-11 01:14:52 +00006361 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00006362 } else
Richard Smithbd305122012-12-11 01:14:52 +00006363 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6364 }
Richard Smithcc36f692011-12-22 02:22:31 +00006365
6366 // If a function is explicitly defaulted on its first declaration,
6367 if (First) {
6368 // -- it is implicitly considered to be constexpr if the implicit
6369 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00006370 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00006371
Richard Smithb9e90b12012-05-15 04:39:51 +00006372 // -- it is implicitly considered to have the same exception-specification
6373 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00006374 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00006375 EPI.ExceptionSpec.Type = EST_Unevaluated;
6376 EPI.ExceptionSpec.SourceDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00006377 MD->setType(Context.getFunctionType(ReturnType,
Craig Topper5fc8fc22014-08-27 06:28:36 +00006378 llvm::makeArrayRef(&ArgType,
Jordan Rose5c382722013-03-08 21:51:21 +00006379 ExpectedParams),
6380 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00006381 }
6382
Richard Smithb9e90b12012-05-15 04:39:51 +00006383 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00006384 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00006385 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00006386 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00006387 // C++11 [dcl.fct.def.default]p4:
6388 // [For a] user-provided explicitly-defaulted function [...] if such a
6389 // function is implicitly defined as deleted, the program is ill-formed.
6390 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith80a47022016-06-29 01:10:27 +00006391 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00006392 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00006393 }
6394 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00006395
Richard Smithb9e90b12012-05-15 04:39:51 +00006396 if (HadError)
6397 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00006398}
6399
Richard Smithbd305122012-12-11 01:14:52 +00006400/// Check whether the exception specification provided for an
6401/// explicitly-defaulted special member matches the exception specification
6402/// that would have been generated for an implicit special member, per
6403/// C++11 [dcl.fct.def.default]p2.
6404void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6405 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
Richard Smith0b3a4622014-11-13 20:01:57 +00006406 // If the exception specification was explicitly specified but hadn't been
6407 // parsed when the method was defaulted, grab it now.
6408 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6409 SpecifiedType =
6410 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6411
Richard Smithbd305122012-12-11 01:14:52 +00006412 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00006413 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6414 /*IsCXXMethod=*/true);
6415 FunctionProtoType::ExtProtoInfo EPI(CC);
Vitaly Buka846b8f72016-12-05 19:25:00 +00006416 auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
6417 EPI.ExceptionSpec = IES.getExceptionSpec();
Richard Smithbd305122012-12-11 01:14:52 +00006418 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006419 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00006420
6421 // Ensure that it matches.
6422 CheckEquivalentExceptionSpec(
6423 PDiag(diag::err_incorrect_defaulted_exception_spec)
6424 << getSpecialMember(MD), PDiag(),
6425 ImplicitType, SourceLocation(),
6426 SpecifiedType, MD->getLocation());
6427}
6428
Alp Tokerae3a9442013-10-18 05:54:19 +00006429void Sema::CheckDelayedMemberExceptionSpecs() {
Richard Smith88f45492014-11-22 03:09:05 +00006430 decltype(DelayedExceptionSpecChecks) Checks;
6431 decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
Richard Smithbd305122012-12-11 01:14:52 +00006432
Richard Smith88f45492014-11-22 03:09:05 +00006433 std::swap(Checks, DelayedExceptionSpecChecks);
Alp Tokerae3a9442013-10-18 05:54:19 +00006434 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
6435
6436 // Perform any deferred checking of exception specifications for virtual
6437 // destructors.
Richard Smith88f45492014-11-22 03:09:05 +00006438 for (auto &Check : Checks)
6439 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
Alp Tokerae3a9442013-10-18 05:54:19 +00006440
6441 // Check that any explicitly-defaulted methods have exception specifications
6442 // compatible with their implicit exception specifications.
Richard Smith88f45492014-11-22 03:09:05 +00006443 for (auto &Spec : Specs)
6444 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
Richard Smithbd305122012-12-11 01:14:52 +00006445}
6446
Richard Smithd951a1d2012-02-18 02:02:13 +00006447namespace {
Richard Smith8bae1be2017-02-24 02:07:20 +00006448/// CRTP base class for visiting operations performed by a special member
6449/// function (or inherited constructor).
6450template<typename Derived>
6451struct SpecialMemberVisitor {
Richard Smithd951a1d2012-02-18 02:02:13 +00006452 Sema &S;
6453 CXXMethodDecl *MD;
6454 Sema::CXXSpecialMember CSM;
Richard Smith80a47022016-06-29 01:10:27 +00006455 Sema::InheritedConstructorInfo *ICI;
Richard Smith8bae1be2017-02-24 02:07:20 +00006456
Richard Smith6f0e63e2017-02-24 21:18:47 +00006457 // Properties of the special member, computed for convenience.
6458 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
Richard Smith8bae1be2017-02-24 02:07:20 +00006459
6460 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6461 Sema::InheritedConstructorInfo *ICI)
6462 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
Richard Smith6f0e63e2017-02-24 21:18:47 +00006463 switch (CSM) {
6464 case Sema::CXXDefaultConstructor:
6465 case Sema::CXXCopyConstructor:
6466 case Sema::CXXMoveConstructor:
6467 IsConstructor = true;
6468 break;
6469 case Sema::CXXCopyAssignment:
6470 case Sema::CXXMoveAssignment:
6471 IsAssignment = true;
6472 break;
6473 case Sema::CXXDestructor:
6474 break;
6475 case Sema::CXXInvalid:
6476 llvm_unreachable("invalid special member kind");
6477 }
6478
Richard Smith8bae1be2017-02-24 02:07:20 +00006479 if (MD->getNumParams()) {
6480 if (const ReferenceType *RT =
6481 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6482 ConstArg = RT->getPointeeType().isConstQualified();
6483 }
6484 }
6485
Richard Smith6f0e63e2017-02-24 21:18:47 +00006486 Derived &getDerived() { return static_cast<Derived&>(*this); }
6487
6488 /// Is this a "move" special member?
6489 bool isMove() const {
6490 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6491 }
6492
Richard Smith8bae1be2017-02-24 02:07:20 +00006493 /// Look up the corresponding special member in the given class.
6494 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6495 unsigned Quals, bool IsMutable) {
6496 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6497 ConstArg && !IsMutable);
6498 }
6499
Richard Smith6f0e63e2017-02-24 21:18:47 +00006500 /// Look up the constructor for the specified base class to see if it's
6501 /// overridden due to this being an inherited constructor.
6502 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6503 if (!ICI)
6504 return {};
6505 assert(CSM == Sema::CXXDefaultConstructor);
6506 auto *BaseCtor =
6507 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6508 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6509 return MD;
6510 return {};
6511 }
6512
Richard Smith8bae1be2017-02-24 02:07:20 +00006513 /// A base or member subobject.
6514 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6515
Richard Smith6f0e63e2017-02-24 21:18:47 +00006516 /// Get the location to use for a subobject in diagnostics.
Richard Smith8bae1be2017-02-24 02:07:20 +00006517 static SourceLocation getSubobjectLoc(Subobject Subobj) {
Richard Smith6f0e63e2017-02-24 21:18:47 +00006518 // FIXME: For an indirect virtual base, the direct base leading to
6519 // the indirect virtual base would be a more useful choice.
Richard Smith8bae1be2017-02-24 02:07:20 +00006520 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6521 return B->getBaseTypeLoc();
6522 else
6523 return Subobj.get<FieldDecl*>()->getLocation();
6524 }
6525
Richard Smith6f0e63e2017-02-24 21:18:47 +00006526 enum BasesToVisit {
6527 /// Visit all non-virtual (direct) bases.
6528 VisitNonVirtualBases,
6529 /// Visit all direct bases, virtual or not.
6530 VisitDirectBases,
6531 /// Visit all non-virtual bases, and all virtual bases if the class
6532 /// is not abstract.
6533 VisitPotentiallyConstructedBases,
6534 /// Visit all direct or virtual bases.
6535 VisitAllBases
6536 };
6537
6538 // Visit the bases and members of the class.
6539 bool visit(BasesToVisit Bases) {
6540 CXXRecordDecl *RD = MD->getParent();
6541
6542 if (Bases == VisitPotentiallyConstructedBases)
6543 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
6544
6545 for (auto &B : RD->bases())
6546 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
6547 getDerived().visitBase(&B))
6548 return true;
6549
6550 if (Bases == VisitAllBases)
6551 for (auto &B : RD->vbases())
6552 if (getDerived().visitBase(&B))
6553 return true;
6554
6555 for (auto *F : RD->fields())
6556 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
6557 getDerived().visitField(F))
6558 return true;
6559
6560 return false;
6561 }
Richard Smith8bae1be2017-02-24 02:07:20 +00006562};
6563}
6564
6565namespace {
6566struct SpecialMemberDeletionInfo
6567 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
Richard Smith852265f2012-03-30 20:53:28 +00006568 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00006569
Richard Smithd951a1d2012-02-18 02:02:13 +00006570 SourceLocation Loc;
6571
6572 bool AllFieldsAreConst;
6573
6574 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith80a47022016-06-29 01:10:27 +00006575 Sema::CXXSpecialMember CSM,
6576 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
Richard Smith8bae1be2017-02-24 02:07:20 +00006577 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
Richard Smith6f0e63e2017-02-24 21:18:47 +00006578 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
Richard Smithd951a1d2012-02-18 02:02:13 +00006579
6580 bool inUnion() const { return MD->getParent()->isUnion(); }
6581
Richard Smith80a47022016-06-29 01:10:27 +00006582 Sema::CXXSpecialMember getEffectiveCSM() {
6583 return ICI ? Sema::CXXInvalid : CSM;
6584 }
6585
Richard Smith6f0e63e2017-02-24 21:18:47 +00006586 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
6587 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
6588
Richard Smith852265f2012-03-30 20:53:28 +00006589 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00006590 bool shouldDeleteForField(FieldDecl *FD);
6591 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00006592
Richard Smithaf136f82012-07-18 03:51:16 +00006593 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6594 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00006595 bool shouldDeleteForSubobjectCall(Subobject Subobj,
Richard Smith8bae1be2017-02-24 02:07:20 +00006596 Sema::SpecialMemberOverloadResult SMOR,
Richard Smith852265f2012-03-30 20:53:28 +00006597 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00006598
6599 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00006600};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006601}
Richard Smithd951a1d2012-02-18 02:02:13 +00006602
John McCalld4274212012-04-09 20:53:23 +00006603/// Is the given special member inaccessible when used on the given
6604/// sub-object.
6605bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6606 CXXMethodDecl *target) {
6607 /// If we're operating on a base class, the object type is the
6608 /// type of this special member.
6609 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00006610 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00006611 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6612 objectTy = S.Context.getTypeDeclType(MD->getParent());
6613 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6614
6615 // If we're operating on a field, the object type is the type of the field.
6616 } else {
6617 objectTy = S.Context.getTypeDeclType(target->getParent());
6618 }
6619
6620 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6621}
6622
Richard Smith852265f2012-03-30 20:53:28 +00006623/// Check whether we should delete a special member due to the implicit
6624/// definition containing a call to a special member of a subobject.
6625bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
Richard Smith8bae1be2017-02-24 02:07:20 +00006626 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
Richard Smith852265f2012-03-30 20:53:28 +00006627 bool IsDtorCallInCtor) {
Richard Smith8bae1be2017-02-24 02:07:20 +00006628 CXXMethodDecl *Decl = SMOR.getMethod();
Richard Smith852265f2012-03-30 20:53:28 +00006629 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6630
6631 int DiagKind = -1;
6632
Richard Smith8bae1be2017-02-24 02:07:20 +00006633 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
Richard Smith852265f2012-03-30 20:53:28 +00006634 DiagKind = !Decl ? 0 : 1;
Richard Smith8bae1be2017-02-24 02:07:20 +00006635 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
Richard Smith852265f2012-03-30 20:53:28 +00006636 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00006637 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00006638 DiagKind = 3;
6639 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6640 !Decl->isTrivial()) {
6641 // A member of a union must have a trivial corresponding special member.
6642 // As a weird special case, a destructor call from a union's constructor
6643 // must be accessible and non-deleted, but need not be trivial. Such a
6644 // destructor is never actually called, but is semantically checked as
6645 // if it were.
6646 DiagKind = 4;
6647 }
6648
6649 if (DiagKind == -1)
6650 return false;
6651
6652 if (Diagnose) {
6653 if (Field) {
6654 S.Diag(Field->getLocation(),
6655 diag::note_deleted_special_member_class_subobject)
Richard Smith80a47022016-06-29 01:10:27 +00006656 << getEffectiveCSM() << MD->getParent() << /*IsField*/true
Richard Smith852265f2012-03-30 20:53:28 +00006657 << Field << DiagKind << IsDtorCallInCtor;
6658 } else {
6659 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6660 S.Diag(Base->getLocStart(),
6661 diag::note_deleted_special_member_class_subobject)
Richard Smith80a47022016-06-29 01:10:27 +00006662 << getEffectiveCSM() << MD->getParent() << /*IsField*/false
Richard Smith852265f2012-03-30 20:53:28 +00006663 << Base->getType() << DiagKind << IsDtorCallInCtor;
6664 }
6665
6666 if (DiagKind == 1)
6667 S.NoteDeletedFunction(Decl);
6668 // FIXME: Explain inaccessibility if DiagKind == 3.
6669 }
6670
6671 return true;
6672}
6673
Richard Smith921bd202012-02-26 09:11:52 +00006674/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00006675/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00006676bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00006677 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00006678 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00006679 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00006680
6681 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00006682 // -- any direct or virtual base class, or non-static data member with no
6683 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00006684 // either M has no default constructor or overload resolution as applied
6685 // to M's default constructor results in an ambiguity or in a function
6686 // that is deleted or inaccessible
6687 // C++11 [class.copy]p11, C++11 [class.copy]p23:
6688 // -- a direct or virtual base class B that cannot be copied/moved because
6689 // overload resolution, as applied to B's corresponding special member,
6690 // results in an ambiguity or a function that is deleted or inaccessible
6691 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00006692 // C++11 [class.dtor]p5:
6693 // -- any direct or virtual base class [...] has a type with a destructor
6694 // that is deleted or inaccessible
6695 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006696 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00006697 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6698 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006699 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00006700
Richard Smith852265f2012-03-30 20:53:28 +00006701 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6702 // -- any direct or virtual base class or non-static data member has a
6703 // type with a destructor that is deleted or inaccessible
6704 if (IsConstructor) {
Richard Smith8bae1be2017-02-24 02:07:20 +00006705 Sema::SpecialMemberOverloadResult SMOR =
Richard Smith852265f2012-03-30 20:53:28 +00006706 S.LookupSpecialMember(Class, Sema::CXXDestructor,
6707 false, false, false, false, false);
6708 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
6709 return true;
6710 }
6711
Richard Smith921bd202012-02-26 09:11:52 +00006712 return false;
6713}
6714
6715/// Check whether we should delete a special member function due to the class
6716/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00006717bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006718 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Serge Pavlov5c49e1a2015-12-28 19:40:14 +00006719 // If program is correct, BaseClass cannot be null, but if it is, the error
6720 // must be reported elsewhere.
Richard Smith80a47022016-06-29 01:10:27 +00006721 if (!BaseClass)
6722 return false;
6723 // If we have an inheriting constructor, check whether we're calling an
6724 // inherited constructor instead of a default constructor.
Richard Smith6f0e63e2017-02-24 21:18:47 +00006725 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
6726 if (auto *BaseCtor = SMOR.getMethod()) {
6727 // Note that we do not check access along this path; other than that,
6728 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
6729 // FIXME: Check that the base has a usable destructor! Sink this into
6730 // shouldDeleteForClassSubobject.
6731 if (BaseCtor->isDeleted() && Diagnose) {
6732 S.Diag(Base->getLocStart(),
6733 diag::note_deleted_special_member_class_subobject)
6734 << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6735 << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false;
6736 S.NoteDeletedFunction(BaseCtor);
Richard Smith80a47022016-06-29 01:10:27 +00006737 }
Richard Smith6f0e63e2017-02-24 21:18:47 +00006738 return BaseCtor->isDeleted();
Richard Smith80a47022016-06-29 01:10:27 +00006739 }
6740 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00006741}
6742
6743/// Check whether we should delete a special member function due to the class
6744/// having a particular non-static data member.
6745bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
6746 QualType FieldType = S.Context.getBaseElementType(FD->getType());
6747 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
6748
6749 if (CSM == Sema::CXXDefaultConstructor) {
6750 // For a default constructor, all references must be initialized in-class
6751 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00006752 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
6753 if (Diagnose)
6754 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smith80a47022016-06-29 01:10:27 +00006755 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00006756 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006757 }
Richard Smith619ecdc2012-02-27 06:07:25 +00006758 // C++11 [class.ctor]p5: any non-variant non-static data member of
6759 // const-qualified type (or array thereof) with no
6760 // brace-or-equal-initializer does not have a user-provided default
6761 // constructor.
6762 if (!inUnion() && FieldType.isConstQualified() &&
6763 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00006764 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
6765 if (Diagnose)
6766 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smith80a47022016-06-29 01:10:27 +00006767 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00006768 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006769 }
6770
6771 if (inUnion() && !FieldType.isConstQualified())
6772 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00006773 } else if (CSM == Sema::CXXCopyConstructor) {
6774 // For a copy constructor, data members must not be of rvalue reference
6775 // type.
Richard Smith852265f2012-03-30 20:53:28 +00006776 if (FieldType->isRValueReferenceType()) {
6777 if (Diagnose)
6778 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
6779 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00006780 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006781 }
Richard Smithd951a1d2012-02-18 02:02:13 +00006782 } else if (IsAssignment) {
6783 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00006784 if (FieldType->isReferenceType()) {
6785 if (Diagnose)
6786 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smith6f0e63e2017-02-24 21:18:47 +00006787 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00006788 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006789 }
6790 if (!FieldRecord && FieldType.isConstQualified()) {
6791 // C++11 [class.copy]p23:
6792 // -- a non-static data member of const non-class type (or array thereof)
6793 if (Diagnose)
6794 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smith6f0e63e2017-02-24 21:18:47 +00006795 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00006796 return true;
6797 }
Richard Smithd951a1d2012-02-18 02:02:13 +00006798 }
6799
6800 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00006801 // Some additional restrictions exist on the variant members.
6802 if (!inUnion() && FieldRecord->isUnion() &&
6803 FieldRecord->isAnonymousStructOrUnion()) {
6804 bool AllVariantFieldsAreConst = true;
6805
Richard Smith5704fe82012-03-29 19:00:10 +00006806 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006807 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00006808 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00006809
6810 if (!UnionFieldType.isConstQualified())
6811 AllVariantFieldsAreConst = false;
6812
Richard Smith921bd202012-02-26 09:11:52 +00006813 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
6814 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006815 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00006816 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00006817 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00006818 }
6819
6820 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00006821 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006822 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00006823 if (Diagnose)
6824 S.Diag(FieldRecord->getLocation(),
6825 diag::note_deleted_default_ctor_all_const)
Richard Smith80a47022016-06-29 01:10:27 +00006826 << !!ICI << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00006827 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006828 }
Richard Smithd951a1d2012-02-18 02:02:13 +00006829
Richard Smith5704fe82012-03-29 19:00:10 +00006830 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00006831 // This is technically non-conformant, but sanity demands it.
6832 return false;
6833 }
6834
Richard Smithaf136f82012-07-18 03:51:16 +00006835 if (shouldDeleteForClassSubobject(FieldRecord, FD,
6836 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00006837 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00006838 }
6839
6840 return false;
6841}
6842
6843/// C++11 [class.ctor] p5:
6844/// A defaulted default constructor for a class X is defined as deleted if
6845/// X is a union and all of its variant members are of const-qualified type.
6846bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00006847 // This is a silly definition, because it gives an empty union a deleted
6848 // default constructor. Don't do that.
Richard Smith5e052982016-11-08 01:07:26 +00006849 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
6850 bool AnyFields = false;
6851 for (auto *F : MD->getParent()->fields())
6852 if ((AnyFields = !F->isUnnamedBitfield()))
6853 break;
6854 if (!AnyFields)
6855 return false;
Richard Smith852265f2012-03-30 20:53:28 +00006856 if (Diagnose)
6857 S.Diag(MD->getParent()->getLocation(),
6858 diag::note_deleted_default_ctor_all_const)
Richard Smith80a47022016-06-29 01:10:27 +00006859 << !!ICI << MD->getParent() << /*not anonymous union*/0;
Richard Smith852265f2012-03-30 20:53:28 +00006860 return true;
6861 }
6862 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00006863}
6864
6865/// Determine whether a defaulted special member function should be defined as
6866/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
6867/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00006868bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
Richard Smith80a47022016-06-29 01:10:27 +00006869 InheritedConstructorInfo *ICI,
Richard Smith852265f2012-03-30 20:53:28 +00006870 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00006871 if (MD->isInvalidDecl())
6872 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00006873 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00006874 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006875 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00006876 return false;
6877
Richard Smithd951a1d2012-02-18 02:02:13 +00006878 // C++11 [expr.lambda.prim]p19:
6879 // The closure type associated with a lambda-expression has a
6880 // deleted (8.4.3) default constructor and a deleted copy
6881 // assignment operator.
6882 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00006883 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
6884 if (Diagnose)
6885 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00006886 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006887 }
6888
Richard Smith6f1e2c62012-04-02 20:59:25 +00006889 // For an anonymous struct or union, the copy and assignment special members
6890 // will never be used, so skip the check. For an anonymous union declared at
6891 // namespace scope, the constructor and destructor are used.
6892 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
6893 RD->isAnonymousStructOrUnion())
6894 return false;
6895
Richard Smith852265f2012-03-30 20:53:28 +00006896 // C++11 [class.copy]p7, p18:
6897 // If the class definition declares a move constructor or move assignment
6898 // operator, an implicitly declared copy constructor or copy assignment
6899 // operator is defined as deleted.
6900 if (MD->isImplicit() &&
6901 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006902 CXXMethodDecl *UserDeclaredMove = nullptr;
Richard Smith852265f2012-03-30 20:53:28 +00006903
Peter Collingbourne66bfcb32016-11-19 00:30:56 +00006904 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
6905 // deletion of the corresponding copy operation, not both copy operations.
6906 // MSVC 2015 has adopted the standards conforming behavior.
6907 bool DeletesOnlyMatchingCopy =
6908 getLangOpts().MSVCCompat &&
6909 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
6910
Richard Smith852265f2012-03-30 20:53:28 +00006911 if (RD->hasUserDeclaredMoveConstructor() &&
Peter Collingbourne66bfcb32016-11-19 00:30:56 +00006912 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00006913 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00006914
6915 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006916 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00006917 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006918 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00006919 break;
6920 }
6921 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006922 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00006923 } else if (RD->hasUserDeclaredMoveAssignment() &&
Peter Collingbourne66bfcb32016-11-19 00:30:56 +00006924 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00006925 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00006926
6927 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00006928 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00006929 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00006930 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00006931 break;
6932 }
6933 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006934 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00006935 }
6936
6937 if (UserDeclaredMove) {
6938 Diag(UserDeclaredMove->getLocation(),
6939 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00006940 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00006941 << UserDeclaredMove->isMoveAssignmentOperator();
6942 return true;
6943 }
6944 }
Alexis Huntd6da8762011-10-10 06:18:57 +00006945
Richard Smith6f1e2c62012-04-02 20:59:25 +00006946 // Do access control from the special member function
6947 ContextRAII MethodContext(*this, MD);
6948
Richard Smith921bd202012-02-26 09:11:52 +00006949 // C++11 [class.dtor]p5:
6950 // -- for a virtual destructor, lookup of the non-array deallocation function
6951 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00006952 if (CSM == CXXDestructor && MD->isVirtual()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006953 FunctionDecl *OperatorDelete = nullptr;
Richard Smith921bd202012-02-26 09:11:52 +00006954 DeclarationName Name =
6955 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6956 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smithb2f0f052016-10-10 18:54:32 +00006957 OperatorDelete, /*Diagnose*/false)) {
Richard Smith852265f2012-03-30 20:53:28 +00006958 if (Diagnose)
6959 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00006960 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006961 }
Richard Smith921bd202012-02-26 09:11:52 +00006962 }
6963
Richard Smith80a47022016-06-29 01:10:27 +00006964 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00006965
Richard Smithd1627032013-07-22 18:06:23 +00006966 // Per DR1611, do not consider virtual bases of constructors of abstract
Richard Smithdf054d32017-02-25 23:53:05 +00006967 // classes, since we are not going to construct them.
6968 // Per DR1658, do not consider virtual bases of destructors of abstract
6969 // classes either.
6970 // Per DR2180, for assignment operators we only assign (and thus only
6971 // consider) direct bases.
6972 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
6973 : SMI.VisitPotentiallyConstructedBases))
Richard Smith6f0e63e2017-02-24 21:18:47 +00006974 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00006975
Richard Smithd951a1d2012-02-18 02:02:13 +00006976 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00006977 return true;
6978
Eli Bendersky9a220fc2014-09-29 20:38:29 +00006979 if (getLangOpts().CUDA) {
6980 // We should delete the special member in CUDA mode if target inference
6981 // failed.
6982 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
6983 Diagnose);
6984 }
6985
Alexis Huntea6f0322011-05-11 22:34:38 +00006986 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006987}
6988
Richard Smith92f241f2012-12-08 02:53:02 +00006989/// Perform lookup for a special member of the specified kind, and determine
6990/// whether it is trivial. If the triviality can be determined without the
6991/// lookup, skip it. This is intended for use when determining whether a
6992/// special member of a containing object is trivial, and thus does not ever
6993/// perform overload resolution for default constructors.
6994///
6995/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
6996/// member that was most likely to be intended to be trivial, if any.
6997static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
6998 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00006999 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00007000 if (Selected)
Craig Topperc3ec1492014-05-26 06:22:03 +00007001 *Selected = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00007002
7003 switch (CSM) {
7004 case Sema::CXXInvalid:
7005 llvm_unreachable("not a special member");
7006
7007 case Sema::CXXDefaultConstructor:
7008 // C++11 [class.ctor]p5:
7009 // A default constructor is trivial if:
7010 // - all the [direct subobjects] have trivial default constructors
7011 //
7012 // Note, no overload resolution is performed in this case.
7013 if (RD->hasTrivialDefaultConstructor())
7014 return true;
7015
7016 if (Selected) {
7017 // If there's a default constructor which could have been trivial, dig it
7018 // out. Otherwise, if there's any user-provided default constructor, point
7019 // to that as an example of why there's not a trivial one.
Craig Topperc3ec1492014-05-26 06:22:03 +00007020 CXXConstructorDecl *DefCtor = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00007021 if (RD->needsImplicitDefaultConstructor())
7022 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00007023 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00007024 if (!CI->isDefaultConstructor())
7025 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00007026 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00007027 if (!DefCtor->isUserProvided())
7028 break;
7029 }
7030
7031 *Selected = DefCtor;
7032 }
7033
7034 return false;
7035
7036 case Sema::CXXDestructor:
7037 // C++11 [class.dtor]p5:
7038 // A destructor is trivial if:
7039 // - all the direct [subobjects] have trivial destructors
7040 if (RD->hasTrivialDestructor())
7041 return true;
7042
7043 if (Selected) {
7044 if (RD->needsImplicitDestructor())
7045 S.DeclareImplicitDestructor(RD);
7046 *Selected = RD->getDestructor();
7047 }
7048
7049 return false;
7050
7051 case Sema::CXXCopyConstructor:
7052 // C++11 [class.copy]p12:
7053 // A copy constructor is trivial if:
7054 // - the constructor selected to copy each direct [subobject] is trivial
7055 if (RD->hasTrivialCopyConstructor()) {
7056 if (Quals == Qualifiers::Const)
7057 // We must either select the trivial copy constructor or reach an
7058 // ambiguity; no need to actually perform overload resolution.
7059 return true;
7060 } else if (!Selected) {
7061 return false;
7062 }
7063 // In C++98, we are not supposed to perform overload resolution here, but we
7064 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
7065 // cases like B as having a non-trivial copy constructor:
7066 // struct A { template<typename T> A(T&); };
7067 // struct B { mutable A a; };
7068 goto NeedOverloadResolution;
7069
7070 case Sema::CXXCopyAssignment:
7071 // C++11 [class.copy]p25:
7072 // A copy assignment operator is trivial if:
7073 // - the assignment operator selected to copy each direct [subobject] is
7074 // trivial
7075 if (RD->hasTrivialCopyAssignment()) {
7076 if (Quals == Qualifiers::Const)
7077 return true;
7078 } else if (!Selected) {
7079 return false;
7080 }
7081 // In C++98, we are not supposed to perform overload resolution here, but we
7082 // treat that as a language defect.
7083 goto NeedOverloadResolution;
7084
7085 case Sema::CXXMoveConstructor:
7086 case Sema::CXXMoveAssignment:
7087 NeedOverloadResolution:
Richard Smith8bae1be2017-02-24 02:07:20 +00007088 Sema::SpecialMemberOverloadResult SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00007089 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00007090
7091 // The standard doesn't describe how to behave if the lookup is ambiguous.
7092 // We treat it as not making the member non-trivial, just like the standard
7093 // mandates for the default constructor. This should rarely matter, because
7094 // the member will also be deleted.
Richard Smith8bae1be2017-02-24 02:07:20 +00007095 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
Richard Smith92f241f2012-12-08 02:53:02 +00007096 return true;
7097
Richard Smith8bae1be2017-02-24 02:07:20 +00007098 if (!SMOR.getMethod()) {
7099 assert(SMOR.getKind() ==
Richard Smith92f241f2012-12-08 02:53:02 +00007100 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
7101 return false;
7102 }
7103
7104 // We deliberately don't check if we found a deleted special member. We're
7105 // not supposed to!
7106 if (Selected)
Richard Smith8bae1be2017-02-24 02:07:20 +00007107 *Selected = SMOR.getMethod();
7108 return SMOR.getMethod()->isTrivial();
Richard Smith92f241f2012-12-08 02:53:02 +00007109 }
7110
7111 llvm_unreachable("unknown special method kind");
7112}
7113
Benjamin Kramer3e350262013-02-15 12:30:38 +00007114static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00007115 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00007116 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00007117 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00007118
7119 // Look for constructor templates.
7120 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7121 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7122 if (CXXConstructorDecl *CD =
7123 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7124 return CD;
7125 }
7126
Craig Topperc3ec1492014-05-26 06:22:03 +00007127 return nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00007128}
7129
7130/// The kind of subobject we are checking for triviality. The values of this
7131/// enumeration are used in diagnostics.
7132enum TrivialSubobjectKind {
7133 /// The subobject is a base class.
7134 TSK_BaseClass,
7135 /// The subobject is a non-static data member.
7136 TSK_Field,
7137 /// The object is actually the complete object.
7138 TSK_CompleteObject
7139};
7140
7141/// Check whether the special member selected for a given type would be trivial.
7142static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00007143 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00007144 Sema::CXXSpecialMember CSM,
7145 TrivialSubobjectKind Kind,
7146 bool Diagnose) {
7147 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7148 if (!SubRD)
7149 return true;
7150
7151 CXXMethodDecl *Selected;
7152 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Craig Topperc3ec1492014-05-26 06:22:03 +00007153 ConstRHS, Diagnose ? &Selected : nullptr))
Richard Smith92f241f2012-12-08 02:53:02 +00007154 return true;
7155
7156 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00007157 if (ConstRHS)
7158 SubType.addConst();
7159
Richard Smith92f241f2012-12-08 02:53:02 +00007160 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7161 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7162 << Kind << SubType.getUnqualifiedType();
7163 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7164 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7165 } else if (!Selected)
7166 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7167 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7168 else if (Selected->isUserProvided()) {
7169 if (Kind == TSK_CompleteObject)
7170 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7171 << Kind << SubType.getUnqualifiedType() << CSM;
7172 else {
7173 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7174 << Kind << SubType.getUnqualifiedType() << CSM;
7175 S.Diag(Selected->getLocation(), diag::note_declared_at);
7176 }
7177 } else {
7178 if (Kind != TSK_CompleteObject)
7179 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7180 << Kind << SubType.getUnqualifiedType() << CSM;
7181
7182 // Explain why the defaulted or deleted special member isn't trivial.
7183 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
7184 }
7185 }
7186
7187 return false;
7188}
7189
7190/// Check whether the members of a class type allow a special member to be
7191/// trivial.
7192static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7193 Sema::CXXSpecialMember CSM,
7194 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007195 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00007196 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7197 continue;
7198
7199 QualType FieldType = S.Context.getBaseElementType(FI->getType());
7200
7201 // Pretend anonymous struct or union members are members of this class.
7202 if (FI->isAnonymousStructOrUnion()) {
7203 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7204 CSM, ConstArg, Diagnose))
7205 return false;
7206 continue;
7207 }
7208
7209 // C++11 [class.ctor]p5:
7210 // A default constructor is trivial if [...]
7211 // -- no non-static data member of its class has a
7212 // brace-or-equal-initializer
7213 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7214 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007215 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00007216 return false;
7217 }
7218
7219 // Objective C ARC 4.3.5:
7220 // [...] nontrivally ownership-qualified types are [...] not trivially
7221 // default constructible, copy constructible, move constructible, copy
7222 // assignable, move assignable, or destructible [...]
Brian Kelley762f9282017-03-29 18:16:38 +00007223 if (FieldType.hasNonTrivialObjCLifetime()) {
Richard Smith92f241f2012-12-08 02:53:02 +00007224 if (Diagnose)
7225 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7226 << RD << FieldType.getObjCLifetime();
7227 return false;
7228 }
7229
Richard Smith41c35d62013-11-27 03:39:20 +00007230 bool ConstRHS = ConstArg && !FI->isMutable();
7231 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7232 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00007233 return false;
7234 }
7235
7236 return true;
7237}
7238
7239/// Diagnose why the specified class does not have a trivial special member of
7240/// the given kind.
7241void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7242 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00007243
Richard Smith41c35d62013-11-27 03:39:20 +00007244 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7245 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00007246 TSK_CompleteObject, /*Diagnose*/true);
7247}
7248
7249/// Determine whether a defaulted or deleted special member function is trivial,
7250/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7251/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7252bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7253 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00007254 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7255
7256 CXXRecordDecl *RD = MD->getParent();
7257
7258 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00007259
Richard Smith2002bfe2013-11-04 02:02:27 +00007260 // C++11 [class.copy]p12, p25: [DR1593]
7261 // A [special member] is trivial if [...] its parameter-type-list is
7262 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00007263 switch (CSM) {
7264 case CXXDefaultConstructor:
7265 case CXXDestructor:
7266 // Trivial default constructors and destructors cannot have parameters.
7267 break;
7268
7269 case CXXCopyConstructor:
7270 case CXXCopyAssignment: {
7271 // Trivial copy operations always have const, non-volatile parameter types.
7272 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00007273 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00007274 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7275 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7276 if (Diagnose)
7277 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7278 << Param0->getSourceRange() << Param0->getType()
7279 << Context.getLValueReferenceType(
7280 Context.getRecordType(RD).withConst());
7281 return false;
7282 }
7283 break;
7284 }
7285
7286 case CXXMoveConstructor:
7287 case CXXMoveAssignment: {
7288 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00007289 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00007290 const RValueReferenceType *RT =
7291 Param0->getType()->getAs<RValueReferenceType>();
7292 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7293 if (Diagnose)
7294 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7295 << Param0->getSourceRange() << Param0->getType()
7296 << Context.getRValueReferenceType(Context.getRecordType(RD));
7297 return false;
7298 }
7299 break;
7300 }
7301
7302 case CXXInvalid:
7303 llvm_unreachable("not a special member");
7304 }
7305
Richard Smith92f241f2012-12-08 02:53:02 +00007306 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7307 if (Diagnose)
7308 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7309 diag::note_nontrivial_default_arg)
7310 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7311 return false;
7312 }
7313 if (MD->isVariadic()) {
7314 if (Diagnose)
7315 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7316 return false;
7317 }
7318
7319 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7320 // A copy/move [constructor or assignment operator] is trivial if
7321 // -- the [member] selected to copy/move each direct base class subobject
7322 // is trivial
7323 //
7324 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7325 // A [default constructor or destructor] is trivial if
7326 // -- all the direct base classes have trivial [default constructors or
7327 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00007328 for (const auto &BI : RD->bases())
7329 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00007330 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00007331 return false;
7332
7333 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7334 // A copy/move [constructor or assignment operator] for a class X is
7335 // trivial if
7336 // -- for each non-static data member of X that is of class type (or array
7337 // thereof), the constructor selected to copy/move that member is
7338 // trivial
7339 //
7340 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7341 // A [default constructor or destructor] is trivial if
7342 // -- for all of the non-static data members of its class that are of class
7343 // type (or array thereof), each such class has a trivial [default
7344 // constructor or destructor]
7345 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
7346 return false;
7347
7348 // C++11 [class.dtor]p5:
7349 // A destructor is trivial if [...]
7350 // -- the destructor is not virtual
7351 if (CSM == CXXDestructor && MD->isVirtual()) {
7352 if (Diagnose)
7353 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7354 return false;
7355 }
7356
7357 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7358 // A [special member] for class X is trivial if [...]
7359 // -- class X has no virtual functions and no virtual base classes
7360 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7361 if (!Diagnose)
7362 return false;
7363
7364 if (RD->getNumVBases()) {
7365 // Check for virtual bases. We already know that the corresponding
7366 // member in all bases is trivial, so vbases must all be direct.
7367 CXXBaseSpecifier &BS = *RD->vbases_begin();
7368 assert(BS.isVirtual());
7369 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
7370 return false;
7371 }
7372
7373 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00007374 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00007375 if (MI->isVirtual()) {
7376 SourceLocation MLoc = MI->getLocStart();
7377 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7378 return false;
7379 }
7380 }
7381
7382 llvm_unreachable("dynamic class with no vbases and no virtual functions");
7383 }
7384
7385 // Looks like it's trivial!
7386 return true;
7387}
7388
Benjamin Kramer024e6192011-03-04 13:12:48 +00007389namespace {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007390struct FindHiddenVirtualMethod {
7391 Sema *S;
7392 CXXMethodDecl *Method;
7393 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7394 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007395
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007396private:
7397 /// Check whether any most overriden method from MD in Methods
7398 static bool CheckMostOverridenMethods(
7399 const CXXMethodDecl *MD,
7400 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7401 if (MD->size_overridden_methods() == 0)
7402 return Methods.count(MD->getCanonicalDecl());
7403 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7404 E = MD->end_overridden_methods();
7405 I != E; ++I)
7406 if (CheckMostOverridenMethods(*I, Methods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007407 return true;
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007408 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007409 }
7410
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007411public:
7412 /// Member lookup function that determines whether a given C++
7413 /// method overloads virtual methods in a base class without overriding any,
7414 /// to be used with CXXRecordDecl::lookupInBases().
7415 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7416 RecordDecl *BaseRecord =
7417 Specifier->getType()->getAs<RecordType>()->getDecl();
7418
7419 DeclarationName Name = Method->getDeclName();
7420 assert(Name.getNameKind() == DeclarationName::Identifier);
7421
7422 bool foundSameNameMethod = false;
7423 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7424 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7425 Path.Decls = Path.Decls.slice(1)) {
7426 NamedDecl *D = Path.Decls.front();
7427 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7428 MD = MD->getCanonicalDecl();
7429 foundSameNameMethod = true;
7430 // Interested only in hidden virtual methods.
7431 if (!MD->isVirtual())
7432 continue;
7433 // If the method we are checking overrides a method from its base
7434 // don't warn about the other overloaded methods. Clang deviates from
7435 // GCC by only diagnosing overloads of inherited virtual functions that
7436 // do not override any other virtual functions in the base. GCC's
7437 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7438 // function from a base class. These cases may be better served by a
7439 // warning (not specific to virtual functions) on call sites when the
7440 // call would select a different function from the base class, were it
7441 // visible.
7442 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7443 if (!S->IsOverload(Method, MD, false))
7444 return true;
7445 // Collect the overload only if its hidden.
7446 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7447 overloadedMethods.push_back(MD);
7448 }
7449 }
7450
7451 if (foundSameNameMethod)
7452 OverloadedMethods.append(overloadedMethods.begin(),
7453 overloadedMethods.end());
7454 return foundSameNameMethod;
7455 }
7456};
7457} // end anonymous namespace
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007458
David Blaikie282c92a2012-10-19 00:53:08 +00007459/// \brief Add the most overriden methods from MD to Methods
7460static void AddMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00007461 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00007462 if (MD->size_overridden_methods() == 0)
7463 Methods.insert(MD->getCanonicalDecl());
7464 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7465 E = MD->end_overridden_methods();
7466 I != E; ++I)
7467 AddMostOverridenMethods(*I, Methods);
7468}
7469
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007470/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007471/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007472void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7473 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00007474 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007475 return;
7476
7477 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7478 /*bool RecordPaths=*/false,
7479 /*bool DetectVirtual=*/false);
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007480 FindHiddenVirtualMethod FHVM;
7481 FHVM.Method = MD;
7482 FHVM.S = this;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007483
7484 // Keep the base methods that were overriden or introduced in the subclass
7485 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007486 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00007487 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7488 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7489 NamedDecl *ND = *I;
7490 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00007491 ND = shad->getTargetDecl();
7492 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007493 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007494 }
7495
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007496 if (DC->lookupInBases(FHVM, Paths))
7497 OverloadedMethods = FHVM.OverloadedMethods;
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007498}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007499
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007500void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7501 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7502 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7503 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7504 PartialDiagnostic PD = PDiag(
7505 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7506 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7507 Diag(overloadedMD->getLocation(), PD);
7508 }
7509}
7510
7511/// \brief Diagnose methods which overload virtual methods in a base class
7512/// without overriding any.
7513void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7514 if (MD->isInvalidDecl())
7515 return;
7516
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007517 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007518 return;
7519
7520 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7521 FindHiddenVirtualMethods(MD, OverloadedMethods);
7522 if (!OverloadedMethods.empty()) {
7523 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7524 << MD << (OverloadedMethods.size() > 1);
7525
7526 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007527 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00007528}
7529
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00007530void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00007531 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00007532 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00007533 SourceLocation RBrac,
7534 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00007535 if (!TagDecl)
7536 return;
Mike Stump11289f42009-09-09 15:08:12 +00007537
Douglas Gregorc9f9b862009-05-11 19:58:34 +00007538 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00007539
Rafael Espindola06e1b132012-07-12 04:32:30 +00007540 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
7541 if (l->getKind() != AttributeList::AT_Visibility)
7542 continue;
7543 l->setInvalid();
7544 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
7545 l->getName();
7546 }
7547
David Blaikie751c5582011-09-22 02:58:26 +00007548 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00007549 // strict aliasing violation!
7550 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00007551 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00007552
Richard Smith96cd6712017-08-16 01:49:53 +00007553 CheckCompletedCXXClass(dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00007554}
7555
Douglas Gregor05379422008-11-03 17:51:48 +00007556/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7557/// special functions, such as the default constructor, copy
7558/// constructor, or destructor, to the given C++ class (C++
7559/// [special]p1). This routine can only be executed just before the
7560/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00007561void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Richard Smith5179eb72016-06-28 19:03:57 +00007562 if (ClassDecl->needsImplicitDefaultConstructor()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00007563 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00007564
Richard Smith5179eb72016-06-28 19:03:57 +00007565 if (ClassDecl->hasInheritedConstructor())
7566 DeclareImplicitDefaultConstructor(ClassDecl);
7567 }
Richard Smith12e79312016-05-13 06:47:56 +00007568
Richard Smitha87b7662016-05-13 18:48:05 +00007569 if (ClassDecl->needsImplicitCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00007570 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00007571
Richard Smith6b02d462012-12-08 08:32:28 +00007572 // If the properties or semantics of the copy constructor couldn't be
7573 // determined while the class was being declared, force a declaration
7574 // of it now.
Richard Smith12e79312016-05-13 06:47:56 +00007575 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7576 ClassDecl->hasInheritedConstructor())
Richard Smith6b02d462012-12-08 08:32:28 +00007577 DeclareImplicitCopyConstructor(ClassDecl);
Peter Collingbourne120eb542016-11-22 00:21:43 +00007578 // For the MS ABI we need to know whether the copy ctor is deleted. A
7579 // prerequisite for deleting the implicit copy ctor is that the class has a
7580 // move ctor or move assignment that is either user-declared or whose
7581 // semantics are inherited from a subobject. FIXME: We should provide a more
7582 // direct way for CodeGen to ask whether the constructor was deleted.
7583 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7584 (ClassDecl->hasUserDeclaredMoveConstructor() ||
7585 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7586 ClassDecl->hasUserDeclaredMoveAssignment() ||
7587 ClassDecl->needsOverloadResolutionForMoveAssignment()))
7588 DeclareImplicitCopyConstructor(ClassDecl);
Richard Smith6b02d462012-12-08 08:32:28 +00007589 }
7590
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007591 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00007592 ++ASTContext::NumImplicitMoveConstructors;
7593
Richard Smith12e79312016-05-13 06:47:56 +00007594 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7595 ClassDecl->hasInheritedConstructor())
Richard Smith6b02d462012-12-08 08:32:28 +00007596 DeclareImplicitMoveConstructor(ClassDecl);
7597 }
7598
Richard Smitha87b7662016-05-13 18:48:05 +00007599 if (ClassDecl->needsImplicitCopyAssignment()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007600 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00007601
7602 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007603 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00007604 // it shows up in the right place in the vtable and that we diagnose
7605 // problems with the implicit exception specification.
7606 if (ClassDecl->isDynamicClass() ||
Richard Smith12e79312016-05-13 06:47:56 +00007607 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7608 ClassDecl->hasInheritedAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007609 DeclareImplicitCopyAssignment(ClassDecl);
7610 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00007611
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007612 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00007613 ++ASTContext::NumImplicitMoveAssignmentOperators;
7614
7615 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00007616 if (ClassDecl->isDynamicClass() ||
Richard Smith12e79312016-05-13 06:47:56 +00007617 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7618 ClassDecl->hasInheritedAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00007619 DeclareImplicitMoveAssignment(ClassDecl);
7620 }
7621
Richard Smitha87b7662016-05-13 18:48:05 +00007622 if (ClassDecl->needsImplicitDestructor()) {
Douglas Gregor7454c562010-07-02 20:37:36 +00007623 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00007624
7625 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00007626 // have to declare the destructor immediately. This ensures that, e.g., it
7627 // shows up in the right place in the vtable and that we diagnose problems
7628 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00007629 if (ClassDecl->isDynamicClass() ||
7630 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00007631 DeclareImplicitDestructor(ClassDecl);
7632 }
Douglas Gregor05379422008-11-03 17:51:48 +00007633}
7634
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00007635unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Francois Pichet1c229c02011-04-22 22:18:13 +00007636 if (!D)
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00007637 return 0;
Francois Pichet1c229c02011-04-22 22:18:13 +00007638
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00007639 // The order of template parameters is not important here. All names
7640 // get added to the same scope.
7641 SmallVector<TemplateParameterList *, 4> ParameterLists;
7642
7643 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7644 D = TD->getTemplatedDecl();
7645
7646 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
7647 ParameterLists.push_back(PSD->getTemplateParameters());
7648
7649 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
7650 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
7651 ParameterLists.push_back(DD->getTemplateParameterList(i));
7652
7653 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7654 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
7655 ParameterLists.push_back(FTD->getTemplateParameters());
7656 }
7657 }
7658
7659 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7660 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
7661 ParameterLists.push_back(TD->getTemplateParameterList(i));
7662
7663 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
7664 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
7665 ParameterLists.push_back(CTD->getTemplateParameters());
7666 }
7667 }
7668
7669 unsigned Count = 0;
7670 for (TemplateParameterList *Params : ParameterLists) {
7671 if (Params->size() > 0)
7672 // Ignore explicit specializations; they don't contribute to the template
7673 // depth.
7674 ++Count;
7675 for (NamedDecl *Param : *Params) {
7676 if (Param->getDeclName()) {
7677 S->AddDecl(Param);
7678 IdResolver.AddDecl(Param);
Francois Pichet1c229c02011-04-22 22:18:13 +00007679 }
7680 }
7681 }
Francois Pichet1c229c02011-04-22 22:18:13 +00007682
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00007683 return Count;
Douglas Gregore44a2ad2009-05-27 23:11:45 +00007684}
7685
John McCall48871652010-08-21 09:40:31 +00007686void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00007687 if (!RecordD) return;
7688 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00007689 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00007690 PushDeclContext(S, Record);
7691}
7692
John McCall48871652010-08-21 09:40:31 +00007693void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00007694 if (!RecordD) return;
7695 PopDeclContext();
7696}
7697
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007698/// This is used to implement the constant expression evaluation part of the
7699/// attribute enable_if extension. There is nothing in standard C++ which would
7700/// require reentering parameters.
7701void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
7702 if (!Param)
7703 return;
7704
7705 S->AddDecl(Param);
7706 if (Param->getDeclName())
7707 IdResolver.AddDecl(Param);
7708}
7709
Douglas Gregor4d87df52008-12-16 21:30:33 +00007710/// ActOnStartDelayedCXXMethodDeclaration - We have completed
7711/// parsing a top-level (non-nested) C++ class, and we are now
7712/// parsing those parts of the given Method declaration that could
7713/// not be parsed earlier (C++ [class.mem]p2), such as default
7714/// arguments. This action should enter the scope of the given
7715/// Method declaration as if we had just parsed the qualified method
7716/// name. However, it should not bring the parameters into scope;
7717/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00007718void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00007719}
7720
7721/// ActOnDelayedCXXMethodParameter - We've already started a delayed
7722/// C++ method declaration. We're (re-)introducing the given
7723/// function parameter into scope for use in parsing later parts of
7724/// the method declaration. For example, we could see an
7725/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00007726void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00007727 if (!ParamD)
7728 return;
Mike Stump11289f42009-09-09 15:08:12 +00007729
John McCall48871652010-08-21 09:40:31 +00007730 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00007731
7732 // If this parameter has an unparsed default argument, clear it out
7733 // to make way for the parsed default argument.
7734 if (Param->hasUnparsedDefaultArg())
Craig Topperc3ec1492014-05-26 06:22:03 +00007735 Param->setDefaultArg(nullptr);
Douglas Gregor58354032008-12-24 00:01:03 +00007736
John McCall48871652010-08-21 09:40:31 +00007737 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00007738 if (Param->getDeclName())
7739 IdResolver.AddDecl(Param);
7740}
7741
7742/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
7743/// processing the delayed method declaration for Method. The method
7744/// declaration is now considered finished. There may be a separate
7745/// ActOnStartOfFunctionDef action later (not necessarily
7746/// immediately!) for this method, if it was also defined inside the
7747/// class body.
John McCall48871652010-08-21 09:40:31 +00007748void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00007749 if (!MethodD)
7750 return;
Mike Stump11289f42009-09-09 15:08:12 +00007751
Douglas Gregorc8c277a2009-08-24 11:57:43 +00007752 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00007753
John McCall48871652010-08-21 09:40:31 +00007754 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00007755
7756 // Now that we have our default arguments, check the constructor
7757 // again. It could produce additional diagnostics or affect whether
7758 // the class has implicitly-declared destructors, among other
7759 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007760 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
7761 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00007762
7763 // Check the default arguments, which we may have added.
7764 if (!Method->isInvalidDecl())
7765 CheckCXXDefaultArguments(Method);
7766}
7767
Douglas Gregor831c93f2008-11-05 20:51:48 +00007768/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00007769/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00007770/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00007771/// emit diagnostics and set the invalid bit to true. In any case, the type
7772/// will be updated to reflect a well-formed type for the constructor and
7773/// returned.
7774QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00007775 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007776 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007777
7778 // C++ [class.ctor]p3:
7779 // A constructor shall not be virtual (10.3) or static (9.4). A
7780 // constructor can be invoked for a const, volatile or const
7781 // volatile object. A constructor shall not be declared const,
7782 // volatile, or const volatile (9.3.2).
7783 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00007784 if (!D.isInvalidType())
7785 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7786 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
7787 << SourceRange(D.getIdentifierLoc());
7788 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007789 }
John McCall8e7d6562010-08-26 03:08:43 +00007790 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00007791 if (!D.isInvalidType())
7792 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7793 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7794 << SourceRange(D.getIdentifierLoc());
7795 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00007796 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00007797 }
Mike Stump11289f42009-09-09 15:08:12 +00007798
David Majnemer03f705f2014-07-08 18:18:04 +00007799 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7800 diagnoseIgnoredQualifiers(
7801 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
7802 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
7803 D.getDeclSpec().getRestrictSpecLoc(),
7804 D.getDeclSpec().getAtomicSpecLoc());
7805 D.setInvalidType();
7806 }
7807
Abramo Bagnara924a8f32010-12-10 16:29:40 +00007808 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00007809 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00007810 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00007811 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7812 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00007813 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00007814 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7815 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00007816 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00007817 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7818 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00007819 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007820 }
Mike Stump11289f42009-09-09 15:08:12 +00007821
Douglas Gregordb9d6642011-01-26 05:01:58 +00007822 // C++0x [class.ctor]p4:
7823 // A constructor shall not be declared with a ref-qualifier.
7824 if (FTI.hasRefQualifier()) {
7825 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
Erich Keanebb863642017-09-20 22:28:24 +00007826 << FTI.RefQualifierIsLValueRef
Douglas Gregordb9d6642011-01-26 05:01:58 +00007827 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7828 D.setInvalidType();
7829 }
Erich Keanebb863642017-09-20 22:28:24 +00007830
Douglas Gregor831c93f2008-11-05 20:51:48 +00007831 // Rebuild the function type "R" without any type qualifiers (in
7832 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00007833 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00007834 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00007835 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00007836 return R;
7837
7838 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7839 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00007840 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00007841
7842 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00007843}
7844
Douglas Gregor4d87df52008-12-16 21:30:33 +00007845/// CheckConstructor - Checks a fully-formed constructor for
7846/// well-formedness, issuing any diagnostics required. Returns true if
7847/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007848void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00007849 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00007850 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
7851 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007852 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00007853
7854 // C++ [class.copy]p3:
7855 // A declaration of a constructor for a class X is ill-formed if
7856 // its first parameter is of type (optionally cv-qualified) X and
7857 // either there are no other parameters or else all other
7858 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00007859 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00007860 ((Constructor->getNumParams() == 1) ||
7861 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00007862 Constructor->getParamDecl(1)->hasDefaultArg())) &&
7863 Constructor->getTemplateSpecializationKind()
7864 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00007865 QualType ParamType = Constructor->getParamDecl(0)->getType();
7866 QualType ClassTy = Context.getTagDeclType(ClassDecl);
7867 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00007868 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Erich Keanebb863642017-09-20 22:28:24 +00007869 const char *ConstRef
7870 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
Douglas Gregorfd42e952010-05-27 21:28:21 +00007871 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00007872 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00007873 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00007874
7875 // FIXME: Rather that making the constructor invalid, we should endeavor
7876 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007877 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00007878 }
7879 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00007880}
7881
John McCalldeb646e2010-08-04 01:04:25 +00007882/// CheckDestructor - Checks a fully-formed destructor definition for
7883/// well-formedness, issuing any diagnostics required. Returns true
7884/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00007885bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00007886 CXXRecordDecl *RD = Destructor->getParent();
Erich Keanebb863642017-09-20 22:28:24 +00007887
Peter Collingbourneb289fe62013-05-20 14:12:25 +00007888 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00007889 SourceLocation Loc;
Erich Keanebb863642017-09-20 22:28:24 +00007890
Anders Carlsson2a50e952009-11-15 22:49:34 +00007891 if (!Destructor->isImplicit())
7892 Loc = Destructor->getLocation();
7893 else
7894 Loc = RD->getLocation();
Erich Keanebb863642017-09-20 22:28:24 +00007895
Anders Carlsson2a50e952009-11-15 22:49:34 +00007896 // If we have a virtual destructor, look up the deallocation function
Richard Smithb2f0f052016-10-10 18:54:32 +00007897 if (FunctionDecl *OperatorDelete =
7898 FindDeallocationFunctionForDestructor(Loc, RD)) {
7899 MarkFunctionReferenced(Loc, OperatorDelete);
7900 Destructor->setOperatorDelete(OperatorDelete);
7901 }
Anders Carlsson2a50e952009-11-15 22:49:34 +00007902 }
Erich Keanebb863642017-09-20 22:28:24 +00007903
Anders Carlsson26a807d2009-11-30 21:24:50 +00007904 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00007905}
7906
Douglas Gregor831c93f2008-11-05 20:51:48 +00007907/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
7908/// the well-formednes of the destructor declarator @p D with type @p
7909/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00007910/// emit diagnostics and set the declarator to invalid. Even if this happens,
7911/// will be updated to reflect a well-formed type for the destructor and
7912/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00007913QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00007914 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007915 // C++ [class.dtor]p1:
7916 // [...] A typedef-name that names a class is a class-name
7917 // (7.1.3); however, a typedef-name that names a class shall not
7918 // be used as the identifier in the declarator for a destructor
7919 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00007920 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00007921 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00007922 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00007923 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00007924 else if (const TemplateSpecializationType *TST =
7925 DeclaratorType->getAs<TemplateSpecializationType>())
7926 if (TST->isTypeAlias())
7927 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
7928 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00007929
7930 // C++ [class.dtor]p2:
7931 // A destructor is used to destroy objects of its class type. A
7932 // destructor takes no parameters, and no return type can be
7933 // specified for it (not even void). The address of a destructor
7934 // shall not be taken. A destructor shall not be static. A
7935 // destructor can be invoked for a const, volatile or const
7936 // volatile object. A destructor shall not be declared const,
7937 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00007938 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00007939 if (!D.isInvalidType())
7940 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
7941 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00007942 << SourceRange(D.getIdentifierLoc())
7943 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
Erich Keanebb863642017-09-20 22:28:24 +00007944
John McCall8e7d6562010-08-26 03:08:43 +00007945 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00007946 }
David Majnemer03f705f2014-07-08 18:18:04 +00007947 if (!D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007948 // Destructors don't have return types, but the parser will
7949 // happily parse something like:
7950 //
7951 // class X {
7952 // float ~X();
7953 // };
7954 //
7955 // The return type will be eliminated later.
David Majnemer03f705f2014-07-08 18:18:04 +00007956 if (D.getDeclSpec().hasTypeSpecifier())
7957 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
7958 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7959 << SourceRange(D.getIdentifierLoc());
7960 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7961 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
7962 SourceLocation(),
7963 D.getDeclSpec().getConstSpecLoc(),
7964 D.getDeclSpec().getVolatileSpecLoc(),
7965 D.getDeclSpec().getRestrictSpecLoc(),
7966 D.getDeclSpec().getAtomicSpecLoc());
7967 D.setInvalidType();
7968 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00007969 }
Mike Stump11289f42009-09-09 15:08:12 +00007970
Abramo Bagnara924a8f32010-12-10 16:29:40 +00007971 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00007972 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00007973 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00007974 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7975 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00007976 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00007977 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7978 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00007979 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00007980 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7981 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00007982 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007983 }
7984
Douglas Gregordb9d6642011-01-26 05:01:58 +00007985 // C++0x [class.dtor]p2:
7986 // A destructor shall not be declared with a ref-qualifier.
7987 if (FTI.hasRefQualifier()) {
7988 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
7989 << FTI.RefQualifierIsLValueRef
7990 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7991 D.setInvalidType();
7992 }
Erich Keanebb863642017-09-20 22:28:24 +00007993
Douglas Gregor831c93f2008-11-05 20:51:48 +00007994 // Make sure we don't have any parameters.
Alp Toker4284c6e2014-05-11 16:05:55 +00007995 if (FTIHasNonVoidParameters(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007996 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
7997
7998 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00007999 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00008000 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00008001 }
8002
Mike Stump11289f42009-09-09 15:08:12 +00008003 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00008004 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00008005 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00008006 D.setInvalidType();
8007 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00008008
8009 // Rebuild the function type "R" without any type qualifiers or
8010 // parameters (in case any of the errors above fired) and with
8011 // "void" as the return type, since destructors don't have return
Erich Keanebb863642017-09-20 22:28:24 +00008012 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00008013 if (!D.isInvalidType())
8014 return R;
8015
Douglas Gregor95755162010-07-01 05:10:53 +00008016 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00008017 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8018 EPI.Variadic = false;
8019 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00008020 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008021 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00008022}
8023
Craig Toppere335f252015-10-04 04:53:55 +00008024static void extendLeft(SourceRange &R, SourceRange Before) {
Richard Smitha865a162014-12-19 02:07:47 +00008025 if (Before.isInvalid())
8026 return;
8027 R.setBegin(Before.getBegin());
8028 if (R.getEnd().isInvalid())
8029 R.setEnd(Before.getEnd());
8030}
8031
Craig Toppere335f252015-10-04 04:53:55 +00008032static void extendRight(SourceRange &R, SourceRange After) {
Richard Smitha865a162014-12-19 02:07:47 +00008033 if (After.isInvalid())
8034 return;
8035 if (R.getBegin().isInvalid())
8036 R.setBegin(After.getBegin());
8037 R.setEnd(After.getEnd());
8038}
8039
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008040/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
8041/// well-formednes of the conversion function declarator @p D with
8042/// type @p R. If there are any errors in the declarator, this routine
8043/// will emit diagnostics and return true. Otherwise, it will return
8044/// false. Either way, the type @p R will be updated to reflect a
8045/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00008046void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00008047 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008048 // C++ [class.conv.fct]p1:
8049 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00008050 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00008051 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00008052 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00008053 if (!D.isInvalidType())
8054 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00008055 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8056 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00008057 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00008058 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008059 }
John McCall212fa2e2010-04-13 00:04:31 +00008060
Richard Smitha865a162014-12-19 02:07:47 +00008061 TypeSourceInfo *ConvTSI = nullptr;
8062 QualType ConvType =
8063 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
John McCall212fa2e2010-04-13 00:04:31 +00008064
Chris Lattnerb41df4f2009-04-25 08:35:12 +00008065 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008066 // Conversion functions don't have return types, but the parser will
8067 // happily parse something like:
8068 //
8069 // class X {
8070 // float operator bool();
8071 // };
8072 //
8073 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00008074 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8075 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8076 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00008077 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008078 }
8079
John McCall212fa2e2010-04-13 00:04:31 +00008080 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8081
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008082 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00008083 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008084 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8085
8086 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00008087 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00008088 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00008089 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008090 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00008091 D.setInvalidType();
8092 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008093
John McCall212fa2e2010-04-13 00:04:31 +00008094 // Diagnose "&operator bool()" and other such nonsense. This
8095 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00008096 if (Proto->getReturnType() != ConvType) {
Richard Smitha865a162014-12-19 02:07:47 +00008097 bool NeedsTypedef = false;
8098 SourceRange Before, After;
8099
8100 // Walk the chunks and extract information on them for our diagnostic.
8101 bool PastFunctionChunk = false;
8102 for (auto &Chunk : D.type_objects()) {
8103 switch (Chunk.Kind) {
8104 case DeclaratorChunk::Function:
8105 if (!PastFunctionChunk) {
8106 if (Chunk.Fun.HasTrailingReturnType) {
8107 TypeSourceInfo *TRT = nullptr;
8108 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8109 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8110 }
8111 PastFunctionChunk = true;
8112 break;
8113 }
8114 // Fall through.
8115 case DeclaratorChunk::Array:
8116 NeedsTypedef = true;
8117 extendRight(After, Chunk.getSourceRange());
8118 break;
8119
8120 case DeclaratorChunk::Pointer:
8121 case DeclaratorChunk::BlockPointer:
8122 case DeclaratorChunk::Reference:
8123 case DeclaratorChunk::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00008124 case DeclaratorChunk::Pipe:
Richard Smitha865a162014-12-19 02:07:47 +00008125 extendLeft(Before, Chunk.getSourceRange());
8126 break;
8127
8128 case DeclaratorChunk::Paren:
8129 extendLeft(Before, Chunk.Loc);
8130 extendRight(After, Chunk.EndLoc);
8131 break;
8132 }
8133 }
8134
8135 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8136 After.isValid() ? After.getBegin() :
8137 D.getIdentifierLoc();
8138 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8139 DB << Before << After;
8140
8141 if (!NeedsTypedef) {
8142 DB << /*don't need a typedef*/0;
8143
8144 // If we can provide a correct fix-it hint, do so.
8145 if (After.isInvalid() && ConvTSI) {
8146 SourceLocation InsertLoc =
Craig Topper07fa1762015-11-15 02:31:46 +00008147 getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
Richard Smitha865a162014-12-19 02:07:47 +00008148 DB << FixItHint::CreateInsertion(InsertLoc, " ")
8149 << FixItHint::CreateInsertionFromRange(
8150 InsertLoc, CharSourceRange::getTokenRange(Before))
8151 << FixItHint::CreateRemoval(Before);
8152 }
8153 } else if (!Proto->getReturnType()->isDependentType()) {
8154 DB << /*typedef*/1 << Proto->getReturnType();
8155 } else if (getLangOpts().CPlusPlus11) {
8156 DB << /*alias template*/2 << Proto->getReturnType();
8157 } else {
8158 DB << /*might not be fixable*/3;
8159 }
8160
8161 // Recover by incorporating the other type chunks into the result type.
8162 // Note, this does *not* change the name of the function. This is compatible
8163 // with the GCC extension:
8164 // struct S { &operator int(); } s;
8165 // int &r = s.operator int(); // ok in GCC
8166 // S::operator int&() {} // error in GCC, function name is 'operator int'.
Alp Toker314cc812014-01-25 16:55:45 +00008167 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00008168 }
8169
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008170 // C++ [class.conv.fct]p4:
8171 // The conversion-type-id shall not represent a function type nor
8172 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008173 if (ConvType->isArrayType()) {
8174 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8175 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00008176 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008177 } else if (ConvType->isFunctionType()) {
8178 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8179 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00008180 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008181 }
8182
8183 // Rebuild the function type "R" without any parameters (in case any
8184 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00008185 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00008186 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008187 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008188
Douglas Gregor5fb53972009-01-14 15:45:31 +00008189 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00008190 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00008191 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008192 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008193 diag::warn_cxx98_compat_explicit_conversion_functions :
8194 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00008195 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008196}
8197
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008198/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8199/// the declaration of the given C++ conversion function. This routine
8200/// is responsible for recording the conversion function in the C++
8201/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00008202Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008203 assert(Conversion && "Expected to receive a conversion function declaration");
8204
Douglas Gregor4287b372008-12-12 08:25:50 +00008205 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008206
8207 // Make sure we aren't redeclaring the conversion function.
8208 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008209
8210 // C++ [class.conv.fct]p1:
8211 // [...] A conversion function is never used to convert a
8212 // (possibly cv-qualified) object to the (possibly cv-qualified)
8213 // same object type (or a reference to it), to a (possibly
8214 // cv-qualified) base class of that type (or a reference to it),
8215 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00008216 // FIXME: Suppress this warning if the conversion function ends up being a
8217 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00008218 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008219 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008220 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008221 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00008222 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8223 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00008224 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00008225 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008226 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8227 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00008228 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008229 << ClassType;
Richard Smith0f59cb32015-12-18 21:45:41 +00008230 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00008231 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008232 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008233 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00008234 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008235 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008236 }
8237
Douglas Gregor457104e2010-09-29 04:25:11 +00008238 if (FunctionTemplateDecl *ConversionTemplate
8239 = Conversion->getDescribedFunctionTemplate())
8240 return ConversionTemplate;
Erich Keanebb863642017-09-20 22:28:24 +00008241
John McCall48871652010-08-21 09:40:31 +00008242 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008243}
8244
Richard Smithf283fdc2017-02-08 00:35:25 +00008245namespace {
8246/// Utility class to accumulate and print a diagnostic listing the invalid
8247/// specifier(s) on a declaration.
8248struct BadSpecifierDiagnoser {
8249 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8250 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8251 ~BadSpecifierDiagnoser() {
8252 Diagnostic << Specifiers;
8253 }
8254
8255 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8256 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8257 }
8258 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8259 return check(SpecLoc,
8260 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8261 }
8262 void check(SourceLocation SpecLoc, const char *Spec) {
8263 if (SpecLoc.isInvalid()) return;
8264 Diagnostic << SourceRange(SpecLoc, SpecLoc);
8265 if (!Specifiers.empty()) Specifiers += " ";
8266 Specifiers += Spec;
8267 }
8268
8269 Sema &S;
8270 Sema::SemaDiagnosticBuilder Diagnostic;
8271 std::string Specifiers;
8272};
8273}
8274
Richard Smith35845152017-02-07 01:37:30 +00008275/// Check the validity of a declarator that we parsed for a deduction-guide.
8276/// These aren't actually declarators in the grammar, so we need to check that
8277/// the user didn't specify any pieces that are not part of the deduction-guide
8278/// grammar.
8279void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8280 StorageClass &SC) {
Richard Smith278890f2017-02-10 20:39:58 +00008281 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8282 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8283 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8284
8285 // C++ [temp.deduct.guide]p3:
8286 // A deduction-gide shall be declared in the same scope as the
8287 // corresponding class template.
8288 if (!CurContext->getRedeclContext()->Equals(
8289 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8290 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8291 << GuidedTemplateDecl;
8292 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8293 }
8294
Richard Smithf283fdc2017-02-08 00:35:25 +00008295 auto &DS = D.getMutableDeclSpec();
8296 // We leave 'friend' and 'virtual' to be rejected in the normal way.
8297 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8298 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8299 DS.isNoreturnSpecified() || DS.isConstexprSpecified() ||
8300 DS.isConceptSpecified()) {
8301 BadSpecifierDiagnoser Diagnoser(
8302 *this, D.getIdentifierLoc(),
8303 diag::err_deduction_guide_invalid_specifier);
8304
8305 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8306 DS.ClearStorageClassSpecs();
8307 SC = SC_None;
8308
8309 // 'explicit' is permitted.
8310 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8311 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8312 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8313 Diagnoser.check(DS.getConceptSpecLoc(), "concept");
8314 DS.ClearConstexprSpec();
8315 DS.ClearConceptSpec();
8316
8317 Diagnoser.check(DS.getConstSpecLoc(), "const");
8318 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8319 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8320 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8321 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8322 DS.ClearTypeQualifiers();
8323
8324 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8325 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8326 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8327 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8328 DS.ClearTypeSpecType();
8329 }
8330
8331 if (D.isInvalidType())
8332 return;
8333
8334 // Check the declarator is simple enough.
8335 bool FoundFunction = false;
8336 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8337 if (Chunk.Kind == DeclaratorChunk::Paren)
8338 continue;
8339 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8340 Diag(D.getDeclSpec().getLocStart(),
8341 diag::err_deduction_guide_with_complex_decl)
8342 << D.getSourceRange();
8343 break;
8344 }
8345 if (!Chunk.Fun.hasTrailingReturnType()) {
8346 Diag(D.getName().getLocStart(),
8347 diag::err_deduction_guide_no_trailing_return_type);
8348 break;
8349 }
Richard Smith3817e4a2017-02-10 19:49:50 +00008350
8351 // Check that the return type is written as a specialization of
8352 // the template specified as the deduction-guide's name.
8353 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
Richard Smith3817e4a2017-02-10 19:49:50 +00008354 TypeSourceInfo *TSI = nullptr;
8355 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8356 assert(TSI && "deduction guide has valid type but invalid return type?");
8357 bool AcceptableReturnType = false;
8358 bool MightInstantiateToSpecialization = false;
8359 if (auto RetTST =
8360 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8361 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8362 bool TemplateMatches =
8363 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8364 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8365 AcceptableReturnType = true;
8366 else {
8367 // This could still instantiate to the right type, unless we know it
8368 // names the wrong class template.
8369 auto *TD = SpecifiedName.getAsTemplateDecl();
8370 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8371 !TemplateMatches);
8372 }
8373 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8374 MightInstantiateToSpecialization = true;
8375 }
8376
8377 if (!AcceptableReturnType) {
8378 Diag(TSI->getTypeLoc().getLocStart(),
8379 diag::err_deduction_guide_bad_trailing_return_type)
8380 << GuidedTemplate << TSI->getType() << MightInstantiateToSpecialization
8381 << TSI->getTypeLoc().getSourceRange();
8382 }
8383
8384 // Keep going to check that we don't have any inner declarator pieces (we
8385 // could still have a function returning a pointer to a function).
Richard Smithf283fdc2017-02-08 00:35:25 +00008386 FoundFunction = true;
8387 }
8388
Richard Smithc88aa3f2017-02-08 01:27:29 +00008389 if (D.isFunctionDefinition())
8390 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
Richard Smith35845152017-02-07 01:37:30 +00008391}
8392
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008393//===----------------------------------------------------------------------===//
8394// Namespace Handling
8395//===----------------------------------------------------------------------===//
8396
Richard Smith45bb8852012-10-04 22:13:39 +00008397/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
8398/// reopened.
8399static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8400 SourceLocation Loc,
8401 IdentifierInfo *II, bool *IsInline,
8402 NamespaceDecl *PrevNS) {
8403 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00008404
Richard Smithf501cc32012-10-05 01:46:25 +00008405 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8406 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8407 // inline namespaces, with the intention of bringing names into namespace std.
8408 //
8409 // We support this just well enough to get that case working; this is not
8410 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00008411 if (*IsInline && II && II->getName().startswith("__atomic") &&
8412 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00008413 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00008414 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8415 NS = NS->getPreviousDecl())
8416 NS->setInline(*IsInline);
8417 // Patch up the lookup table for the containing namespace. This isn't really
8418 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00008419 for (auto *I : PrevNS->decls())
8420 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00008421 PrevNS->getParent()->makeDeclVisibleInContext(ND);
8422 return;
8423 }
8424
8425 if (PrevNS->isInline())
8426 // The user probably just forgot the 'inline', so suggest that it
8427 // be added back.
8428 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8429 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8430 else
Richard Smith360cb252016-09-30 23:16:08 +00008431 S.Diag(Loc, diag::err_inline_namespace_mismatch);
Richard Smith45bb8852012-10-04 22:13:39 +00008432
8433 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8434 *IsInline = PrevNS->isInline();
8435}
John McCallb1be5232010-08-26 09:15:37 +00008436
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008437/// ActOnStartNamespaceDef - This is called at the start of a namespace
8438/// definition.
John McCall48871652010-08-21 09:40:31 +00008439Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00008440 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00008441 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00008442 SourceLocation IdentLoc,
8443 IdentifierInfo *II,
8444 SourceLocation LBrace,
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00008445 AttributeList *AttrList,
8446 UsingDirectiveDecl *&UD) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00008447 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8448 // For anonymous namespace, take the location of the left brace.
8449 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00008450 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00008451 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00008452 bool IsStd = false;
8453 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008454 Scope *DeclRegionScope = NamespcScope->getParent();
8455
Craig Topperc3ec1492014-05-26 06:22:03 +00008456 NamespaceDecl *PrevNS = nullptr;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008457 if (II) {
8458 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00008459 // The identifier in an original-namespace-definition shall not
8460 // have been previously defined in the declarative region in
8461 // which the original-namespace-definition appears. The
8462 // identifier in an original-namespace-definition is the name of
8463 // the namespace. Subsequently in that declarative region, it is
8464 // treated as an original-namespace-name.
8465 //
8466 // Since namespace names are unique in their scope, and we don't
Richard Smith97135cc2015-11-12 22:19:45 +00008467 // look through using directives, just look for any ordinary names
8468 // as if by qualified name lookup.
Richard Smithbecb92d2017-10-10 22:33:17 +00008469 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
8470 ForExternalRedeclaration);
Richard Smith97135cc2015-11-12 22:19:45 +00008471 LookupQualifiedName(R, CurContext->getRedeclContext());
Richard Smithf2005d32015-12-29 23:34:32 +00008472 NamedDecl *PrevDecl =
8473 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
Douglas Gregore57e7522012-01-07 09:11:48 +00008474 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
Richard Smith97135cc2015-11-12 22:19:45 +00008475
Douglas Gregore57e7522012-01-07 09:11:48 +00008476 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00008477 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00008478 if (IsInline != PrevNS->isInline())
8479 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8480 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00008481 } else if (PrevDecl) {
8482 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00008483 Diag(Loc, diag::err_redefinition_different_kind)
8484 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00008485 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00008486 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00008487 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00008488 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00008489 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00008490 // This is the first "real" definition of the namespace "std", so update
8491 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00008492 PrevNS = getStdNamespace();
8493 IsStd = true;
8494 AddToKnown = !IsInline;
8495 } else {
8496 // We've seen this namespace for the first time.
8497 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00008498 }
Douglas Gregor91f84212008-12-11 16:49:14 +00008499 } else {
John McCall4fa53422009-10-01 00:25:31 +00008500 // Anonymous namespaces.
Erich Keanebb863642017-09-20 22:28:24 +00008501
Douglas Gregore57e7522012-01-07 09:11:48 +00008502 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00008503 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00008504 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00008505 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00008506 } else {
8507 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00008508 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00008509 }
8510
Richard Smith45bb8852012-10-04 22:13:39 +00008511 if (PrevNS && IsInline != PrevNS->isInline())
8512 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8513 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00008514 }
Erich Keanebb863642017-09-20 22:28:24 +00008515
Douglas Gregore57e7522012-01-07 09:11:48 +00008516 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8517 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00008518 if (IsInvalid)
8519 Namespc->setInvalidDecl();
Erich Keanebb863642017-09-20 22:28:24 +00008520
Douglas Gregore57e7522012-01-07 09:11:48 +00008521 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00008522 AddPragmaAttributes(DeclRegionScope, Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00008523
Douglas Gregore57e7522012-01-07 09:11:48 +00008524 // FIXME: Should we be merging attributes?
8525 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00008526 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00008527
8528 if (IsStd)
8529 StdNamespace = Namespc;
8530 if (AddToKnown)
8531 KnownNamespaces[Namespc] = false;
Erich Keanebb863642017-09-20 22:28:24 +00008532
Douglas Gregore57e7522012-01-07 09:11:48 +00008533 if (II) {
8534 PushOnScopeChains(Namespc, DeclRegionScope);
8535 } else {
8536 // Link the anonymous namespace into its parent.
8537 DeclContext *Parent = CurContext->getRedeclContext();
8538 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8539 TU->setAnonymousNamespace(Namespc);
8540 } else {
8541 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00008542 }
John McCall4fa53422009-10-01 00:25:31 +00008543
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00008544 CurContext->addDecl(Namespc);
8545
John McCall4fa53422009-10-01 00:25:31 +00008546 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
8547 // behaves as if it were replaced by
8548 // namespace unique { /* empty body */ }
8549 // using namespace unique;
8550 // namespace unique { namespace-body }
8551 // where all occurrences of 'unique' in a translation unit are
8552 // replaced by the same identifier and this identifier differs
8553 // from all other identifiers in the entire program.
8554
8555 // We just create the namespace with an empty name and then add an
8556 // implicit using declaration, just like the standard suggests.
8557 //
8558 // CodeGen enforces the "universally unique" aspect by giving all
8559 // declarations semantically contained within an anonymous
8560 // namespace internal linkage.
8561
Douglas Gregore57e7522012-01-07 09:11:48 +00008562 if (!PrevNS) {
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00008563 UD = UsingDirectiveDecl::Create(Context, Parent,
8564 /* 'using' */ LBrace,
8565 /* 'namespace' */ SourceLocation(),
8566 /* qualifier */ NestedNameSpecifierLoc(),
8567 /* identifier */ SourceLocation(),
8568 Namespc,
8569 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00008570 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00008571 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00008572 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008573 }
8574
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00008575 ActOnDocumentableDecl(Namespc);
8576
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008577 // Although we could have an invalid decl (i.e. the namespace name is a
8578 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00008579 // FIXME: We should be able to push Namespc here, so that the each DeclContext
8580 // for the namespace has the declarations that showed up in that particular
8581 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00008582 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00008583 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008584}
8585
Sebastian Redla6602e92009-11-23 15:34:23 +00008586/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8587/// is a namespace alias, returns the namespace it points to.
8588static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8589 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8590 return AD->getNamespace();
8591 return dyn_cast_or_null<NamespaceDecl>(D);
8592}
8593
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008594/// ActOnFinishNamespaceDef - This callback is called after a namespace is
8595/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00008596void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008597 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8598 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00008599 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008600 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00008601 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00008602 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008603}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008604
John McCall28a0cf72010-08-25 07:42:41 +00008605CXXRecordDecl *Sema::getStdBadAlloc() const {
8606 return cast_or_null<CXXRecordDecl>(
8607 StdBadAlloc.get(Context.getExternalSource()));
8608}
8609
Richard Smith96269c52016-09-29 22:49:46 +00008610EnumDecl *Sema::getStdAlignValT() const {
8611 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
8612}
8613
John McCall28a0cf72010-08-25 07:42:41 +00008614NamespaceDecl *Sema::getStdNamespace() const {
8615 return cast_or_null<NamespaceDecl>(
8616 StdNamespace.get(Context.getExternalSource()));
8617}
8618
Gor Nishanov3e048bb2016-10-04 00:31:16 +00008619NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
8620 if (!StdExperimentalNamespaceCache) {
8621 if (auto Std = getStdNamespace()) {
8622 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
8623 SourceLocation(), LookupNamespaceName);
8624 if (!LookupQualifiedName(Result, Std) ||
8625 !(StdExperimentalNamespaceCache =
8626 Result.getAsSingle<NamespaceDecl>()))
8627 Result.suppressDiagnostics();
8628 }
8629 }
8630 return StdExperimentalNamespaceCache;
8631}
8632
Erich Keanebb863642017-09-20 22:28:24 +00008633/// \brief Retrieve the special "std" namespace, which may require us to
Douglas Gregorcdf87022010-06-29 17:53:46 +00008634/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00008635NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00008636 if (!StdNamespace) {
8637 // The "std" namespace has not yet been defined, so build one implicitly.
Erich Keanebb863642017-09-20 22:28:24 +00008638 StdNamespace = NamespaceDecl::Create(Context,
Douglas Gregorcdf87022010-06-29 17:53:46 +00008639 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00008640 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00008641 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00008642 &PP.getIdentifierTable().get("std"),
Craig Topperc3ec1492014-05-26 06:22:03 +00008643 /*PrevDecl=*/nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00008644 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00008645 }
Eli Bendersky9a220fc2014-09-29 20:38:29 +00008646
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00008647 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00008648}
8649
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008650bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008651 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008652 "Looking for std::initializer_list outside of C++.");
8653
8654 // We're looking for implicit instantiations of
8655 // template <typename E> class std::initializer_list.
8656
8657 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
8658 return false;
8659
Craig Topperc3ec1492014-05-26 06:22:03 +00008660 ClassTemplateDecl *Template = nullptr;
8661 const TemplateArgument *Arguments = nullptr;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008662
Sebastian Redl43144e72012-01-17 22:49:58 +00008663 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008664
Sebastian Redl43144e72012-01-17 22:49:58 +00008665 ClassTemplateSpecializationDecl *Specialization =
8666 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
8667 if (!Specialization)
8668 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008669
Sebastian Redl43144e72012-01-17 22:49:58 +00008670 Template = Specialization->getSpecializedTemplate();
8671 Arguments = Specialization->getTemplateArgs().data();
8672 } else if (const TemplateSpecializationType *TST =
8673 Ty->getAs<TemplateSpecializationType>()) {
8674 Template = dyn_cast_or_null<ClassTemplateDecl>(
8675 TST->getTemplateName().getAsTemplateDecl());
8676 Arguments = TST->getArgs();
8677 }
8678 if (!Template)
8679 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008680
8681 if (!StdInitializerList) {
8682 // Haven't recognized std::initializer_list yet, maybe this is it.
8683 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
8684 if (TemplateClass->getIdentifier() !=
8685 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00008686 !getStdNamespace()->InEnclosingNamespaceSetOf(
8687 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008688 return false;
8689 // This is a template called std::initializer_list, but is it the right
8690 // template?
8691 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00008692 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008693 return false;
8694 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
8695 return false;
8696
8697 // It's the right template.
8698 StdInitializerList = Template;
8699 }
8700
Richard Smith7d7dee72015-02-24 03:30:14 +00008701 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008702 return false;
8703
8704 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00008705 if (Element)
8706 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008707 return true;
8708}
8709
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008710static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
8711 NamespaceDecl *Std = S.getStdNamespace();
8712 if (!Std) {
8713 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00008714 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008715 }
8716
8717 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
8718 Loc, Sema::LookupOrdinaryName);
8719 if (!S.LookupQualifiedName(Result, Std)) {
8720 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00008721 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008722 }
8723 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
8724 if (!Template) {
8725 Result.suppressDiagnostics();
8726 // We found something weird. Complain about the first thing we found.
8727 NamedDecl *Found = *Result.begin();
8728 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00008729 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008730 }
8731
8732 // We found some template called std::initializer_list. Now verify that it's
8733 // correct.
8734 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00008735 if (Params->getMinRequiredArguments() != 1 ||
8736 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008737 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00008738 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008739 }
8740
8741 return Template;
8742}
8743
8744QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
8745 if (!StdInitializerList) {
8746 StdInitializerList = LookupStdInitializerList(*this, Loc);
8747 if (!StdInitializerList)
8748 return QualType();
8749 }
8750
8751 TemplateArgumentListInfo Args(Loc, Loc);
8752 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
8753 Context.getTrivialTypeSourceInfo(Element,
8754 Loc)));
8755 return Context.getCanonicalType(
8756 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
8757}
8758
Richard Smith60437622017-02-09 19:17:44 +00008759bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
Sebastian Redlbe24ec22012-01-17 22:50:14 +00008760 // C++ [dcl.init.list]p2:
8761 // A constructor is an initializer-list constructor if its first parameter
8762 // is of type std::initializer_list<E> or reference to possibly cv-qualified
8763 // std::initializer_list<E> for some type E, and either there are no other
8764 // parameters or else all other parameters have default arguments.
8765 if (Ctor->getNumParams() < 1 ||
8766 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
8767 return false;
8768
8769 QualType ArgType = Ctor->getParamDecl(0)->getType();
8770 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
8771 ArgType = RT->getPointeeType().getUnqualifiedType();
8772
Craig Topperc3ec1492014-05-26 06:22:03 +00008773 return isStdInitializerList(ArgType, nullptr);
Sebastian Redlbe24ec22012-01-17 22:50:14 +00008774}
8775
Douglas Gregora172e082011-03-26 22:25:30 +00008776/// \brief Determine whether a using statement is in a context where it will be
8777/// apply in all contexts.
8778static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
8779 switch (CurContext->getDeclKind()) {
8780 case Decl::TranslationUnit:
8781 return true;
8782 case Decl::LinkageSpec:
8783 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
8784 default:
8785 return false;
8786 }
8787}
8788
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008789namespace {
8790
8791// Callback to only accept typo corrections that are namespaces.
8792class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008793public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008794 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008795 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008796 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008797 return false;
8798 }
8799};
8800
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008801}
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008802
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008803static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
8804 CXXScopeSpec &SS,
8805 SourceLocation IdentLoc,
8806 IdentifierInfo *Ident) {
8807 R.clear();
Kaelyn Takata89c881b2014-10-27 18:07:29 +00008808 if (TypoCorrection Corrected =
8809 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
8810 llvm::make_unique<NamespaceValidatorCCC>(),
8811 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00008812 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00008813 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
8814 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00008815 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00008816 S.diagnoseTypo(Corrected,
8817 S.PDiag(diag::err_using_directive_member_suggest)
8818 << Ident << DC << DroppedSpecifier << SS.getRange(),
8819 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00008820 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00008821 S.diagnoseTypo(Corrected,
8822 S.PDiag(diag::err_using_directive_suggest) << Ident,
8823 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00008824 }
Richard Smithde6d6c42015-12-29 19:43:10 +00008825 R.addDecl(Corrected.getFoundDecl());
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008826 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008827 }
8828 return false;
8829}
8830
John McCall48871652010-08-21 09:40:31 +00008831Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00008832 SourceLocation UsingLoc,
8833 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00008834 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00008835 SourceLocation IdentLoc,
8836 IdentifierInfo *NamespcName,
8837 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00008838 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8839 assert(NamespcName && "Invalid NamespcName.");
8840 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00008841
8842 // This can only happen along a recovery path.
Davide Italiano5be22332015-11-11 20:06:35 +00008843 while (S->isTemplateParamScope())
John McCall9b72f892010-11-10 02:40:36 +00008844 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00008845 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00008846
Craig Topperc3ec1492014-05-26 06:22:03 +00008847 UsingDirectiveDecl *UDir = nullptr;
8848 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregorcdf87022010-06-29 17:53:46 +00008849 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00008850 Qualifier = SS.getScopeRep();
Erich Keanebb863642017-09-20 22:28:24 +00008851
Douglas Gregor34074322009-01-14 22:20:51 +00008852 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00008853 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
8854 LookupParsedName(R, S, &SS);
8855 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00008856 return nullptr;
John McCall27b18f82009-11-17 02:14:36 +00008857
Douglas Gregorcdf87022010-06-29 17:53:46 +00008858 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008859 R.clear();
Erich Keanebb863642017-09-20 22:28:24 +00008860 // Allow "using namespace std;" or "using namespace ::std;" even if
Douglas Gregorcdf87022010-06-29 17:53:46 +00008861 // "std" hasn't been defined yet, for GCC compatibility.
8862 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
8863 NamespcName->isStr("std")) {
8864 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00008865 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00008866 R.resolveKind();
Erich Keanebb863642017-09-20 22:28:24 +00008867 }
Douglas Gregorcdf87022010-06-29 17:53:46 +00008868 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008869 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00008870 }
Erich Keanebb863642017-09-20 22:28:24 +00008871
John McCall9f3059a2009-10-09 21:13:30 +00008872 if (!R.empty()) {
Richard Smithf2005d32015-12-29 23:34:32 +00008873 NamedDecl *Named = R.getRepresentativeDecl();
8874 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
8875 assert(NS && "expected namespace decl");
Aaron Ballman43f40102014-11-14 22:34:56 +00008876
Nico Riecke50e59a2014-11-24 17:29:52 +00008877 // The use of a nested name specifier may trigger deprecation warnings.
8878 DiagnoseUseOfDecl(Named, IdentLoc);
Aaron Ballman43f40102014-11-14 22:34:56 +00008879
Douglas Gregor889ceb72009-02-03 19:21:40 +00008880 // C++ [namespace.udir]p1:
8881 // A using-directive specifies that the names in the nominated
8882 // namespace can be used in the scope in which the
8883 // using-directive appears after the using-directive. During
8884 // unqualified name lookup (3.4.1), the names appear as if they
8885 // were declared in the nearest enclosing namespace which
8886 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00008887 // namespace. [Note: in this context, "contains" means "contains
8888 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00008889
8890 // Find enclosing context containing both using-directive and
8891 // nominated namespace.
8892 DeclContext *CommonAncestor = cast<DeclContext>(NS);
8893 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
8894 CommonAncestor = CommonAncestor->getParent();
8895
Sebastian Redla6602e92009-11-23 15:34:23 +00008896 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00008897 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00008898 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00008899
Douglas Gregora172e082011-03-26 22:25:30 +00008900 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00008901 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00008902 Diag(IdentLoc, diag::warn_using_directive_in_header);
8903 }
8904
Douglas Gregor889ceb72009-02-03 19:21:40 +00008905 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00008906 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00008907 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00008908 }
8909
Richard Smith54ecd982013-02-20 19:22:51 +00008910 if (UDir)
8911 ProcessDeclAttributeList(S, UDir, AttrList);
8912
John McCall48871652010-08-21 09:40:31 +00008913 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00008914}
8915
8916void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00008917 // If the scope has an associated entity and the using directive is at
8918 // namespace or translation unit scope, add the UsingDirectiveDecl into
8919 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00008920 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00008921 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00008922 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00008923 else
Yaron Keren065da7c2014-05-20 18:23:05 +00008924 // Otherwise, it is at block scope. The using-directives will affect lookup
Richard Smith05afe5e2012-03-13 03:12:56 +00008925 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00008926 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00008927}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008928
Douglas Gregorfec52632009-06-20 00:51:54 +00008929
John McCall48871652010-08-21 09:40:31 +00008930Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00008931 AccessSpecifier AS,
John McCall9b72f892010-11-10 02:40:36 +00008932 SourceLocation UsingLoc,
Richard Smith151c4562016-12-20 21:35:28 +00008933 SourceLocation TypenameLoc,
John McCall9b72f892010-11-10 02:40:36 +00008934 CXXScopeSpec &SS,
8935 UnqualifiedId &Name,
Richard Smith151c4562016-12-20 21:35:28 +00008936 SourceLocation EllipsisLoc,
8937 AttributeList *AttrList) {
Douglas Gregorfec52632009-06-20 00:51:54 +00008938 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00008939
Richard Smith151c4562016-12-20 21:35:28 +00008940 if (SS.isEmpty()) {
8941 Diag(Name.getLocStart(), diag::err_using_requires_qualname);
8942 return nullptr;
8943 }
8944
Douglas Gregor220f4272009-11-04 16:30:06 +00008945 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00008946 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00008947 case UnqualifiedId::IK_Identifier:
8948 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00008949 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00008950 case UnqualifiedId::IK_ConversionFunctionId:
8951 break;
Erich Keanebb863642017-09-20 22:28:24 +00008952
Douglas Gregor220f4272009-11-04 16:30:06 +00008953 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00008954 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00008955 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008956 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008957 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00008958 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00008959 diag::err_using_decl_constructor)
8960 << SS.getRange();
8961
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008962 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00008963
Craig Topperc3ec1492014-05-26 06:22:03 +00008964 return nullptr;
8965
Douglas Gregor220f4272009-11-04 16:30:06 +00008966 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008967 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00008968 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00008969 return nullptr;
8970
Douglas Gregor220f4272009-11-04 16:30:06 +00008971 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008972 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00008973 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00008974 return nullptr;
Richard Smith35845152017-02-07 01:37:30 +00008975
8976 case UnqualifiedId::IK_DeductionGuideName:
8977 llvm_unreachable("cannot parse qualified deduction guide name");
Douglas Gregor220f4272009-11-04 16:30:06 +00008978 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008979
8980 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
8981 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00008982 if (!TargetName)
Craig Topperc3ec1492014-05-26 06:22:03 +00008983 return nullptr;
John McCall3969e302009-12-08 07:46:18 +00008984
Richard Smithc2bc61b2013-03-18 21:12:30 +00008985 // Warn about access declarations.
Richard Smith6f1daa42016-12-16 00:58:48 +00008986 if (UsingLoc.isInvalid()) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00008987 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00008988 getLangOpts().CPlusPlus11 ? diag::err_access_decl
8989 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00008990 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00008991 }
8992
Richard Smith151c4562016-12-20 21:35:28 +00008993 if (EllipsisLoc.isInvalid()) {
8994 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
8995 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
8996 return nullptr;
8997 } else {
8998 if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
8999 !TargetNameInfo.containsUnexpandedParameterPack()) {
9000 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
9001 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
9002 EllipsisLoc = SourceLocation();
9003 }
9004 }
Douglas Gregorc4356532010-12-16 00:46:58 +00009005
Richard Smith151c4562016-12-20 21:35:28 +00009006 NamedDecl *UD =
9007 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
9008 SS, TargetNameInfo, EllipsisLoc, AttrList,
9009 /*IsInstantiation*/false);
John McCallb96ec562009-12-04 22:46:56 +00009010 if (UD)
9011 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00009012
John McCall48871652010-08-21 09:40:31 +00009013 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00009014}
9015
Douglas Gregor1d9ef842010-07-07 23:08:52 +00009016/// \brief Determine whether a using declaration considers the given
9017/// declarations as "equivalent", e.g., if they are redeclarations of
9018/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00009019static bool
9020IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
9021 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00009022 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00009023
Richard Smithdda56e42011-04-15 14:24:37 +00009024 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00009025 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00009026 return Context.hasSameType(TD1->getUnderlyingType(),
9027 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00009028
9029 return false;
9030}
9031
9032
John McCall84d87672009-12-10 09:41:52 +00009033/// Determines whether to create a using shadow decl for a particular
9034/// decl, given the set of decls existing prior to this using lookup.
9035bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00009036 const LookupResult &Previous,
9037 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00009038 // Diagnose finding a decl which is not from a base class of the
9039 // current class. We do this now because there are cases where this
9040 // function will silently decide not to build a shadow decl, which
9041 // will pre-empt further diagnostics.
9042 //
Richard Smith5cbeb752016-05-05 02:13:49 +00009043 // We don't need to do this in C++11 because we do the check once on
John McCall84d87672009-12-10 09:41:52 +00009044 // the qualifier.
9045 //
9046 // FIXME: diagnose the following if we care enough:
9047 // struct A { int foo; };
9048 // struct B : A { using A::foo; };
9049 // template <class T> struct C : A {};
9050 // template <class T> struct D : C<T> { using B::foo; } // <---
9051 // This is invalid (during instantiation) in C++03 because B::foo
9052 // resolves to the using decl in B, which is not a base class of D<T>.
9053 // We can't diagnose it immediately because C<T> is an unknown
9054 // specialization. The UsingShadowDecl in D<T> then points directly
9055 // to A::foo, which will look well-formed when we instantiate.
9056 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009057 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00009058 DeclContext *OrigDC = Orig->getDeclContext();
9059
9060 // Handle enums and anonymous structs.
9061 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
9062 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9063 while (OrigRec->isAnonymousStructOrUnion())
9064 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9065
9066 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9067 if (OrigDC == CurContext) {
9068 Diag(Using->getLocation(),
9069 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009070 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00009071 Diag(Orig->getLocation(), diag::note_using_decl_target);
Richard Smith151c4562016-12-20 21:35:28 +00009072 Using->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00009073 return true;
9074 }
9075
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009076 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00009077 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009078 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00009079 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009080 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00009081 Diag(Orig->getLocation(), diag::note_using_decl_target);
Richard Smith151c4562016-12-20 21:35:28 +00009082 Using->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00009083 return true;
9084 }
9085 }
9086
9087 if (Previous.empty()) return false;
9088
9089 NamedDecl *Target = Orig;
9090 if (isa<UsingShadowDecl>(Target))
9091 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9092
John McCalla17e83e2009-12-11 02:33:26 +00009093 // If the target happens to be one of the previous declarations, we
9094 // don't have a conflict.
Erich Keanebb863642017-09-20 22:28:24 +00009095 //
John McCalla17e83e2009-12-11 02:33:26 +00009096 // FIXME: but we might be increasing its access, in which case we
9097 // should redeclare it.
Craig Topperc3ec1492014-05-26 06:22:03 +00009098 NamedDecl *NonTag = nullptr, *Tag = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00009099 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00009100 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9101 I != E; ++I) {
9102 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithe5a91462016-02-27 02:36:43 +00009103 // We can have UsingDecls in our Previous results because we use the same
9104 // LookupResult for checking whether the UsingDecl itself is a valid
9105 // redeclaration.
Richard Smith151c4562016-12-20 21:35:28 +00009106 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
Richard Smithe5a91462016-02-27 02:36:43 +00009107 continue;
9108
Richard Smithfd8634a2013-10-23 02:17:46 +00009109 if (IsEquivalentForUsingDecl(Context, D, Target)) {
9110 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9111 PrevShadow = Shadow;
9112 FoundEquivalentDecl = true;
Richard Smith2de44e62016-01-12 20:34:32 +00009113 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9114 // We don't conflict with an existing using shadow decl of an equivalent
9115 // declaration, but we're not a redeclaration of it.
9116 FoundEquivalentDecl = true;
Richard Smithfd8634a2013-10-23 02:17:46 +00009117 }
John McCalla17e83e2009-12-11 02:33:26 +00009118
Richard Smithf091e122015-09-15 01:28:55 +00009119 if (isVisible(D))
9120 (isa<TagDecl>(D) ? Tag : NonTag) = D;
John McCalla17e83e2009-12-11 02:33:26 +00009121 }
9122
Richard Smithfd8634a2013-10-23 02:17:46 +00009123 if (FoundEquivalentDecl)
9124 return false;
9125
Alp Tokera2794f92014-01-22 07:29:52 +00009126 if (FunctionDecl *FD = Target->getAsFunction()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00009127 NamedDecl *OldDecl = nullptr;
9128 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9129 /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00009130 case Ovl_Overload:
9131 return false;
9132
9133 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00009134 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00009135 break;
Richard Smith18819302014-02-06 01:31:33 +00009136
John McCall84d87672009-12-10 09:41:52 +00009137 // We found a decl with the exact signature.
9138 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00009139 // If we're in a record, we want to hide the target, so we
9140 // return true (without a diagnostic) to tell the caller not to
9141 // build a shadow decl.
9142 if (CurContext->isRecord())
9143 return true;
9144
9145 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00009146 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00009147 break;
9148 }
9149
9150 Diag(Target->getLocation(), diag::note_using_decl_target);
9151 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
Richard Smith151c4562016-12-20 21:35:28 +00009152 Using->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00009153 return true;
9154 }
9155
9156 // Target is not a function.
9157
John McCall84d87672009-12-10 09:41:52 +00009158 if (isa<TagDecl>(Target)) {
9159 // No conflict between a tag and a non-tag.
9160 if (!Tag) return false;
9161
John McCalle29c5cd2009-12-10 19:51:03 +00009162 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00009163 Diag(Target->getLocation(), diag::note_using_decl_target);
9164 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
Richard Smith151c4562016-12-20 21:35:28 +00009165 Using->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00009166 return true;
9167 }
9168
9169 // No conflict between a tag and a non-tag.
9170 if (!NonTag) return false;
9171
John McCalle29c5cd2009-12-10 19:51:03 +00009172 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00009173 Diag(Target->getLocation(), diag::note_using_decl_target);
9174 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
Richard Smith151c4562016-12-20 21:35:28 +00009175 Using->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00009176 return true;
9177}
9178
Richard Smith5179eb72016-06-28 19:03:57 +00009179/// Determine whether a direct base class is a virtual base class.
9180static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9181 if (!Derived->getNumVBases())
9182 return false;
9183 for (auto &B : Derived->bases())
9184 if (B.getType()->getAsCXXRecordDecl() == Base)
9185 return B.isVirtual();
9186 llvm_unreachable("not a direct base class");
9187}
9188
John McCall3f746822009-11-17 05:59:44 +00009189/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00009190UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00009191 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00009192 NamedDecl *Orig,
9193 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00009194 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00009195 NamedDecl *Target = Orig;
9196 if (isa<UsingShadowDecl>(Target)) {
9197 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9198 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00009199 }
Richard Smithfd8634a2013-10-23 02:17:46 +00009200
Richard Smith5179eb72016-06-28 19:03:57 +00009201 NamedDecl *NonTemplateTarget = Target;
9202 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9203 NonTemplateTarget = TargetTD->getTemplatedDecl();
9204
9205 UsingShadowDecl *Shadow;
9206 if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
9207 bool IsVirtualBase =
9208 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9209 UD->getQualifier()->getAsRecordDecl());
9210 Shadow = ConstructorUsingShadowDecl::Create(
9211 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9212 } else {
9213 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9214 Target);
9215 }
John McCall3f746822009-11-17 05:59:44 +00009216 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00009217
Douglas Gregor457104e2010-09-29 04:25:11 +00009218 Shadow->setAccess(UD->getAccess());
9219 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9220 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00009221
9222 Shadow->setPreviousDecl(PrevDecl);
9223
John McCall3f746822009-11-17 05:59:44 +00009224 if (S)
John McCall3969e302009-12-08 07:46:18 +00009225 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00009226 else
John McCall3969e302009-12-08 07:46:18 +00009227 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00009228
John McCall3969e302009-12-08 07:46:18 +00009229
John McCall84d87672009-12-10 09:41:52 +00009230 return Shadow;
9231}
John McCall3969e302009-12-08 07:46:18 +00009232
John McCall84d87672009-12-10 09:41:52 +00009233/// Hides a using shadow declaration. This is required by the current
9234/// using-decl implementation when a resolvable using declaration in a
9235/// class is followed by a declaration which would hide or override
9236/// one or more of the using decl's targets; for example:
9237///
9238/// struct Base { void foo(int); };
9239/// struct Derived : Base {
9240/// using Base::foo;
9241/// void foo(int);
9242/// };
9243///
9244/// The governing language is C++03 [namespace.udecl]p12:
9245///
9246/// When a using-declaration brings names from a base class into a
9247/// derived class scope, member functions in the derived class
9248/// override and/or hide member functions with the same name and
9249/// parameter types in a base class (rather than conflicting).
9250///
9251/// There are two ways to implement this:
9252/// (1) optimistically create shadow decls when they're not hidden
9253/// by existing declarations, or
9254/// (2) don't create any shadow decls (or at least don't make them
9255/// visible) until we've fully parsed/instantiated the class.
9256/// The problem with (1) is that we might have to retroactively remove
9257/// a shadow decl, which requires several O(n) operations because the
9258/// decl structures are (very reasonably) not designed for removal.
9259/// (2) avoids this but is very fiddly and phase-dependent.
9260void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00009261 if (Shadow->getDeclName().getNameKind() ==
9262 DeclarationName::CXXConversionFunctionName)
9263 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9264
John McCall84d87672009-12-10 09:41:52 +00009265 // Remove it from the DeclContext...
9266 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00009267
John McCall84d87672009-12-10 09:41:52 +00009268 // ...and the scope, if applicable...
9269 if (S) {
John McCall48871652010-08-21 09:40:31 +00009270 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00009271 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00009272 }
9273
John McCall84d87672009-12-10 09:41:52 +00009274 // ...and the using decl.
9275 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9276
9277 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00009278 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00009279}
9280
Richard Smith09d5b3a2014-05-01 00:35:04 +00009281/// Find the base specifier for a base class with the given type.
9282static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9283 QualType DesiredBase,
9284 bool &AnyDependentBases) {
9285 // Check whether the named type is a direct base class.
9286 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9287 for (auto &Base : Derived->bases()) {
9288 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9289 if (CanonicalDesiredBase == BaseType)
9290 return &Base;
9291 if (BaseType->isDependentType())
9292 AnyDependentBases = true;
9293 }
Craig Topperc3ec1492014-05-26 06:22:03 +00009294 return nullptr;
Richard Smith09d5b3a2014-05-01 00:35:04 +00009295}
9296
Benjamin Kramer8bf44352013-07-24 15:28:33 +00009297namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009298class UsingValidatorCCC : public CorrectionCandidateCallback {
9299public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00009300 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
Richard Smith09d5b3a2014-05-01 00:35:04 +00009301 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009302 : HasTypenameKeyword(HasTypenameKeyword),
Richard Smith09d5b3a2014-05-01 00:35:04 +00009303 IsInstantiation(IsInstantiation), OldNNS(NNS),
9304 RequireMemberOf(RequireMemberOf) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009305
Craig Toppera798a9d2014-03-02 09:32:10 +00009306 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00009307 NamedDecl *ND = Candidate.getCorrectionDecl();
9308
9309 // Keywords are not valid here.
9310 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009311 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00009312
9313 // Completely unqualified names are invalid for a 'using' declaration.
9314 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9315 return false;
9316
Richard Smith9385d702016-05-14 01:58:49 +00009317 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9318 // reject.
9319
Richard Smith09d5b3a2014-05-01 00:35:04 +00009320 if (RequireMemberOf) {
9321 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9322 if (FoundRecord && FoundRecord->isInjectedClassName()) {
9323 // No-one ever wants a using-declaration to name an injected-class-name
9324 // of a base class, unless they're declaring an inheriting constructor.
9325 ASTContext &Ctx = ND->getASTContext();
9326 if (!Ctx.getLangOpts().CPlusPlus11)
9327 return false;
9328 QualType FoundType = Ctx.getRecordType(FoundRecord);
9329
9330 // Check that the injected-class-name is named as a member of its own
9331 // type; we don't want to suggest 'using Derived::Base;', since that
9332 // means something else.
9333 NestedNameSpecifier *Specifier =
9334 Candidate.WillReplaceSpecifier()
9335 ? Candidate.getCorrectionSpecifier()
9336 : OldNNS;
9337 if (!Specifier->getAsType() ||
9338 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9339 return false;
9340
9341 // Check that this inheriting constructor declaration actually names a
9342 // direct base class of the current class.
9343 bool AnyDependentBases = false;
9344 if (!findDirectBaseWithType(RequireMemberOf,
9345 Ctx.getRecordType(FoundRecord),
9346 AnyDependentBases) &&
9347 !AnyDependentBases)
9348 return false;
9349 } else {
9350 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9351 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9352 return false;
9353
9354 // FIXME: Check that the base class member is accessible?
9355 }
Kaelyn Takatad14c0612015-09-30 18:23:35 +00009356 } else {
9357 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9358 if (FoundRecord && FoundRecord->isInjectedClassName())
9359 return false;
Richard Smith09d5b3a2014-05-01 00:35:04 +00009360 }
9361
Benjamin Kramer8bf44352013-07-24 15:28:33 +00009362 if (isa<TypeDecl>(ND))
9363 return HasTypenameKeyword || !IsInstantiation;
9364
9365 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009366 }
9367
9368private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009369 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009370 bool IsInstantiation;
Richard Smith09d5b3a2014-05-01 00:35:04 +00009371 NestedNameSpecifier *OldNNS;
Richard Smith21866c32014-04-30 18:03:21 +00009372 CXXRecordDecl *RequireMemberOf;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009373};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00009374} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009375
John McCalle61f2ba2009-11-18 02:36:19 +00009376/// Builds a using declaration.
9377///
9378/// \param IsInstantiation - Whether this call arises from an
9379/// instantiation of an unresolved using declaration. We treat
9380/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00009381NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
9382 SourceLocation UsingLoc,
Richard Smith151c4562016-12-20 21:35:28 +00009383 bool HasTypenameKeyword,
9384 SourceLocation TypenameLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00009385 CXXScopeSpec &SS,
Richard Smith09d5b3a2014-05-01 00:35:04 +00009386 DeclarationNameInfo NameInfo,
Richard Smith151c4562016-12-20 21:35:28 +00009387 SourceLocation EllipsisLoc,
Anders Carlsson696a3f12009-08-28 05:40:36 +00009388 AttributeList *AttrList,
Richard Smith151c4562016-12-20 21:35:28 +00009389 bool IsInstantiation) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00009390 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00009391 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00009392 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00009393
Anders Carlssonf038fc22009-08-28 05:49:21 +00009394 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00009395
Richard Smith5179eb72016-06-28 19:03:57 +00009396 // For an inheriting constructor declaration, the name of the using
9397 // declaration is the name of a constructor in this class, not in the
9398 // base class.
9399 DeclarationNameInfo UsingName = NameInfo;
9400 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9401 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9402 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9403 Context.getCanonicalType(Context.getRecordType(RD))));
9404
John McCall84d87672009-12-10 09:41:52 +00009405 // Do the redeclaration lookup in the current scope.
Richard Smith5179eb72016-06-28 19:03:57 +00009406 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
Richard Smithbecb92d2017-10-10 22:33:17 +00009407 ForVisibleRedeclaration);
John McCall84d87672009-12-10 09:41:52 +00009408 Previous.setHideTags(false);
9409 if (S) {
9410 LookupName(Previous, S);
9411
9412 // It is really dumb that we have to do this.
9413 LookupResult::Filter F = Previous.makeFilter();
9414 while (F.hasNext()) {
9415 NamedDecl *D = F.next();
9416 if (!isDeclInScope(D, CurContext, S))
9417 F.erase();
Richard Smith83e78f52014-04-11 01:03:38 +00009418 // If we found a local extern declaration that's not ordinarily visible,
9419 // and this declaration is being added to a non-block scope, ignore it.
9420 // We're only checking for scope conflicts here, not also for violations
9421 // of the linkage rules.
9422 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9423 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9424 F.erase();
John McCall84d87672009-12-10 09:41:52 +00009425 }
9426 F.done();
9427 } else {
9428 assert(IsInstantiation && "no scope in non-instantiation");
Richard Smithd8a9e372016-12-18 21:39:37 +00009429 if (CurContext->isRecord())
9430 LookupQualifiedName(Previous, CurContext);
9431 else {
9432 // No redeclaration check is needed here; in non-member contexts we
9433 // diagnosed all possible conflicts with other using-declarations when
9434 // building the template:
9435 //
9436 // For a dependent non-type using declaration, the only valid case is
9437 // if we instantiate to a single enumerator. We check for conflicts
9438 // between shadow declarations we introduce, and we check in the template
9439 // definition for conflicts between a non-type using declaration and any
9440 // other declaration, which together covers all cases.
9441 //
9442 // A dependent typename using declaration will never successfully
9443 // instantiate, since it will always name a class member, so we reject
9444 // that in the template definition.
9445 }
John McCall84d87672009-12-10 09:41:52 +00009446 }
9447
John McCall84d87672009-12-10 09:41:52 +00009448 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009449 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9450 SS, IdentLoc, Previous))
Craig Topperc3ec1492014-05-26 06:22:03 +00009451 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00009452
9453 // Check for bad qualifiers.
Richard Smithd8a9e372016-12-18 21:39:37 +00009454 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
9455 IdentLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00009456 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00009457
John McCall84c16cf2009-11-12 03:15:40 +00009458 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00009459 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009460 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Richard Smith151c4562016-12-20 21:35:28 +00009461 if (!LookupContext || EllipsisLoc.isValid()) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009462 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00009463 // FIXME: not all declaration name kinds are legal here
9464 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9465 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009466 QualifierLoc,
Richard Smith151c4562016-12-20 21:35:28 +00009467 IdentLoc, NameInfo.getName(),
9468 EllipsisLoc);
John McCallb96ec562009-12-04 22:46:56 +00009469 } else {
Erich Keanebb863642017-09-20 22:28:24 +00009470 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
Richard Smith151c4562016-12-20 21:35:28 +00009471 QualifierLoc, NameInfo, EllipsisLoc);
John McCalle61f2ba2009-11-18 02:36:19 +00009472 }
Richard Smith09d5b3a2014-05-01 00:35:04 +00009473 D->setAccess(AS);
9474 CurContext->addDecl(D);
9475 return D;
Anders Carlssonf038fc22009-08-28 05:49:21 +00009476 }
John McCallb96ec562009-12-04 22:46:56 +00009477
Richard Smith09d5b3a2014-05-01 00:35:04 +00009478 auto Build = [&](bool Invalid) {
9479 UsingDecl *UD =
Richard Smith5179eb72016-06-28 19:03:57 +00009480 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
9481 UsingName, HasTypenameKeyword);
Richard Smith09d5b3a2014-05-01 00:35:04 +00009482 UD->setAccess(AS);
9483 CurContext->addDecl(UD);
9484 UD->setInvalidDecl(Invalid);
John McCall3969e302009-12-08 07:46:18 +00009485 return UD;
Richard Smith09d5b3a2014-05-01 00:35:04 +00009486 };
9487 auto BuildInvalid = [&]{ return Build(true); };
9488 auto BuildValid = [&]{ return Build(false); };
9489
9490 if (RequireCompleteDeclContext(SS, LookupContext))
9491 return BuildInvalid();
Anders Carlsson59140b32009-08-28 03:16:11 +00009492
Richard Smith78163e22015-04-01 19:31:06 +00009493 // Look up the target name.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00009494 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00009495
John McCall3969e302009-12-08 07:46:18 +00009496 // Unlike most lookups, we don't always want to hide tag
9497 // declarations: tag names are visible through the using declaration
9498 // even if hidden by ordinary names, *except* in a dependent context
9499 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00009500 if (!IsInstantiation)
9501 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00009502
John McCall5dadb652012-04-07 03:04:20 +00009503 // For the purposes of this lookup, we have a base object type
9504 // equal to that of the current context.
9505 if (CurContext->isRecord()) {
9506 R.setBaseObjectType(
9507 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
9508 }
9509
John McCall27b18f82009-11-17 02:14:36 +00009510 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00009511
Richard Smith78163e22015-04-01 19:31:06 +00009512 // Try to correct typos if possible. If constructor name lookup finds no
9513 // results, that means the named class has no explicit constructors, and we
9514 // suppressed declaring implicit ones (probably because it's dependent or
9515 // invalid).
9516 if (R.empty() &&
9517 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
Richard Smith46d04a32017-01-08 04:01:15 +00009518 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
9519 // it will believe that glibc provides a ::gets in cases where it does not,
9520 // and will try to pull it into namespace std with a using-declaration.
9521 // Just ignore the using-declaration in that case.
9522 auto *II = NameInfo.getName().getAsIdentifierInfo();
9523 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
9524 CurContext->isStdNamespace() &&
9525 isa<TranslationUnitDecl>(LookupContext) &&
9526 getSourceManager().isInSystemHeader(UsingLoc))
9527 return nullptr;
Kaelyn Takata89c881b2014-10-27 18:07:29 +00009528 if (TypoCorrection Corrected = CorrectTypo(
9529 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
9530 llvm::make_unique<UsingValidatorCCC>(
9531 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
9532 dyn_cast<CXXRecordDecl>(CurContext)),
9533 CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00009534 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009535 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00009536 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
9537 << NameInfo.getName() << LookupContext << 0
9538 << SS.getRange());
Richard Smith09d5b3a2014-05-01 00:35:04 +00009539
Benjamin Kramerae65d222017-01-24 12:49:59 +00009540 // If we picked a correction with no attached Decl we can't do anything
9541 // useful with it, bail out.
9542 NamedDecl *ND = Corrected.getCorrectionDecl();
9543 if (!ND)
9544 return BuildInvalid();
9545
Richard Smith09d5b3a2014-05-01 00:35:04 +00009546 // If we corrected to an inheriting constructor, handle it as one.
9547 auto *RD = dyn_cast<CXXRecordDecl>(ND);
9548 if (RD && RD->isInjectedClassName()) {
Richard Smith5179eb72016-06-28 19:03:57 +00009549 // The parent of the injected class name is the class itself.
9550 RD = cast<CXXRecordDecl>(RD->getParent());
9551
Richard Smith09d5b3a2014-05-01 00:35:04 +00009552 // Fix up the information we'll use to build the using declaration.
9553 if (Corrected.WillReplaceSpecifier()) {
9554 NestedNameSpecifierLocBuilder Builder;
9555 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
9556 QualifierLoc.getSourceRange());
9557 QualifierLoc = Builder.getWithLocInContext(Context);
9558 }
9559
Richard Smith5179eb72016-06-28 19:03:57 +00009560 // In this case, the name we introduce is the name of a derived class
9561 // constructor.
9562 auto *CurClass = cast<CXXRecordDecl>(CurContext);
9563 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9564 Context.getCanonicalType(Context.getRecordType(CurClass))));
9565 UsingName.setNamedTypeInfo(nullptr);
Richard Smith78163e22015-04-01 19:31:06 +00009566 for (auto *Ctor : LookupConstructors(RD))
9567 R.addDecl(Ctor);
Richard Smith5179eb72016-06-28 19:03:57 +00009568 R.resolveKind();
Richard Smith78163e22015-04-01 19:31:06 +00009569 } else {
Richard Smith5179eb72016-06-28 19:03:57 +00009570 // FIXME: Pick up all the declarations if we found an overloaded
9571 // function.
9572 UsingName.setName(ND->getDeclName());
Richard Smith78163e22015-04-01 19:31:06 +00009573 R.addDecl(ND);
Richard Smith09d5b3a2014-05-01 00:35:04 +00009574 }
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009575 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00009576 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009577 << NameInfo.getName() << LookupContext << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00009578 return BuildInvalid();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009579 }
Douglas Gregorfec52632009-06-20 00:51:54 +00009580 }
9581
Richard Smith09d5b3a2014-05-01 00:35:04 +00009582 if (R.isAmbiguous())
9583 return BuildInvalid();
Mike Stump11289f42009-09-09 15:08:12 +00009584
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009585 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00009586 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00009587 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00009588 Diag(IdentLoc, diag::err_using_typename_non_type);
9589 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9590 Diag((*I)->getUnderlyingDecl()->getLocation(),
9591 diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00009592 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00009593 }
9594 } else {
9595 // If we asked for a non-typename and we got a type, error out,
9596 // but only if this is an instantiation of an unresolved using
9597 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00009598 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00009599 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
9600 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00009601 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00009602 }
Anders Carlsson59140b32009-08-28 03:16:11 +00009603 }
9604
Richard Smith5cbeb752016-05-05 02:13:49 +00009605 // C++14 [namespace.udecl]p6:
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00009606 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00009607 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00009608 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
9609 << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00009610 return BuildInvalid();
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00009611 }
Mike Stump11289f42009-09-09 15:08:12 +00009612
Richard Smith5cbeb752016-05-05 02:13:49 +00009613 // C++14 [namespace.udecl]p7:
9614 // A using-declaration shall not name a scoped enumerator.
9615 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
9616 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
9617 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
9618 << SS.getRange();
9619 return BuildInvalid();
9620 }
9621 }
9622
Richard Smith09d5b3a2014-05-01 00:35:04 +00009623 UsingDecl *UD = BuildValid();
Richard Smith78163e22015-04-01 19:31:06 +00009624
Richard Smith5179eb72016-06-28 19:03:57 +00009625 // Some additional rules apply to inheriting constructors.
9626 if (UsingName.getName().getNameKind() ==
9627 DeclarationName::CXXConstructorName) {
Richard Smith78163e22015-04-01 19:31:06 +00009628 // Suppress access diagnostics; the access check is instead performed at the
9629 // point of use for an inheriting constructor.
9630 R.suppressDiagnostics();
Richard Smith5179eb72016-06-28 19:03:57 +00009631 if (CheckInheritingConstructorUsingDecl(UD))
9632 return UD;
Richard Smith78163e22015-04-01 19:31:06 +00009633 }
9634
John McCall84d87672009-12-10 09:41:52 +00009635 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00009636 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00009637 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
9638 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00009639 }
John McCall3f746822009-11-17 05:59:44 +00009640
9641 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00009642}
9643
Richard Smith151c4562016-12-20 21:35:28 +00009644NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
9645 ArrayRef<NamedDecl *> Expansions) {
9646 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
9647 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
9648 isa<UsingPackDecl>(InstantiatedFrom));
9649
9650 auto *UPD =
9651 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
9652 UPD->setAccess(InstantiatedFrom->getAccess());
9653 CurContext->addDecl(UPD);
9654 return UPD;
9655}
9656
Sebastian Redl08905022011-02-05 19:23:19 +00009657/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00009658bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009659 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00009660
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009661 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00009662 assert(SourceType &&
9663 "Using decl naming constructor doesn't have type in scope spec.");
9664 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
9665
9666 // Check whether the named type is a direct base class.
Richard Smith09d5b3a2014-05-01 00:35:04 +00009667 bool AnyDependentBases = false;
9668 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
9669 AnyDependentBases);
9670 if (!Base && !AnyDependentBases) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009671 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00009672 diag::err_using_decl_constructor_not_in_direct_base)
9673 << UD->getNameInfo().getSourceRange()
9674 << QualType(SourceType, 0) << TargetClass;
Richard Smith09d5b3a2014-05-01 00:35:04 +00009675 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00009676 return true;
9677 }
9678
Richard Smith09d5b3a2014-05-01 00:35:04 +00009679 if (Base)
9680 Base->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00009681
9682 return false;
9683}
9684
John McCall84d87672009-12-10 09:41:52 +00009685/// Checks that the given using declaration is not an invalid
9686/// redeclaration. Note that this is checking only for the using decl
9687/// itself, not for any ill-formedness among the UsingShadowDecls.
9688bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009689 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00009690 const CXXScopeSpec &SS,
9691 SourceLocation NameLoc,
9692 const LookupResult &Prev) {
Richard Smith4eeaec42016-12-18 22:01:46 +00009693 NestedNameSpecifier *Qual = SS.getScopeRep();
9694
John McCall84d87672009-12-10 09:41:52 +00009695 // C++03 [namespace.udecl]p8:
9696 // C++0x [namespace.udecl]p10:
9697 // A using-declaration is a declaration and can therefore be used
9698 // repeatedly where (and only where) multiple declarations are
9699 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00009700 //
John McCall032092f2010-11-29 18:01:58 +00009701 // That's in non-member contexts.
Richard Smith4eeaec42016-12-18 22:01:46 +00009702 if (!CurContext->getRedeclContext()->isRecord()) {
9703 // A dependent qualifier outside a class can only ever resolve to an
9704 // enumeration type. Therefore it conflicts with any other non-type
9705 // declaration in the same scope.
9706 // FIXME: How should we check for dependent type-type conflicts at block
9707 // scope?
9708 if (Qual->isDependent() && !HasTypenameKeyword) {
9709 for (auto *D : Prev) {
Richard Smith151c4562016-12-20 21:35:28 +00009710 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
Richard Smith4eeaec42016-12-18 22:01:46 +00009711 bool OldCouldBeEnumerator =
9712 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
9713 Diag(NameLoc,
9714 OldCouldBeEnumerator ? diag::err_redefinition
9715 : diag::err_redefinition_different_kind)
9716 << Prev.getLookupName();
9717 Diag(D->getLocation(), diag::note_previous_definition);
9718 return true;
9719 }
9720 }
9721 }
John McCall84d87672009-12-10 09:41:52 +00009722 return false;
Richard Smith4eeaec42016-12-18 22:01:46 +00009723 }
John McCall84d87672009-12-10 09:41:52 +00009724
9725 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
9726 NamedDecl *D = *I;
9727
9728 bool DTypename;
9729 NestedNameSpecifier *DQual;
9730 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009731 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009732 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00009733 } else if (UnresolvedUsingValueDecl *UD
9734 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
9735 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009736 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00009737 } else if (UnresolvedUsingTypenameDecl *UD
9738 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
9739 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009740 DQual = UD->getQualifier();
Richard Smith4eeaec42016-12-18 22:01:46 +00009741 } else continue;
John McCall84d87672009-12-10 09:41:52 +00009742
9743 // using decls differ if one says 'typename' and the other doesn't.
9744 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009745 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00009746
9747 // using decls differ if they name different scopes (but note that
9748 // template instantiation can cause this check to trigger when it
9749 // didn't before instantiation).
9750 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
9751 Context.getCanonicalNestedNameSpecifier(DQual))
9752 continue;
9753
9754 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00009755 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00009756 return true;
9757 }
9758
9759 return false;
9760}
9761
John McCall3969e302009-12-08 07:46:18 +00009762
John McCallb96ec562009-12-04 22:46:56 +00009763/// Checks that the given nested-name qualifier used in a using decl
9764/// in the current context is appropriately related to the current
9765/// scope. If an error is found, diagnoses it and returns true.
9766bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
Richard Smithd8a9e372016-12-18 21:39:37 +00009767 bool HasTypename,
John McCallb96ec562009-12-04 22:46:56 +00009768 const CXXScopeSpec &SS,
Richard Smith7ad0b882014-04-02 21:44:35 +00009769 const DeclarationNameInfo &NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00009770 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00009771 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00009772
John McCall3969e302009-12-08 07:46:18 +00009773 if (!CurContext->isRecord()) {
9774 // C++03 [namespace.udecl]p3:
9775 // C++0x [namespace.udecl]p8:
9776 // A using-declaration for a class member shall be a member-declaration.
9777
Richard Smithd8a9e372016-12-18 21:39:37 +00009778 // If we weren't able to compute a valid scope, it might validly be a
9779 // dependent class scope or a dependent enumeration unscoped scope. If
9780 // we have a 'typename' keyword, the scope must resolve to a class type.
9781 if ((HasTypename && !NamedContext) ||
9782 (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
Richard Smith5cbeb752016-05-05 02:13:49 +00009783 auto *RD = NamedContext
9784 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
9785 : nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00009786 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
Craig Topperc3ec1492014-05-26 06:22:03 +00009787 RD = nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00009788
John McCall3969e302009-12-08 07:46:18 +00009789 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
9790 << SS.getRange();
Richard Smith7ad0b882014-04-02 21:44:35 +00009791
9792 // If we have a complete, non-dependent source type, try to suggest a
9793 // way to get the same effect.
9794 if (!RD)
9795 return true;
9796
9797 // Find what this using-declaration was referring to.
9798 LookupResult R(*this, NameInfo, LookupOrdinaryName);
9799 R.setHideTags(false);
9800 R.suppressDiagnostics();
9801 LookupQualifiedName(R, RD);
9802
9803 if (R.getAsSingle<TypeDecl>()) {
9804 if (getLangOpts().CPlusPlus11) {
9805 // Convert 'using X::Y;' to 'using Y = X::Y;'.
9806 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
9807 << 0 // alias declaration
9808 << FixItHint::CreateInsertion(SS.getBeginLoc(),
9809 NameInfo.getName().getAsString() +
9810 " = ");
9811 } else {
9812 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
9813 SourceLocation InsertLoc =
Craig Topper07fa1762015-11-15 02:31:46 +00009814 getLocForEndOfToken(NameInfo.getLocEnd());
Richard Smith7ad0b882014-04-02 21:44:35 +00009815 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
9816 << 1 // typedef declaration
9817 << FixItHint::CreateReplacement(UsingLoc, "typedef")
9818 << FixItHint::CreateInsertion(
9819 InsertLoc, " " + NameInfo.getName().getAsString());
9820 }
9821 } else if (R.getAsSingle<VarDecl>()) {
9822 // Don't provide a fixit outside C++11 mode; we don't want to suggest
9823 // repeating the type of the static data member here.
9824 FixItHint FixIt;
9825 if (getLangOpts().CPlusPlus11) {
9826 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9827 FixIt = FixItHint::CreateReplacement(
9828 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
9829 }
9830
9831 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9832 << 2 // reference declaration
9833 << FixIt;
Richard Smithdce10ea2016-05-05 19:16:15 +00009834 } else if (R.getAsSingle<EnumConstantDecl>()) {
9835 // Don't provide a fixit outside C++11 mode; we don't want to suggest
9836 // repeating the type of the enumeration here, and we can't do so if
9837 // the type is anonymous.
9838 FixItHint FixIt;
9839 if (getLangOpts().CPlusPlus11) {
9840 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9841 FixIt = FixItHint::CreateReplacement(
Richard Smithd8a9e372016-12-18 21:39:37 +00009842 UsingLoc,
9843 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
Richard Smithdce10ea2016-05-05 19:16:15 +00009844 }
9845
9846 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9847 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
9848 << FixIt;
Richard Smith7ad0b882014-04-02 21:44:35 +00009849 }
John McCall3969e302009-12-08 07:46:18 +00009850 return true;
9851 }
9852
Richard Smithd8a9e372016-12-18 21:39:37 +00009853 // Otherwise, this might be valid.
John McCall3969e302009-12-08 07:46:18 +00009854 return false;
9855 }
9856
9857 // The current scope is a record.
9858
9859 // If the named context is dependent, we can't decide much.
9860 if (!NamedContext) {
9861 // FIXME: in C++0x, we can diagnose if we can prove that the
9862 // nested-name-specifier does not refer to a base class, which is
9863 // still possible in some cases.
9864
9865 // Otherwise we have to conservatively report that things might be
9866 // okay.
9867 return false;
9868 }
9869
9870 if (!NamedContext->isRecord()) {
9871 // Ideally this would point at the last name in the specifier,
9872 // but we don't have that level of source info.
9873 Diag(SS.getRange().getBegin(),
9874 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00009875 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00009876 return true;
9877 }
9878
Douglas Gregor7c842292010-12-21 07:41:49 +00009879 if (!NamedContext->isDependentContext() &&
9880 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
9881 return true;
9882
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009883 if (getLangOpts().CPlusPlus11) {
Richard Smith5cbeb752016-05-05 02:13:49 +00009884 // C++11 [namespace.udecl]p3:
John McCall3969e302009-12-08 07:46:18 +00009885 // In a using-declaration used as a member-declaration, the
9886 // nested-name-specifier shall name a base class of the class
9887 // being defined.
9888
9889 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
9890 cast<CXXRecordDecl>(NamedContext))) {
9891 if (CurContext == NamedContext) {
9892 Diag(NameLoc,
9893 diag::err_using_decl_nested_name_specifier_is_current_class)
9894 << SS.getRange();
9895 return true;
9896 }
9897
Eric Fiselier7ae80c62016-10-10 14:26:40 +00009898 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
9899 Diag(SS.getRange().getBegin(),
9900 diag::err_using_decl_nested_name_specifier_is_not_base_class)
9901 << SS.getScopeRep()
9902 << cast<CXXRecordDecl>(CurContext)
9903 << SS.getRange();
9904 }
John McCall3969e302009-12-08 07:46:18 +00009905 return true;
9906 }
9907
9908 return false;
9909 }
9910
9911 // C++03 [namespace.udecl]p4:
9912 // A using-declaration used as a member-declaration shall refer
9913 // to a member of a base class of the class being defined [etc.].
9914
9915 // Salient point: SS doesn't have to name a base class as long as
9916 // lookup only finds members from base classes. Therefore we can
9917 // diagnose here only if we can prove that that can't happen,
9918 // i.e. if the class hierarchies provably don't intersect.
9919
9920 // TODO: it would be nice if "definitely valid" results were cached
9921 // in the UsingDecl and UsingShadowDecl so that these checks didn't
9922 // need to be repeated.
9923
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00009924 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
9925 auto Collect = [&Bases](const CXXRecordDecl *Base) {
9926 Bases.insert(Base);
9927 return true;
John McCall3969e302009-12-08 07:46:18 +00009928 };
9929
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00009930 // Collect all bases. Return false if we find a dependent base.
9931 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
John McCall3969e302009-12-08 07:46:18 +00009932 return false;
9933
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00009934 // Returns true if the base is dependent or is one of the accumulated base
9935 // classes.
9936 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
9937 return !Bases.count(Base);
9938 };
9939
9940 // Return false if the class has a dependent base or if it or one
John McCall3969e302009-12-08 07:46:18 +00009941 // of its bases is present in the base set of the current context.
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00009942 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
9943 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
John McCall3969e302009-12-08 07:46:18 +00009944 return false;
9945
9946 Diag(SS.getRange().getBegin(),
9947 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00009948 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00009949 << cast<CXXRecordDecl>(CurContext)
9950 << SS.getRange();
9951
9952 return true;
John McCallb96ec562009-12-04 22:46:56 +00009953}
9954
Richard Smithdda56e42011-04-15 14:24:37 +00009955Decl *Sema::ActOnAliasDeclaration(Scope *S,
9956 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00009957 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00009958 SourceLocation UsingLoc,
9959 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00009960 AttributeList *AttrList,
David Majnemerf9bde282015-03-11 06:45:39 +00009961 TypeResult Type,
9962 Decl *DeclFromDeclSpec) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00009963 // Skip up to the relevant declaration scope.
Davide Italiano5be22332015-11-11 20:06:35 +00009964 while (S->isTemplateParamScope())
Richard Smith3f1b5d02011-05-05 21:57:07 +00009965 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00009966 assert((S->getFlags() & Scope::DeclScope) &&
9967 "got alias-declaration outside of declaration scope");
9968
9969 if (Type.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00009970 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00009971
9972 bool Invalid = false;
9973 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
Craig Topperc3ec1492014-05-26 06:22:03 +00009974 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky82e47802011-05-02 01:07:19 +00009975 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00009976
9977 if (DiagnoseClassNameShadow(CurContext, NameInfo))
Craig Topperc3ec1492014-05-26 06:22:03 +00009978 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00009979
9980 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00009981 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00009982 Invalid = true;
Erich Keanebb863642017-09-20 22:28:24 +00009983 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
Richard Smith3f1b5d02011-05-05 21:57:07 +00009984 TInfo->getTypeLoc().getBeginLoc());
9985 }
Richard Smithdda56e42011-04-15 14:24:37 +00009986
Richard Smithbecb92d2017-10-10 22:33:17 +00009987 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9988 TemplateParamLists.size()
9989 ? forRedeclarationInCurContext()
9990 : ForVisibleRedeclaration);
Richard Smithdda56e42011-04-15 14:24:37 +00009991 LookupName(Previous, S);
9992
9993 // Warn about shadowing the name of a template parameter.
9994 if (Previous.isSingleResult() &&
9995 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00009996 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00009997 Previous.clear();
9998 }
9999
10000 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
10001 "name in alias declaration must be an identifier");
10002 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
10003 Name.StartLocation,
10004 Name.Identifier, TInfo);
10005
10006 NewTD->setAccess(AS);
10007
10008 if (Invalid)
10009 NewTD->setInvalidDecl();
10010
Richard Smith54ecd982013-02-20 19:22:51 +000010011 ProcessDeclAttributeList(S, NewTD, AttrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +000010012 AddPragmaAttributes(S, NewTD);
Richard Smith54ecd982013-02-20 19:22:51 +000010013
Richard Smith3f1b5d02011-05-05 21:57:07 +000010014 CheckTypedefForVariablyModifiedType(S, NewTD);
10015 Invalid |= NewTD->isInvalidDecl();
10016
Richard Smithdda56e42011-04-15 14:24:37 +000010017 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +000010018
10019 NamedDecl *NewND;
10020 if (TemplateParamLists.size()) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010021 TypeAliasTemplateDecl *OldDecl = nullptr;
10022 TemplateParameterList *OldTemplateParams = nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +000010023
10024 if (TemplateParamLists.size() != 1) {
10025 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010026 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
10027 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +000010028 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +000010029 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +000010030
Richard Smith882593f2016-04-06 17:38:58 +000010031 // Check that we can declare a template here.
10032 if (CheckTemplateDeclScope(S, TemplateParams))
10033 return nullptr;
10034
Richard Smith3f1b5d02011-05-05 21:57:07 +000010035 // Only consider previous declarations in the same scope.
10036 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
10037 /*ExplicitInstantiationOrSpecialization*/false);
10038 if (!Previous.empty()) {
10039 Redeclaration = true;
10040
10041 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
10042 if (!OldDecl && !Invalid) {
10043 Diag(UsingLoc, diag::err_redefinition_different_kind)
10044 << Name.Identifier;
10045
10046 NamedDecl *OldD = Previous.getRepresentativeDecl();
10047 if (OldD->getLocation().isValid())
10048 Diag(OldD->getLocation(), diag::note_previous_definition);
10049
10050 Invalid = true;
10051 }
10052
10053 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
10054 if (TemplateParameterListsAreEqual(TemplateParams,
10055 OldDecl->getTemplateParameters(),
10056 /*Complain=*/true,
10057 TPL_TemplateMatch))
10058 OldTemplateParams = OldDecl->getTemplateParameters();
10059 else
10060 Invalid = true;
10061
10062 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
10063 if (!Invalid &&
10064 !Context.hasSameType(OldTD->getUnderlyingType(),
10065 NewTD->getUnderlyingType())) {
10066 // FIXME: The C++0x standard does not clearly say this is ill-formed,
10067 // but we can't reasonably accept it.
10068 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10069 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10070 if (OldTD->getLocation().isValid())
10071 Diag(OldTD->getLocation(), diag::note_previous_definition);
10072 Invalid = true;
10073 }
10074 }
10075 }
10076
10077 // Merge any previous default template arguments into our parameters,
10078 // and check the parameter list.
10079 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10080 TPC_TypeAliasTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +000010081 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +000010082
10083 TypeAliasTemplateDecl *NewDecl =
10084 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10085 Name.Identifier, TemplateParams,
10086 NewTD);
Richard Smith43ccec8e2014-08-26 03:52:16 +000010087 NewTD->setDescribedAliasTemplate(NewDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +000010088
10089 NewDecl->setAccess(AS);
10090
10091 if (Invalid)
10092 NewDecl->setInvalidDecl();
Richard Smithbecb92d2017-10-10 22:33:17 +000010093 else if (OldDecl) {
Rafael Espindola8db352d2013-10-17 15:37:26 +000010094 NewDecl->setPreviousDecl(OldDecl);
Richard Smithbecb92d2017-10-10 22:33:17 +000010095 CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
10096 }
Richard Smith3f1b5d02011-05-05 21:57:07 +000010097
10098 NewND = NewDecl;
10099 } else {
David Majnemerf9bde282015-03-11 06:45:39 +000010100 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10101 setTagNameForLinkagePurposes(TD, NewTD);
10102 handleTagNumbering(TD, S);
10103 }
Richard Smith3f1b5d02011-05-05 21:57:07 +000010104 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10105 NewND = NewTD;
10106 }
Richard Smithdda56e42011-04-15 14:24:37 +000010107
Richard Smith3cbf3f12016-07-15 20:53:25 +000010108 PushOnScopeChains(NewND, S);
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +000010109 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +000010110 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +000010111}
10112
Richard Smithf4634362014-09-03 23:11:22 +000010113Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10114 SourceLocation AliasLoc,
10115 IdentifierInfo *Alias, CXXScopeSpec &SS,
10116 SourceLocation IdentLoc,
10117 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +000010118
Anders Carlssonbb1e4722009-03-28 23:53:49 +000010119 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +000010120 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10121 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +000010122
John McCall27b18f82009-11-17 02:14:36 +000010123 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +000010124 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +000010125
John McCall9f3059a2009-10-09 21:13:30 +000010126 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +000010127 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +000010128 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000010129 return nullptr;
Douglas Gregor9629e9a2010-06-29 18:55:19 +000010130 }
Anders Carlssonac2c9652009-03-28 06:42:02 +000010131 }
Richard Smithf4634362014-09-03 23:11:22 +000010132 assert(!R.isAmbiguous() && !R.empty());
Richard Smithf2005d32015-12-29 23:34:32 +000010133 NamedDecl *ND = R.getRepresentativeDecl();
Richard Smithf4634362014-09-03 23:11:22 +000010134
10135 // Check if we have a previous declaration with the same name.
Richard Smith10568d82015-11-17 03:02:41 +000010136 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +000010137 ForVisibleRedeclaration);
Richard Smith2b2a1762015-12-03 23:24:04 +000010138 LookupName(PrevR, S);
Richard Smithf4634362014-09-03 23:11:22 +000010139
Richard Smith2b2a1762015-12-03 23:24:04 +000010140 // Check we're not shadowing a template parameter.
10141 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10142 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10143 PrevR.clear();
10144 }
Aaron Ballman43f40102014-11-14 22:34:56 +000010145
Richard Smith2b2a1762015-12-03 23:24:04 +000010146 // Filter out any other lookup result from an enclosing scope.
10147 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10148 /*AllowInlineNamespace*/false);
10149
10150 // Find the previous declaration and check that we can redeclare it.
Erich Keanebb863642017-09-20 22:28:24 +000010151 NamespaceAliasDecl *Prev = nullptr;
Richard Smith7d8d6722015-12-29 23:42:34 +000010152 if (PrevR.isSingleResult()) {
10153 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10154 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Richard Smithf4634362014-09-03 23:11:22 +000010155 // We already have an alias with the same name that points to the same
10156 // namespace; check that it matches.
Richard Smith2b2a1762015-12-03 23:24:04 +000010157 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10158 Prev = AD;
10159 } else if (isVisible(PrevDecl)) {
Richard Smithf4634362014-09-03 23:11:22 +000010160 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10161 << Alias;
Richard Smithf2005d32015-12-29 23:34:32 +000010162 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
Richard Smithf4634362014-09-03 23:11:22 +000010163 << AD->getNamespace();
10164 return nullptr;
10165 }
Richard Smith2b2a1762015-12-03 23:24:04 +000010166 } else if (isVisible(PrevDecl)) {
Richard Smith7d8d6722015-12-29 23:42:34 +000010167 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
Richard Smithf4634362014-09-03 23:11:22 +000010168 ? diag::err_redefinition
10169 : diag::err_redefinition_different_kind;
10170 Diag(AliasLoc, DiagID) << Alias;
10171 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10172 return nullptr;
10173 }
10174 }
Mike Stump11289f42009-09-09 15:08:12 +000010175
Nico Riecke50e59a2014-11-24 17:29:52 +000010176 // The use of a nested name specifier may trigger deprecation warnings.
Aaron Ballman43f40102014-11-14 22:34:56 +000010177 DiagnoseUseOfDecl(ND, IdentLoc);
10178
Fariborz Jahanian423a81f2009-06-19 19:55:27 +000010179 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +000010180 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +000010181 Alias, SS.getWithLocInContext(Context),
Aaron Ballman43f40102014-11-14 22:34:56 +000010182 IdentLoc, ND);
Richard Smith2b2a1762015-12-03 23:24:04 +000010183 if (Prev)
10184 AliasDecl->setPreviousDecl(Prev);
Mike Stump11289f42009-09-09 15:08:12 +000010185
John McCalld8d0d432010-02-16 06:53:13 +000010186 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +000010187 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +000010188}
10189
Richard Smith2246c832017-02-24 01:29:42 +000010190namespace {
Richard Smith8bae1be2017-02-24 02:07:20 +000010191struct SpecialMemberExceptionSpecInfo
10192 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
Richard Smith2246c832017-02-24 01:29:42 +000010193 SourceLocation Loc;
10194 Sema::ImplicitExceptionSpecification ExceptSpec;
10195
Richard Smith2246c832017-02-24 01:29:42 +000010196 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10197 Sema::CXXSpecialMember CSM,
10198 Sema::InheritedConstructorInfo *ICI,
10199 SourceLocation Loc)
Richard Smith8bae1be2017-02-24 02:07:20 +000010200 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
Richard Smith2246c832017-02-24 01:29:42 +000010201
Richard Smith6f0e63e2017-02-24 21:18:47 +000010202 bool visitBase(CXXBaseSpecifier *Base);
10203 bool visitField(FieldDecl *FD);
Richard Smith2246c832017-02-24 01:29:42 +000010204
10205 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10206 unsigned Quals);
10207
10208 void visitSubobjectCall(Subobject Subobj,
Richard Smith8bae1be2017-02-24 02:07:20 +000010209 Sema::SpecialMemberOverloadResult SMOR);
Richard Smith2246c832017-02-24 01:29:42 +000010210};
10211}
10212
Richard Smith6f0e63e2017-02-24 21:18:47 +000010213bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
Richard Smith2246c832017-02-24 01:29:42 +000010214 auto *RT = Base->getType()->getAs<RecordType>();
10215 if (!RT)
Richard Smith6f0e63e2017-02-24 21:18:47 +000010216 return false;
Richard Smith2246c832017-02-24 01:29:42 +000010217
10218 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
Richard Smith6f0e63e2017-02-24 21:18:47 +000010219 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10220 if (auto *BaseCtor = SMOR.getMethod()) {
10221 visitSubobjectCall(Base, BaseCtor);
10222 return false;
Richard Smith2246c832017-02-24 01:29:42 +000010223 }
10224
10225 visitClassSubobject(BaseClass, Base, 0);
Richard Smith6f0e63e2017-02-24 21:18:47 +000010226 return false;
Richard Smith2246c832017-02-24 01:29:42 +000010227}
10228
Richard Smith6f0e63e2017-02-24 21:18:47 +000010229bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
Richard Smith2246c832017-02-24 01:29:42 +000010230 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10231 Expr *E = FD->getInClassInitializer();
10232 if (!E)
10233 // FIXME: It's a little wasteful to build and throw away a
10234 // CXXDefaultInitExpr here.
10235 // FIXME: We should have a single context note pointing at Loc, and
10236 // this location should be MD->getLocation() instead, since that's
10237 // the location where we actually use the default init expression.
10238 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10239 if (E)
10240 ExceptSpec.CalledExpr(E);
10241 } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10242 ->getAs<RecordType>()) {
10243 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10244 FD->getType().getCVRQualifiers());
10245 }
Richard Smith6f0e63e2017-02-24 21:18:47 +000010246 return false;
Richard Smith2246c832017-02-24 01:29:42 +000010247}
10248
10249void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10250 Subobject Subobj,
10251 unsigned Quals) {
10252 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10253 bool IsMutable = Field && Field->isMutable();
10254 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10255}
10256
10257void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
Richard Smith8bae1be2017-02-24 02:07:20 +000010258 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
Richard Smith2246c832017-02-24 01:29:42 +000010259 // Note, if lookup fails, it doesn't matter what exception specification we
10260 // choose because the special member will be deleted.
Richard Smith8bae1be2017-02-24 02:07:20 +000010261 if (CXXMethodDecl *MD = SMOR.getMethod())
10262 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
Richard Smith2246c832017-02-24 01:29:42 +000010263}
10264
10265static Sema::ImplicitExceptionSpecification
10266ComputeDefaultedSpecialMemberExceptionSpec(
10267 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
10268 Sema::InheritedConstructorInfo *ICI) {
Richard Smithd3b5c9082012-07-27 04:22:15 +000010269 CXXRecordDecl *ClassDecl = MD->getParent();
10270
Douglas Gregor6d880b12010-07-01 22:31:05 +000010271 // C++ [except.spec]p14:
Erich Keanebb863642017-09-20 22:28:24 +000010272 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor6d880b12010-07-01 22:31:05 +000010273 // exception-specification. [...]
Richard Smith2246c832017-02-24 01:29:42 +000010274 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, Loc);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +000010275 if (ClassDecl->isInvalidDecl())
Richard Smith2246c832017-02-24 01:29:42 +000010276 return Info.ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +000010277
Richard Smith6f0e63e2017-02-24 21:18:47 +000010278 // C++1z [except.spec]p7:
10279 // [Look for exceptions thrown by] a constructor selected [...] to
10280 // initialize a potentially constructed subobject,
10281 // C++1z [except.spec]p8:
10282 // The exception specification for an implicitly-declared destructor, or a
10283 // destructor without a noexcept-specifier, is potentially-throwing if and
10284 // only if any of the destructors for any of its potentially constructed
10285 // subojects is potentially throwing.
Richard Smithdf054d32017-02-25 23:53:05 +000010286 // FIXME: We respect the first rule but ignore the "potentially constructed"
10287 // in the second rule to resolve a core issue (no number yet) that would have
10288 // us reject:
Richard Smith6f0e63e2017-02-24 21:18:47 +000010289 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
10290 // struct B : A {};
10291 // struct C : B { void f(); };
10292 // ... due to giving B::~B() a non-throwing exception specification.
Richard Smithdf054d32017-02-25 23:53:05 +000010293 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
10294 : Info.VisitAllBases);
John McCalldb40c7f2010-12-14 08:05:40 +000010295
Richard Smith2246c832017-02-24 01:29:42 +000010296 return Info.ExceptSpec;
Richard Smithc2bc61b2013-03-18 21:12:30 +000010297}
10298
Richard Smith8bf22e52012-11-29 01:34:07 +000010299namespace {
10300/// RAII object to register a special member as being currently declared.
10301struct DeclaringSpecialMember {
10302 Sema &S;
10303 Sema::SpecialMemberDecl D;
Richard Smith12e79312016-05-13 06:47:56 +000010304 Sema::ContextRAII SavedContext;
Richard Smith8bf22e52012-11-29 01:34:07 +000010305 bool WasAlreadyBeingDeclared;
10306
10307 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
Richard Smith13381222017-02-23 21:43:43 +000010308 : S(S), D(RD, CSM), SavedContext(S, RD) {
David Blaikie82e95a32014-11-19 07:49:47 +000010309 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
Richard Smith8bf22e52012-11-29 01:34:07 +000010310 if (WasAlreadyBeingDeclared)
10311 // This almost never happens, but if it does, ensure that our cache
10312 // doesn't contain a stale result.
10313 S.SpecialMemberCache.clear();
Richard Smith13381222017-02-23 21:43:43 +000010314 else {
10315 // Register a note to be produced if we encounter an error while
10316 // declaring the special member.
10317 Sema::CodeSynthesisContext Ctx;
10318 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
10319 // FIXME: We don't have a location to use here. Using the class's
10320 // location maintains the fiction that we declare all special members
10321 // with the class, but (1) it's not clear that lying about that helps our
10322 // users understand what's going on, and (2) there may be outer contexts
10323 // on the stack (some of which are relevant) and printing them exposes
10324 // our lies.
10325 Ctx.PointOfInstantiation = RD->getLocation();
10326 Ctx.Entity = RD;
10327 Ctx.SpecialMember = CSM;
10328 S.pushCodeSynthesisContext(Ctx);
10329 }
Richard Smith8bf22e52012-11-29 01:34:07 +000010330 }
10331 ~DeclaringSpecialMember() {
Richard Smith13381222017-02-23 21:43:43 +000010332 if (!WasAlreadyBeingDeclared) {
Richard Smith8bf22e52012-11-29 01:34:07 +000010333 S.SpecialMembersBeingDeclared.erase(D);
Richard Smith13381222017-02-23 21:43:43 +000010334 S.popCodeSynthesisContext();
10335 }
Richard Smith8bf22e52012-11-29 01:34:07 +000010336 }
10337
10338 /// \brief Are we already trying to declare this special member?
10339 bool isAlreadyBeingDeclared() const {
10340 return WasAlreadyBeingDeclared;
10341 }
10342};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010343}
Richard Smith8bf22e52012-11-29 01:34:07 +000010344
Richard Smith12e79312016-05-13 06:47:56 +000010345void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10346 // Look up any existing declarations, but don't trigger declaration of all
10347 // implicit special members with this name.
10348 DeclarationName Name = FD->getDeclName();
10349 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +000010350 ForExternalRedeclaration);
Richard Smith12e79312016-05-13 06:47:56 +000010351 for (auto *D : FD->getParent()->lookup(Name))
10352 if (auto *Acceptable = R.getAcceptableDecl(D))
10353 R.addDecl(Acceptable);
10354 R.resolveKind();
Richard Smitha87b7662016-05-13 18:48:05 +000010355 R.suppressDiagnostics();
Richard Smith12e79312016-05-13 06:47:56 +000010356
Richard Smithf445f192017-02-09 21:04:43 +000010357 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
Richard Smith12e79312016-05-13 06:47:56 +000010358}
10359
Alexis Hunt6d5b96c2011-05-10 00:49:42 +000010360CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
10361 CXXRecordDecl *ClassDecl) {
10362 // C++ [class.ctor]p5:
10363 // A default constructor for a class X is a constructor of class X
10364 // that can be called without an argument. If there is no
10365 // user-declared constructor for class X, a default constructor is
10366 // implicitly declared. An implicitly-declared default constructor
10367 // is an inline public member of its class.
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010368 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +000010369 "Should not build implicit default constructor!");
10370
Richard Smith8bf22e52012-11-29 01:34:07 +000010371 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
10372 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010373 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010374
Richard Smithb5800092012-06-10 05:43:50 +000010375 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10376 CXXDefaultConstructor,
10377 false);
10378
Douglas Gregor6d880b12010-07-01 22:31:05 +000010379 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +000010380 CanQualType ClassType
10381 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010382 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +000010383 DeclarationName Name
10384 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +000010385 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +000010386 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010387 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
10388 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
10389 /*isImplicitlyDeclared=*/true, Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +000010390 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +000010391 DefaultCon->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010392
10393 if (getLangOpts().CUDA) {
10394 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
10395 DefaultCon,
10396 /* ConstRHS */ false,
10397 /* Diagnose */ false);
10398 }
Richard Smithd3b5c9082012-07-27 04:22:15 +000010399
10400 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +000010401 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000010402 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010403
Richard Smith6b02d462012-12-08 08:32:28 +000010404 // We don't need to use SpecialMemberIsTrivial here; triviality for default
10405 // constructors is easy to compute.
10406 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
10407
Douglas Gregor9672f922010-07-03 00:47:00 +000010408 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +000010409 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +000010410
Richard Smith12e79312016-05-13 06:47:56 +000010411 Scope *S = getScopeForContext(ClassDecl);
10412 CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
10413
10414 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
10415 SetDeclDeleted(DefaultCon, ClassLoc);
10416
10417 if (S)
Douglas Gregor9672f922010-07-03 00:47:00 +000010418 PushOnScopeChains(DefaultCon, S, false);
10419 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +000010420
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +000010421 return DefaultCon;
10422}
10423
Fariborz Jahanian423a81f2009-06-19 19:55:27 +000010424void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
10425 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +000010426 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +000010427 !Constructor->doesThisDeclarationHaveABody() &&
10428 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +000010429 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Richard Smith883dbc42017-05-25 22:47:05 +000010430 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
10431 return;
Mike Stump11289f42009-09-09 15:08:12 +000010432
Anders Carlsson423f5d82010-04-23 16:04:08 +000010433 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +000010434 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +000010435
Eli Friedmaneaf34142012-10-18 20:14:08 +000010436 SynthesizedFunctionScope Scope(*this, Constructor);
Douglas Gregor73193272010-09-20 16:48:21 +000010437
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010438 // The exception specification is needed because we are defining the
10439 // function.
10440 ResolveExceptionSpec(CurrentLocation,
10441 Constructor->getType()->castAs<FunctionProtoType>());
Richard Smith883dbc42017-05-25 22:47:05 +000010442 MarkVTableUsed(CurrentLocation, ClassDecl);
10443
10444 // Add a context note for diagnostics produced after this point.
10445 Scope.addContextNote(CurrentLocation);
10446
10447 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
10448 Constructor->setInvalidDecl();
10449 return;
10450 }
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010451
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010452 SourceLocation Loc = Constructor->getLocEnd().isValid()
10453 ? Constructor->getLocEnd()
10454 : Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +000010455 Constructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +000010456 Constructor->markUsed(Context);
Sebastian Redlab238a72011-04-24 16:28:06 +000010457
10458 if (ASTMutationListener *L = getASTMutationListener()) {
10459 L->CompletedImplicitDefinition(Constructor);
10460 }
Richard Trieuef64e942013-10-25 00:56:00 +000010461
10462 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +000010463}
10464
Richard Smith938f40b2011-06-11 17:19:42 +000010465void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +000010466 // Perform any delayed checks on exception specifications.
10467 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +000010468}
10469
Richard Smith5179eb72016-06-28 19:03:57 +000010470/// Find or create the fake constructor we synthesize to model constructing an
10471/// object of a derived class via a constructor of a base class.
10472CXXConstructorDecl *
10473Sema::findInheritingConstructor(SourceLocation Loc,
10474 CXXConstructorDecl *BaseCtor,
10475 ConstructorUsingShadowDecl *Shadow) {
10476 CXXRecordDecl *Derived = Shadow->getParent();
10477 SourceLocation UsingLoc = Shadow->getLocation();
Richard Smith185be182013-04-10 05:48:59 +000010478
Richard Smith5179eb72016-06-28 19:03:57 +000010479 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
10480 // For now we use the name of the base class constructor as a member of the
10481 // derived class to indicate a (fake) inherited constructor name.
10482 DeclarationName Name = BaseCtor->getDeclName();
Richard Smith185be182013-04-10 05:48:59 +000010483
Richard Smith5179eb72016-06-28 19:03:57 +000010484 // Check to see if we already have a fake constructor for this inherited
10485 // constructor call.
10486 for (NamedDecl *Ctor : Derived->lookup(Name))
10487 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
10488 ->getInheritedConstructor()
10489 .getConstructor(),
10490 BaseCtor))
10491 return cast<CXXConstructorDecl>(Ctor);
Richard Smith185be182013-04-10 05:48:59 +000010492
Richard Smith5179eb72016-06-28 19:03:57 +000010493 DeclarationNameInfo NameInfo(Name, UsingLoc);
10494 TypeSourceInfo *TInfo =
10495 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
10496 FunctionProtoTypeLoc ProtoLoc =
10497 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
Richard Smith185be182013-04-10 05:48:59 +000010498
Richard Smith5179eb72016-06-28 19:03:57 +000010499 // Check the inherited constructor is valid and find the list of base classes
10500 // from which it was inherited.
10501 InheritedConstructorInfo ICI(*this, Loc, Shadow);
Richard Smith185be182013-04-10 05:48:59 +000010502
Richard Smith5179eb72016-06-28 19:03:57 +000010503 bool Constexpr =
10504 BaseCtor->isConstexpr() &&
10505 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
10506 false, BaseCtor, &ICI);
Richard Smith185be182013-04-10 05:48:59 +000010507
Richard Smith5179eb72016-06-28 19:03:57 +000010508 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
10509 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
10510 BaseCtor->isExplicit(), /*Inline=*/true,
10511 /*ImplicitlyDeclared=*/true, Constexpr,
10512 InheritedConstructor(Shadow, BaseCtor));
10513 if (Shadow->isInvalidDecl())
10514 DerivedCtor->setInvalidDecl();
Richard Smith185be182013-04-10 05:48:59 +000010515
Richard Smith5179eb72016-06-28 19:03:57 +000010516 // Build an unevaluated exception specification for this fake constructor.
10517 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
10518 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10519 EPI.ExceptionSpec.Type = EST_Unevaluated;
10520 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
10521 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
10522 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +000010523
Richard Smith5179eb72016-06-28 19:03:57 +000010524 // Build the parameter declarations.
10525 SmallVector<ParmVarDecl *, 16> ParamDecls;
10526 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +000010527 TypeSourceInfo *TInfo =
Richard Smith5179eb72016-06-28 19:03:57 +000010528 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
10529 ParmVarDecl *PD = ParmVarDecl::Create(
10530 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
10531 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
10532 PD->setScopeInfo(0, I);
10533 PD->setImplicit();
10534 // Ensure attributes are propagated onto parameters (this matters for
10535 // format, pass_object_size, ...).
10536 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
10537 ParamDecls.push_back(PD);
10538 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +000010539 }
10540
Richard Smith5179eb72016-06-28 19:03:57 +000010541 // Set up the new constructor.
10542 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
10543 DerivedCtor->setAccess(BaseCtor->getAccess());
10544 DerivedCtor->setParams(ParamDecls);
10545 Derived->addDecl(DerivedCtor);
Richard Smith80a47022016-06-29 01:10:27 +000010546
10547 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
10548 SetDeclDeleted(DerivedCtor, UsingLoc);
10549
Richard Smith5179eb72016-06-28 19:03:57 +000010550 return DerivedCtor;
Sebastian Redl08905022011-02-05 19:23:19 +000010551}
10552
Richard Smith80a47022016-06-29 01:10:27 +000010553void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
10554 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
10555 Ctor->getInheritedConstructor().getShadowDecl());
10556 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
10557 /*Diagnose*/true);
10558}
10559
Richard Smithc2bc61b2013-03-18 21:12:30 +000010560void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
10561 CXXConstructorDecl *Constructor) {
10562 CXXRecordDecl *ClassDecl = Constructor->getParent();
10563 assert(Constructor->getInheritedConstructor() &&
10564 !Constructor->doesThisDeclarationHaveABody() &&
10565 !Constructor->isDeleted());
Richard Smith883dbc42017-05-25 22:47:05 +000010566 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
Richard Smith5179eb72016-06-28 19:03:57 +000010567 return;
Richard Smithc2bc61b2013-03-18 21:12:30 +000010568
Richard Smith883dbc42017-05-25 22:47:05 +000010569 // Initializations are performed "as if by a defaulted default constructor",
10570 // so enter the appropriate scope.
10571 SynthesizedFunctionScope Scope(*this, Constructor);
10572
10573 // The exception specification is needed because we are defining the
10574 // function.
10575 ResolveExceptionSpec(CurrentLocation,
10576 Constructor->getType()->castAs<FunctionProtoType>());
10577 MarkVTableUsed(CurrentLocation, ClassDecl);
10578
10579 // Add a context note for diagnostics produced after this point.
10580 Scope.addContextNote(CurrentLocation);
10581
Richard Smith5179eb72016-06-28 19:03:57 +000010582 ConstructorUsingShadowDecl *Shadow =
10583 Constructor->getInheritedConstructor().getShadowDecl();
10584 CXXConstructorDecl *InheritedCtor =
10585 Constructor->getInheritedConstructor().getConstructor();
10586
10587 // [class.inhctor.init]p1:
10588 // initialization proceeds as if a defaulted default constructor is used to
10589 // initialize the D object and each base class subobject from which the
10590 // constructor was inherited
10591
10592 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
10593 CXXRecordDecl *RD = Shadow->getParent();
10594 SourceLocation InitLoc = Shadow->getLocation();
10595
Richard Smith5179eb72016-06-28 19:03:57 +000010596 // Build explicit initializers for all base classes from which the
10597 // constructor was inherited.
10598 SmallVector<CXXCtorInitializer*, 8> Inits;
10599 for (bool VBase : {false, true}) {
10600 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
10601 if (B.isVirtual() != VBase)
10602 continue;
10603
10604 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
10605 if (!BaseRD)
10606 continue;
10607
10608 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
10609 if (!BaseCtor.first)
10610 continue;
10611
10612 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
10613 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
10614 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
10615
10616 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
10617 Inits.push_back(new (Context) CXXCtorInitializer(
10618 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
10619 SourceLocation()));
10620 }
10621 }
10622
10623 // We now proceed as if for a defaulted default constructor, with the relevant
10624 // initializers replaced.
10625
Richard Smith883dbc42017-05-25 22:47:05 +000010626 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
Richard Smithc2bc61b2013-03-18 21:12:30 +000010627 Constructor->setInvalidDecl();
10628 return;
10629 }
10630
Richard Smith5179eb72016-06-28 19:03:57 +000010631 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
Eli Friedman276dd182013-09-05 00:02:25 +000010632 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +000010633
10634 if (ASTMutationListener *L = getASTMutationListener()) {
10635 L->CompletedImplicitDefinition(Constructor);
10636 }
Richard Smithc2bc61b2013-03-18 21:12:30 +000010637
Richard Smith5179eb72016-06-28 19:03:57 +000010638 DiagnoseUninitializedFields(*this, Constructor);
10639}
Richard Smithc2bc61b2013-03-18 21:12:30 +000010640
Alexis Huntf91729462011-05-12 22:46:25 +000010641CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
10642 // C++ [class.dtor]p2:
10643 // If a class has no user-declared destructor, a destructor is
10644 // declared implicitly. An implicitly-declared destructor is an
10645 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +000010646 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +000010647
Richard Smith8bf22e52012-11-29 01:34:07 +000010648 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
10649 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010650 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010651
Douglas Gregor7454c562010-07-02 20:37:36 +000010652 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +000010653 CanQualType ClassType
10654 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010655 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +000010656 DeclarationName Name
10657 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +000010658 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +000010659 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +000010660 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +000010661 QualType(), nullptr, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010662 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +000010663 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +000010664 Destructor->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010665
10666 if (getLangOpts().CUDA) {
10667 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
10668 Destructor,
10669 /* ConstRHS */ false,
10670 /* Diagnose */ false);
10671 }
Richard Smithd3b5c9082012-07-27 04:22:15 +000010672
10673 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +000010674 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000010675 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010676
Richard Smith6b02d462012-12-08 08:32:28 +000010677 // We don't need to use SpecialMemberIsTrivial here; triviality for
10678 // destructors is easy to compute.
10679 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
10680
Douglas Gregor7454c562010-07-02 20:37:36 +000010681 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +000010682 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +000010683
Richard Smith12e79312016-05-13 06:47:56 +000010684 Scope *S = getScopeForContext(ClassDecl);
10685 CheckImplicitSpecialMemberDeclaration(S, Destructor);
10686
Richard Smithb2f0f052016-10-10 18:54:32 +000010687 // We can't check whether an implicit destructor is deleted before we complete
10688 // the definition of the class, because its validity depends on the alignment
10689 // of the class. We'll check this from ActOnFields once the class is complete.
10690 if (ClassDecl->isCompleteDefinition() &&
10691 ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith12e79312016-05-13 06:47:56 +000010692 SetDeclDeleted(Destructor, ClassLoc);
10693
Douglas Gregor7454c562010-07-02 20:37:36 +000010694 // Introduce this destructor into its scope.
Richard Smith12e79312016-05-13 06:47:56 +000010695 if (S)
Douglas Gregor7454c562010-07-02 20:37:36 +000010696 PushOnScopeChains(Destructor, S, false);
10697 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +000010698
Douglas Gregorf1203042010-07-01 19:09:28 +000010699 return Destructor;
10700}
10701
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010702void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +000010703 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +000010704 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010705 !Destructor->doesThisDeclarationHaveABody() &&
10706 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010707 "DefineImplicitDestructor - call it for implicit default dtor");
Richard Smith883dbc42017-05-25 22:47:05 +000010708 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
10709 return;
10710
Anders Carlsson2a50e952009-11-15 22:49:34 +000010711 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010712 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010713
Eli Friedmaneaf34142012-10-18 20:14:08 +000010714 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010715
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010716 // The exception specification is needed because we are defining the
10717 // function.
10718 ResolveExceptionSpec(CurrentLocation,
10719 Destructor->getType()->castAs<FunctionProtoType>());
Richard Smith883dbc42017-05-25 22:47:05 +000010720 MarkVTableUsed(CurrentLocation, ClassDecl);
10721
10722 // Add a context note for diagnostics produced after this point.
10723 Scope.addContextNote(CurrentLocation);
10724
10725 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10726 Destructor->getParent());
10727
10728 if (CheckDestructor(Destructor)) {
10729 Destructor->setInvalidDecl();
10730 return;
10731 }
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010732
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010733 SourceLocation Loc = Destructor->getLocEnd().isValid()
10734 ? Destructor->getLocEnd()
10735 : Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +000010736 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +000010737 Destructor->markUsed(Context);
Sebastian Redlab238a72011-04-24 16:28:06 +000010738
10739 if (ASTMutationListener *L = getASTMutationListener()) {
10740 L->CompletedImplicitDefinition(Destructor);
10741 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010742}
10743
Richard Smith84973e52012-04-21 18:42:51 +000010744/// \brief Perform any semantic analysis which needs to be delayed until all
10745/// pending class member declarations have been parsed.
10746void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +000010747 // If the context is an invalid C++ class, just suppress these checks.
10748 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
10749 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +000010750 DelayedDefaultedMemberExceptionSpecs.clear();
Richard Smith88f45492014-11-22 03:09:05 +000010751 DelayedExceptionSpecChecks.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +000010752 return;
10753 }
Reid Kleckner61195e12017-01-05 01:08:22 +000010754 checkForMultipleExportedDefaultConstructors(*this, Record);
Reid Klecknerbba3cb92015-03-17 19:00:50 +000010755 }
10756}
10757
Hans Wennborg99000c22015-08-15 01:18:16 +000010758void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
Reid Kleckner5b640342016-02-26 19:51:02 +000010759 referenceDLLExportedClassMethods();
10760}
10761
10762void Sema::referenceDLLExportedClassMethods() {
Hans Wennborg99000c22015-08-15 01:18:16 +000010763 if (!DelayedDllExportClasses.empty()) {
10764 // Calling ReferenceDllExportedMethods might cause the current function to
10765 // be called again, so use a local copy of DelayedDllExportClasses.
10766 SmallVector<CXXRecordDecl *, 4> WorkList;
10767 std::swap(DelayedDllExportClasses, WorkList);
10768 for (CXXRecordDecl *Class : WorkList)
10769 ReferenceDllExportedMethods(*this, Class);
10770 }
Reid Klecknerbba3cb92015-03-17 19:00:50 +000010771}
10772
Richard Smithd3b5c9082012-07-27 04:22:15 +000010773void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
10774 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010775 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +000010776 "adjusting dtor exception specs was introduced in c++11");
10777
Sebastian Redl623ea822011-05-19 05:13:44 +000010778 // C++11 [class.dtor]p3:
10779 // A declaration of a destructor that does not have an exception-
10780 // specification is implicitly considered to have the same exception-
10781 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +000010782 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +000010783 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010784 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +000010785 return;
10786
Chandler Carruth9a797572011-09-20 04:55:26 +000010787 // Replace the destructor's type, building off the existing one. Fortunately,
10788 // the only thing of interest in the destructor type is its extended info.
10789 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +000010790 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +000010791 EPI.ExceptionSpec.Type = EST_Unevaluated;
10792 EPI.ExceptionSpec.SourceDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000010793 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +000010794
Sebastian Redl623ea822011-05-19 05:13:44 +000010795 // FIXME: If the destructor has a body that could throw, and the newly created
10796 // spec doesn't allow exceptions, we should emit a warning, because this
10797 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +000010798 // However, we don't have a body or an exception specification yet, so it
10799 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +000010800}
10801
Pavel Labath58934982013-08-30 08:52:28 +000010802namespace {
10803/// \brief An abstract base class for all helper classes used in building the
10804// copy/move operators. These classes serve as factory functions and help us
10805// avoid using the same Expr* in the AST twice.
10806class ExprBuilder {
Aaron Ballmanabc18922015-02-15 22:54:08 +000010807 ExprBuilder(const ExprBuilder&) = delete;
10808 ExprBuilder &operator=(const ExprBuilder&) = delete;
Pavel Labath58934982013-08-30 08:52:28 +000010809
10810protected:
10811 static Expr *assertNotNull(Expr *E) {
10812 assert(E && "Expression construction must not fail.");
10813 return E;
10814 }
10815
10816public:
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000010817 ExprBuilder() {}
10818 virtual ~ExprBuilder() {}
Pavel Labath58934982013-08-30 08:52:28 +000010819
10820 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
10821};
10822
10823class RefBuilder: public ExprBuilder {
10824 VarDecl *Var;
10825 QualType VarType;
10826
10827public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010828 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010829 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +000010830 }
10831
10832 RefBuilder(VarDecl *Var, QualType VarType)
10833 : Var(Var), VarType(VarType) {}
10834};
10835
10836class ThisBuilder: public ExprBuilder {
10837public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010838 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010839 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
Pavel Labath58934982013-08-30 08:52:28 +000010840 }
10841};
10842
10843class CastBuilder: public ExprBuilder {
10844 const ExprBuilder &Builder;
10845 QualType Type;
10846 ExprValueKind Kind;
10847 const CXXCastPath &Path;
10848
10849public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010850 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010851 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
10852 CK_UncheckedDerivedToBase, Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010853 &Path).get());
Pavel Labath58934982013-08-30 08:52:28 +000010854 }
10855
10856 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
10857 const CXXCastPath &Path)
10858 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
10859};
10860
10861class DerefBuilder: public ExprBuilder {
10862 const ExprBuilder &Builder;
10863
10864public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010865 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010866 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010867 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +000010868 }
10869
10870 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10871};
10872
10873class MemberBuilder: public ExprBuilder {
10874 const ExprBuilder &Builder;
10875 QualType Type;
10876 CXXScopeSpec SS;
10877 bool IsArrow;
10878 LookupResult &MemberLookup;
10879
10880public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010881 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010882 return assertNotNull(S.BuildMemberReferenceExpr(
Craig Topperc3ec1492014-05-26 06:22:03 +000010883 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
Aaron Ballman6924dcd2015-09-01 14:49:24 +000010884 nullptr, MemberLookup, nullptr, nullptr).get());
Pavel Labath58934982013-08-30 08:52:28 +000010885 }
10886
10887 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
10888 LookupResult &MemberLookup)
10889 : Builder(Builder), Type(Type), IsArrow(IsArrow),
10890 MemberLookup(MemberLookup) {}
10891};
10892
10893class MoveCastBuilder: public ExprBuilder {
10894 const ExprBuilder &Builder;
10895
10896public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010897 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010898 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
10899 }
10900
10901 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10902};
10903
10904class LvalueConvBuilder: public ExprBuilder {
10905 const ExprBuilder &Builder;
10906
10907public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010908 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010909 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010910 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +000010911 }
10912
10913 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10914};
10915
10916class SubscriptBuilder: public ExprBuilder {
10917 const ExprBuilder &Base;
10918 const ExprBuilder &Index;
10919
10920public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010921 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010922 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010923 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +000010924 }
10925
10926 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
10927 : Base(Base), Index(Index) {}
10928};
10929
10930} // end anonymous namespace
10931
Richard Smith41ae3282012-11-14 00:50:40 +000010932/// When generating a defaulted copy or move assignment operator, if a field
10933/// should be copied with __builtin_memcpy rather than via explicit assignments,
10934/// do so. This optimization only applies for arrays of scalars, and for arrays
10935/// of class type where the selected copy/move-assignment operator is trivial.
10936static StmtResult
10937buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +000010938 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +000010939 // Compute the size of the memory buffer to be copied.
10940 QualType SizeType = S.Context.getSizeType();
10941 llvm::APInt Size(S.Context.getTypeSize(SizeType),
10942 S.Context.getTypeSizeInChars(T).getQuantity());
10943
10944 // Take the address of the field references for "from" and "to". We
10945 // directly construct UnaryOperators here because semantic analysis
10946 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +000010947 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000010948 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
10949 S.Context.getPointerType(From->getType()),
10950 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +000010951 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000010952 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
10953 S.Context.getPointerType(To->getType()),
10954 VK_RValue, OK_Ordinary, Loc);
10955
10956 const Type *E = T->getBaseElementTypeUnsafe();
10957 bool NeedsCollectableMemCpy =
10958 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
10959
10960 // Create a reference to the __builtin_objc_memmove_collectable function
10961 StringRef MemCpyName = NeedsCollectableMemCpy ?
10962 "__builtin_objc_memmove_collectable" :
10963 "__builtin_memcpy";
10964 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
10965 Sema::LookupOrdinaryName);
10966 S.LookupName(R, S.TUScope, true);
10967
10968 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
10969 if (!MemCpy)
10970 // Something went horribly wrong earlier, and we will have complained
10971 // about it.
10972 return StmtError();
10973
10974 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
Craig Topperc3ec1492014-05-26 06:22:03 +000010975 VK_RValue, Loc, nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +000010976 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
10977
10978 Expr *CallArgs[] = {
10979 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
10980 };
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010981 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
Richard Smith41ae3282012-11-14 00:50:40 +000010982 Loc, CallArgs, Loc);
10983
10984 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010985 return Call.getAs<Stmt>();
Richard Smith41ae3282012-11-14 00:50:40 +000010986}
10987
Sebastian Redl22653ba2011-08-30 19:58:05 +000010988/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +000010989/// \c To.
10990///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010991/// This routine is used to copy/move the members of a class with an
10992/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +000010993/// copied are arrays, this routine builds for loops to copy them.
10994///
10995/// \param S The Sema object used for type-checking.
10996///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010997/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +000010998///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010999/// \param T The type of the expressions being copied/moved. Both expressions
11000/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +000011001///
Sebastian Redl22653ba2011-08-30 19:58:05 +000011002/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +000011003///
Sebastian Redl22653ba2011-08-30 19:58:05 +000011004/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +000011005///
Sebastian Redl22653ba2011-08-30 19:58:05 +000011006/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +000011007/// Otherwise, it's a non-static member subobject.
11008///
Sebastian Redl22653ba2011-08-30 19:58:05 +000011009/// \param Copying Whether we're copying or moving.
11010///
Douglas Gregorb139cd52010-05-01 20:49:11 +000011011/// \param Depth Internal parameter recording the depth of the recursion.
11012///
Richard Smith41ae3282012-11-14 00:50:40 +000011013/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
11014/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +000011015static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +000011016buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +000011017 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +000011018 bool CopyingBaseSubobject, bool Copying,
11019 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +000011020 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +000011021 // Each subobject is assigned in the manner appropriate to its type:
11022 //
Sebastian Redl22653ba2011-08-30 19:58:05 +000011023 // - if the subobject is of class type, as if by a call to operator= with
11024 // the subobject as the object expression and the corresponding
11025 // subobject of x as a single function argument (as if by explicit
11026 // qualification; that is, ignoring any possible virtual overriding
11027 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +000011028 //
11029 // C++03 [class.copy]p13:
11030 // - if the subobject is of class type, the copy assignment operator for
11031 // the class is used (as if by explicit qualification; that is,
11032 // ignoring any possible virtual overriding functions in more derived
11033 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011034 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
11035 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +000011036
Douglas Gregorb139cd52010-05-01 20:49:11 +000011037 // Look for operator=.
11038 DeclarationName Name
11039 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11040 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
11041 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011042
Richard Smith52c0b582012-11-13 00:54:12 +000011043 // Prior to C++11, filter out any result that isn't a copy/move-assignment
11044 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +000011045 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +000011046 LookupResult::Filter F = OpLookup.makeFilter();
11047 while (F.hasNext()) {
11048 NamedDecl *D = F.next();
11049 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
11050 if (Method->isCopyAssignmentOperator() ||
11051 (!Copying && Method->isMoveAssignmentOperator()))
11052 continue;
11053
11054 F.erase();
11055 }
11056 F.done();
John McCallab8c2732010-03-16 06:11:48 +000011057 }
Richard Smith52c0b582012-11-13 00:54:12 +000011058
Douglas Gregor40c92bb2010-05-04 15:20:55 +000011059 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +000011060 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +000011061 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +000011062 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +000011063 // ambiguities), we need to cast "this" to that subobject type; to
11064 // ensure that we don't go through the virtual call mechanism, we need
11065 // to qualify the operator= name with the base class (see below). However,
11066 // this means that if the base class has a protected copy assignment
11067 // operator, the protected member access check will fail. So, we
11068 // rewrite "protected" access to "public" access in this case, since we
11069 // know by construction that we're calling from a derived class.
11070 if (CopyingBaseSubobject) {
11071 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11072 L != LEnd; ++L) {
11073 if (L.getAccess() == AS_protected)
11074 L.setAccess(AS_public);
11075 }
11076 }
Richard Smith52c0b582012-11-13 00:54:12 +000011077
Douglas Gregorb139cd52010-05-01 20:49:11 +000011078 // Create the nested-name-specifier that will be used to qualify the
11079 // reference to operator=; this is required to suppress the virtual
11080 // call mechanism.
11081 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +000011082 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +000011083 SS.MakeTrivial(S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +000011084 NestedNameSpecifier::Create(S.Context, nullptr, false,
Manuel Klimeke7167412012-02-06 21:51:39 +000011085 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +000011086 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +000011087
Douglas Gregorb139cd52010-05-01 20:49:11 +000011088 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +000011089 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +000011090 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
11091 SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000011092 /*FirstQualifierInScope=*/nullptr,
Abramo Bagnara7945c982012-01-27 09:46:47 +000011093 OpLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000011094 /*TemplateArgs=*/nullptr, /*S*/nullptr,
Douglas Gregorb139cd52010-05-01 20:49:11 +000011095 /*SuppressQualifierCheck=*/true);
11096 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011097 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +000011098
Douglas Gregorb139cd52010-05-01 20:49:11 +000011099 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +000011100
Pavel Labath58934982013-08-30 08:52:28 +000011101 Expr *FromInst = From.build(S, Loc);
Craig Topperc3ec1492014-05-26 06:22:03 +000011102 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011103 OpEqualRef.getAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +000011104 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011105 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011106 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +000011107
Richard Smith41ae3282012-11-14 00:50:40 +000011108 // If we built a call to a trivial 'operator=' while copying an array,
11109 // bail out. We'll replace the whole shebang with a memcpy.
11110 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11111 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
Craig Topperc3ec1492014-05-26 06:22:03 +000011112 return StmtResult((Stmt*)nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +000011113
Richard Smith52c0b582012-11-13 00:54:12 +000011114 // Convert to an expression-statement, and clean up any produced
11115 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +000011116 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +000011117 }
John McCallab8c2732010-03-16 06:11:48 +000011118
Richard Smith52c0b582012-11-13 00:54:12 +000011119 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +000011120 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +000011121 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011122 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +000011123 ExprResult Assignment = S.CreateBuiltinBinOp(
11124 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000011125 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000011126 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +000011127 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +000011128 }
Richard Smith52c0b582012-11-13 00:54:12 +000011129
11130 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +000011131 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +000011132
Douglas Gregorb139cd52010-05-01 20:49:11 +000011133 // Construct a loop over the array bounds, e.g.,
11134 //
11135 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11136 //
Erich Keanebb863642017-09-20 22:28:24 +000011137 // that will copy each of the array elements.
Douglas Gregorb139cd52010-05-01 20:49:11 +000011138 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +000011139
Douglas Gregorb139cd52010-05-01 20:49:11 +000011140 // Create the iteration variable.
Craig Topperc3ec1492014-05-26 06:22:03 +000011141 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011142 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000011143 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011144 llvm::raw_svector_ostream OS(Str);
11145 OS << "__i" << Depth;
11146 IterationVarName = &S.Context.Idents.get(OS.str());
11147 }
Abramo Bagnaradff19302011-03-08 08:55:46 +000011148 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +000011149 IterationVarName, SizeType,
11150 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +000011151 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +000011152
Douglas Gregorb139cd52010-05-01 20:49:11 +000011153 // Initialize the iteration variable to zero.
11154 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000011155 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000011156
Pavel Labath58934982013-08-30 08:52:28 +000011157 // Creates a reference to the iteration variable.
11158 RefBuilder IterationVarRef(IterationVar, SizeType);
11159 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +000011160
Douglas Gregorb139cd52010-05-01 20:49:11 +000011161 // Create the DeclStmt that holds the iteration variable.
11162 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000011163
Douglas Gregorb139cd52010-05-01 20:49:11 +000011164 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +000011165 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11166 MoveCastBuilder FromIndexMove(FromIndexCopy);
11167 const ExprBuilder *FromIndex;
11168 if (Copying)
11169 FromIndex = &FromIndexCopy;
11170 else
11171 FromIndex = &FromIndexMove;
11172
11173 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011174
11175 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +000011176 StmtResult Copy =
11177 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +000011178 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +000011179 Copying, Depth + 1);
11180 // Bail out if copying fails or if we determined that we should use memcpy.
11181 if (Copy.isInvalid() || !Copy.get())
11182 return Copy;
11183
11184 // Create the comparison against the array bound.
11185 llvm::APInt Upper
11186 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11187 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +000011188 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +000011189 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11190 BO_NE, S.Context.BoolTy,
Adam Nemet484aa452017-03-27 19:17:25 +000011191 VK_RValue, OK_Ordinary, Loc, FPOptions());
Richard Smith41ae3282012-11-14 00:50:40 +000011192
11193 // Create the pre-increment of the iteration variable.
11194 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +000011195 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
11196 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000011197
Douglas Gregorb139cd52010-05-01 20:49:11 +000011198 // Construct the loop that copies all elements of this array.
Richard Smith03a4aa32016-06-23 19:02:52 +000011199 return S.ActOnForStmt(
11200 Loc, Loc, InitStmt,
11201 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11202 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
Fariborz Jahanian41f79272009-06-25 21:45:19 +000011203}
11204
Richard Smith41ae3282012-11-14 00:50:40 +000011205static StmtResult
11206buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +000011207 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +000011208 bool CopyingBaseSubobject, bool Copying) {
11209 // Maybe we should use a memcpy?
11210 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11211 T.isTriviallyCopyableType(S.Context))
11212 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11213
11214 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11215 CopyingBaseSubobject,
11216 Copying, 0));
11217
11218 // If we ended up picking a trivial assignment operator for an array of a
11219 // non-trivially-copyable class type, just emit a memcpy.
11220 if (!Result.isInvalid() && !Result.get())
11221 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11222
11223 return Result;
11224}
11225
Alexis Hunt119f3652011-05-14 05:23:20 +000011226CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11227 // Note: The following rules are largely analoguous to the copy
11228 // constructor rules. Note that virtual bases are not taken into account
11229 // for determining the argument type of the operator. Note also that
11230 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +000011231 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +000011232
Richard Smith8bf22e52012-11-29 01:34:07 +000011233 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11234 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000011235 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000011236
Alexis Hunt119f3652011-05-14 05:23:20 +000011237 QualType ArgType = Context.getTypeDeclType(ClassDecl);
11238 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +000011239 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11240 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +000011241 ArgType = ArgType.withConst();
11242 ArgType = Context.getLValueReferenceType(ArgType);
11243
Richard Smith99005e62013-05-07 03:19:20 +000011244 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11245 CXXCopyAssignment,
11246 Const);
11247
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000011248 // An implicitly-declared copy assignment operator is an inline public
11249 // member of its class.
11250 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +000011251 SourceLocation ClassLoc = ClassDecl->getLocation();
11252 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000011253 CXXMethodDecl *CopyAssignment =
11254 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000011255 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11256 /*isInline=*/true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000011257 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +000011258 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000011259 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +000011260
Eli Bendersky9a220fc2014-09-29 20:38:29 +000011261 if (getLangOpts().CUDA) {
11262 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11263 CopyAssignment,
11264 /* ConstRHS */ Const,
11265 /* Diagnose */ false);
11266 }
11267
Richard Smithd3b5c9082012-07-27 04:22:15 +000011268 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000011269 FunctionProtoType::ExtProtoInfo EPI =
11270 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000011271 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000011272
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000011273 // Add the parameter to the operator.
11274 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000011275 ClassLoc, ClassLoc,
11276 /*Id=*/nullptr, ArgType,
11277 /*TInfo=*/nullptr, SC_None,
11278 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000011279 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +000011280
Richard Smith6b02d462012-12-08 08:32:28 +000011281 CopyAssignment->setTrivial(
11282 ClassDecl->needsOverloadResolutionForCopyAssignment()
11283 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11284 : ClassDecl->hasTrivialCopyAssignment());
11285
Richard Smith6b02d462012-12-08 08:32:28 +000011286 // Note that we have added this copy-assignment operator.
11287 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
11288
Richard Smith12e79312016-05-13 06:47:56 +000011289 Scope *S = getScopeForContext(ClassDecl);
11290 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11291
11292 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11293 SetDeclDeleted(CopyAssignment, ClassLoc);
11294
11295 if (S)
Richard Smith6b02d462012-12-08 08:32:28 +000011296 PushOnScopeChains(CopyAssignment, S, false);
11297 ClassDecl->addDecl(CopyAssignment);
11298
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000011299 return CopyAssignment;
11300}
11301
Richard Smithd577fbb2013-06-13 03:23:42 +000011302/// Diagnose an implicit copy operation for a class which is odr-used, but
11303/// which is deprecated because the class has a user-declared copy constructor,
11304/// copy assignment operator, or destructor.
Richard Smith883dbc42017-05-25 22:47:05 +000011305static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011306 assert(CopyOp->isImplicit());
11307
11308 CXXRecordDecl *RD = CopyOp->getParent();
Craig Topperc3ec1492014-05-26 06:22:03 +000011309 CXXMethodDecl *UserDeclaredOperation = nullptr;
Richard Smithd577fbb2013-06-13 03:23:42 +000011310
11311 // In Microsoft mode, assignment operations don't affect constructors and
11312 // vice versa.
11313 if (RD->hasUserDeclaredDestructor()) {
11314 UserDeclaredOperation = RD->getDestructor();
11315 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11316 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000011317 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011318 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +000011319 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011320 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +000011321 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +000011322 break;
11323 }
11324 }
11325 assert(UserDeclaredOperation);
11326 } else if (isa<CXXConstructorDecl>(CopyOp) &&
11327 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000011328 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011329 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +000011330 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011331 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000011332 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +000011333 break;
11334 }
11335 }
11336 assert(UserDeclaredOperation);
11337 }
11338
11339 if (UserDeclaredOperation) {
11340 S.Diag(UserDeclaredOperation->getLocation(),
11341 diag::warn_deprecated_copy_operation)
11342 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11343 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
Richard Smithd577fbb2013-06-13 03:23:42 +000011344 }
11345}
11346
Douglas Gregorb139cd52010-05-01 20:49:11 +000011347void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11348 CXXMethodDecl *CopyAssignOperator) {
Erich Keanebb863642017-09-20 22:28:24 +000011349 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000011350 CopyAssignOperator->isOverloadedOperator() &&
11351 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000011352 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11353 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000011354 "DefineImplicitCopyAssignment called for wrong function");
Richard Smith883dbc42017-05-25 22:47:05 +000011355 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
11356 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011357
11358 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
Richard Smith883dbc42017-05-25 22:47:05 +000011359 if (ClassDecl->isInvalidDecl()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000011360 CopyAssignOperator->setInvalidDecl();
11361 return;
11362 }
Richard Smithd577fbb2013-06-13 03:23:42 +000011363
Richard Smith883dbc42017-05-25 22:47:05 +000011364 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
11365
11366 // The exception specification is needed because we are defining the
11367 // function.
11368 ResolveExceptionSpec(CurrentLocation,
11369 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11370
11371 // Add a context note for diagnostics produced after this point.
11372 Scope.addContextNote(CurrentLocation);
11373
Richard Smithd577fbb2013-06-13 03:23:42 +000011374 // C++11 [class.copy]p18:
11375 // The [definition of an implicitly declared copy assignment operator] is
11376 // deprecated if the class has a user-declared copy constructor or a
11377 // user-declared destructor.
11378 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
Richard Smith883dbc42017-05-25 22:47:05 +000011379 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011380
11381 // C++0x [class.copy]p30:
11382 // The implicitly-defined or explicitly-defaulted copy assignment operator
Erich Keanebb863642017-09-20 22:28:24 +000011383 // for a non-union class X performs memberwise copy assignment of its
11384 // subobjects. The direct base classes of X are assigned first, in the
11385 // order of their declaration in the base-specifier-list, and then the
11386 // immediate non-static data members of X are assigned, in the order in
Douglas Gregorb139cd52010-05-01 20:49:11 +000011387 // which they were declared in the class definition.
Erich Keanebb863642017-09-20 22:28:24 +000011388
Douglas Gregorb139cd52010-05-01 20:49:11 +000011389 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000011390 SmallVector<Stmt*, 8> Statements;
Erich Keanebb863642017-09-20 22:28:24 +000011391
Douglas Gregorb139cd52010-05-01 20:49:11 +000011392 // The parameter for the "other" object, which we are copying from.
11393 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11394 Qualifiers OtherQuals = Other->getType().getQualifiers();
11395 QualType OtherRefType = Other->getType();
11396 if (const LValueReferenceType *OtherRef
11397 = OtherRefType->getAs<LValueReferenceType>()) {
11398 OtherRefType = OtherRef->getPointeeType();
11399 OtherQuals = OtherRefType.getQualifiers();
11400 }
Erich Keanebb863642017-09-20 22:28:24 +000011401
Douglas Gregorb139cd52010-05-01 20:49:11 +000011402 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011403 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
11404 ? CopyAssignOperator->getLocEnd()
11405 : CopyAssignOperator->getLocation();
11406
Pavel Labath58934982013-08-30 08:52:28 +000011407 // Builds a DeclRefExpr for the "other" object.
11408 RefBuilder OtherRef(Other, OtherRefType);
11409
11410 // Builds the "this" pointer.
11411 ThisBuilder This;
Erich Keanebb863642017-09-20 22:28:24 +000011412
Douglas Gregorb139cd52010-05-01 20:49:11 +000011413 // Assign base classes.
11414 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000011415 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000011416 // Form the assignment:
11417 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000011418 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +000011419 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000011420 Invalid = true;
11421 continue;
11422 }
11423
John McCallcf142162010-08-07 06:22:56 +000011424 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000011425 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +000011426
Douglas Gregorb139cd52010-05-01 20:49:11 +000011427 // Construct the "from" expression, which is an implicit cast to the
11428 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000011429 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
11430 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011431
11432 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000011433 DerefBuilder DerefThis(This);
11434 CastBuilder To(DerefThis,
11435 Context.getCVRQualifiedType(
11436 BaseType, CopyAssignOperator->getTypeQualifiers()),
11437 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011438
11439 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +000011440 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000011441 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000011442 /*CopyingBaseSubobject=*/true,
11443 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011444 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000011445 CopyAssignOperator->setInvalidDecl();
11446 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011447 }
Erich Keanebb863642017-09-20 22:28:24 +000011448
Douglas Gregorb139cd52010-05-01 20:49:11 +000011449 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011450 Statements.push_back(Copy.getAs<Expr>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000011451 }
Erich Keanebb863642017-09-20 22:28:24 +000011452
Douglas Gregorb139cd52010-05-01 20:49:11 +000011453 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011454 for (auto *Field : ClassDecl->fields()) {
Richard Smith419bd092015-04-29 19:26:57 +000011455 // FIXME: We should form some kind of AST representation for the implied
11456 // memcpy in a union copy operation.
11457 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
Douglas Gregor556e5862011-10-10 17:22:13 +000011458 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +000011459
11460 if (Field->isInvalidDecl()) {
11461 Invalid = true;
11462 continue;
11463 }
11464
Douglas Gregorb139cd52010-05-01 20:49:11 +000011465 // Check for members of reference type; we can't copy those.
11466 if (Field->getType()->isReferenceType()) {
11467 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11468 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11469 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011470 Invalid = true;
11471 continue;
11472 }
Erich Keanebb863642017-09-20 22:28:24 +000011473
Douglas Gregorb139cd52010-05-01 20:49:11 +000011474 // Check for members of const-qualified, non-class type.
11475 QualType BaseType = Context.getBaseElementType(Field->getType());
11476 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11477 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11478 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11479 Diag(Field->getLocation(), diag::note_declared_at);
Erich Keanebb863642017-09-20 22:28:24 +000011480 Invalid = true;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011481 continue;
11482 }
John McCall1b1a1db2011-06-17 00:18:42 +000011483
11484 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000011485 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11486 continue;
Erich Keanebb863642017-09-20 22:28:24 +000011487
Douglas Gregorb139cd52010-05-01 20:49:11 +000011488 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000011489 if (FieldType->isIncompleteArrayType()) {
Erich Keanebb863642017-09-20 22:28:24 +000011490 assert(ClassDecl->hasFlexibleArrayMember() &&
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000011491 "Incomplete array type is not valid");
11492 continue;
11493 }
Erich Keanebb863642017-09-20 22:28:24 +000011494
Douglas Gregorb139cd52010-05-01 20:49:11 +000011495 // Build references to the field in the object we're copying from and to.
11496 CXXScopeSpec SS; // Intentionally empty
11497 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11498 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011499 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011500 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000011501
11502 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
11503
11504 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011505
Douglas Gregorb139cd52010-05-01 20:49:11 +000011506 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000011507 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000011508 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000011509 /*CopyingBaseSubobject=*/false,
11510 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011511 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000011512 CopyAssignOperator->setInvalidDecl();
11513 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011514 }
Erich Keanebb863642017-09-20 22:28:24 +000011515
Douglas Gregorb139cd52010-05-01 20:49:11 +000011516 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011517 Statements.push_back(Copy.getAs<Stmt>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000011518 }
11519
11520 if (!Invalid) {
11521 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +000011522 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Erich Keanebb863642017-09-20 22:28:24 +000011523
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000011524 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +000011525 if (Return.isInvalid())
11526 Invalid = true;
Richard Smith883dbc42017-05-25 22:47:05 +000011527 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011528 Statements.push_back(Return.getAs<Stmt>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000011529 }
11530
11531 if (Invalid) {
11532 CopyAssignOperator->setInvalidDecl();
11533 return;
11534 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011535
11536 StmtResult Body;
11537 {
11538 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011539 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011540 /*isStmtExpr=*/false);
11541 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11542 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011543 CopyAssignOperator->setBody(Body.getAs<Stmt>());
Richard Smith883dbc42017-05-25 22:47:05 +000011544 CopyAssignOperator->markUsed(Context);
Sebastian Redlab238a72011-04-24 16:28:06 +000011545
11546 if (ASTMutationListener *L = getASTMutationListener()) {
11547 L->CompletedImplicitDefinition(CopyAssignOperator);
11548 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +000011549}
11550
Sebastian Redl22653ba2011-08-30 19:58:05 +000011551CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000011552 assert(ClassDecl->needsImplicitMoveAssignment());
11553
Richard Smith8bf22e52012-11-29 01:34:07 +000011554 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
11555 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000011556 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000011557
Sebastian Redl22653ba2011-08-30 19:58:05 +000011558 // Note: The following rules are largely analoguous to the move
11559 // constructor rules.
11560
Sebastian Redl22653ba2011-08-30 19:58:05 +000011561 QualType ArgType = Context.getTypeDeclType(ClassDecl);
11562 QualType RetType = Context.getLValueReferenceType(ArgType);
11563 ArgType = Context.getRValueReferenceType(ArgType);
11564
Richard Smith99005e62013-05-07 03:19:20 +000011565 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11566 CXXMoveAssignment,
11567 false);
11568
Sebastian Redl22653ba2011-08-30 19:58:05 +000011569 // An implicitly-declared move assignment operator is an inline public
11570 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +000011571 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11572 SourceLocation ClassLoc = ClassDecl->getLocation();
11573 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000011574 CXXMethodDecl *MoveAssignment =
11575 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000011576 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
Richard Smith99005e62013-05-07 03:19:20 +000011577 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011578 MoveAssignment->setAccess(AS_public);
11579 MoveAssignment->setDefaulted();
11580 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +000011581
Eli Bendersky9a220fc2014-09-29 20:38:29 +000011582 if (getLangOpts().CUDA) {
11583 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
11584 MoveAssignment,
11585 /* ConstRHS */ false,
11586 /* Diagnose */ false);
11587 }
11588
Richard Smithd3b5c9082012-07-27 04:22:15 +000011589 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000011590 FunctionProtoType::ExtProtoInfo EPI =
11591 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000011592 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000011593
Sebastian Redl22653ba2011-08-30 19:58:05 +000011594 // Add the parameter to the operator.
11595 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000011596 ClassLoc, ClassLoc,
11597 /*Id=*/nullptr, ArgType,
11598 /*TInfo=*/nullptr, SC_None,
11599 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000011600 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011601
Richard Smith6b02d462012-12-08 08:32:28 +000011602 MoveAssignment->setTrivial(
11603 ClassDecl->needsOverloadResolutionForMoveAssignment()
11604 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
11605 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011606
Richard Smith12e79312016-05-13 06:47:56 +000011607 // Note that we have added this copy-assignment operator.
11608 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
11609
11610 Scope *S = getScopeForContext(ClassDecl);
11611 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
11612
Richard Smithd951a1d2012-02-18 02:02:13 +000011613 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000011614 ClassDecl->setImplicitMoveAssignmentIsDeleted();
11615 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011616 }
11617
Richard Smith12e79312016-05-13 06:47:56 +000011618 if (S)
Sebastian Redl22653ba2011-08-30 19:58:05 +000011619 PushOnScopeChains(MoveAssignment, S, false);
11620 ClassDecl->addDecl(MoveAssignment);
11621
Sebastian Redl22653ba2011-08-30 19:58:05 +000011622 return MoveAssignment;
11623}
11624
Richard Smithb2504bd2013-11-04 04:26:14 +000011625/// Check if we're implicitly defining a move assignment operator for a class
11626/// with virtual bases. Such a move assignment might move-assign the virtual
11627/// base multiple times.
11628static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
11629 SourceLocation CurrentLocation) {
11630 assert(!Class->isDependentContext() && "should not define dependent move");
11631
11632 // Only a virtual base could get implicitly move-assigned multiple times.
11633 // Only a non-trivial move assignment can observe this. We only want to
11634 // diagnose if we implicitly define an assignment operator that assigns
11635 // two base classes, both of which move-assign the same virtual base.
11636 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
11637 Class->getNumBases() < 2)
11638 return;
11639
11640 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
11641 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
11642 VBaseMap VBases;
11643
Aaron Ballman574705e2014-03-13 15:41:46 +000011644 for (auto &BI : Class->bases()) {
11645 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000011646 while (!Worklist.empty()) {
11647 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
11648 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
11649
11650 // If the base has no non-trivial move assignment operators,
11651 // we don't care about moves from it.
11652 if (!Base->hasNonTrivialMoveAssignment())
11653 continue;
11654
11655 // If there's nothing virtual here, skip it.
11656 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
11657 continue;
11658
11659 // If we're not actually going to call a move assignment for this base,
11660 // or the selected move assignment is trivial, skip it.
Richard Smith8bae1be2017-02-24 02:07:20 +000011661 Sema::SpecialMemberOverloadResult SMOR =
Richard Smithb2504bd2013-11-04 04:26:14 +000011662 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
11663 /*ConstArg*/false, /*VolatileArg*/false,
11664 /*RValueThis*/true, /*ConstThis*/false,
11665 /*VolatileThis*/false);
Richard Smith8bae1be2017-02-24 02:07:20 +000011666 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
11667 !SMOR.getMethod()->isMoveAssignmentOperator())
Richard Smithb2504bd2013-11-04 04:26:14 +000011668 continue;
11669
11670 if (BaseSpec->isVirtual()) {
11671 // We're going to move-assign this virtual base, and its move
11672 // assignment operator is not trivial. If this can happen for
11673 // multiple distinct direct bases of Class, diagnose it. (If it
11674 // only happens in one base, we'll diagnose it when synthesizing
11675 // that base class's move assignment operator.)
11676 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +000011677 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +000011678 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +000011679 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +000011680 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
11681 << Class << Base;
11682 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
11683 << (Base->getCanonicalDecl() ==
11684 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11685 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +000011686 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +000011687 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +000011688 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11689 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +000011690
11691 // Only diagnose each vbase once.
Craig Topperc3ec1492014-05-26 06:22:03 +000011692 Existing = nullptr;
Richard Smithb2504bd2013-11-04 04:26:14 +000011693 }
11694 } else {
11695 // Only walk over bases that have defaulted move assignment operators.
11696 // We assume that any user-provided move assignment operator handles
11697 // the multiple-moves-of-vbase case itself somehow.
Richard Smith8bae1be2017-02-24 02:07:20 +000011698 if (!SMOR.getMethod()->isDefaulted())
Richard Smithb2504bd2013-11-04 04:26:14 +000011699 continue;
11700
11701 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +000011702 for (auto &BI : Base->bases())
11703 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000011704 }
11705 }
11706 }
11707}
11708
Sebastian Redl22653ba2011-08-30 19:58:05 +000011709void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
11710 CXXMethodDecl *MoveAssignOperator) {
Erich Keanebb863642017-09-20 22:28:24 +000011711 assert((MoveAssignOperator->isDefaulted() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000011712 MoveAssignOperator->isOverloadedOperator() &&
11713 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000011714 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
11715 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000011716 "DefineImplicitMoveAssignment called for wrong function");
Richard Smith883dbc42017-05-25 22:47:05 +000011717 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
11718 return;
Sebastian Redl22653ba2011-08-30 19:58:05 +000011719
11720 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
Richard Smith883dbc42017-05-25 22:47:05 +000011721 if (ClassDecl->isInvalidDecl()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000011722 MoveAssignOperator->setInvalidDecl();
11723 return;
11724 }
Erich Keanebb863642017-09-20 22:28:24 +000011725
Sebastian Redl22653ba2011-08-30 19:58:05 +000011726 // C++0x [class.copy]p28:
11727 // The implicitly-defined or move assignment operator for a non-union class
11728 // X performs memberwise move assignment of its subobjects. The direct base
11729 // classes of X are assigned first, in the order of their declaration in the
11730 // base-specifier-list, and then the immediate non-static data members of X
11731 // are assigned, in the order in which they were declared in the class
11732 // definition.
11733
Richard Smithb2504bd2013-11-04 04:26:14 +000011734 // Issue a warning if our implicit move assignment operator will move
11735 // from a virtual base more than once.
11736 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +000011737
Richard Smith883dbc42017-05-25 22:47:05 +000011738 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
11739
11740 // The exception specification is needed because we are defining the
11741 // function.
11742 ResolveExceptionSpec(CurrentLocation,
11743 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
11744
11745 // Add a context note for diagnostics produced after this point.
11746 Scope.addContextNote(CurrentLocation);
11747
Sebastian Redl22653ba2011-08-30 19:58:05 +000011748 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000011749 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +000011750
11751 // The parameter for the "other" object, which we are move from.
11752 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
11753 QualType OtherRefType = Other->getType()->
11754 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +000011755 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000011756 "Bad argument type of defaulted move assignment");
11757
11758 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011759 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
11760 ? MoveAssignOperator->getLocEnd()
11761 : MoveAssignOperator->getLocation();
Sebastian Redl22653ba2011-08-30 19:58:05 +000011762
Pavel Labath58934982013-08-30 08:52:28 +000011763 // Builds a reference to the "other" object.
11764 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011765 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +000011766 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011767
Pavel Labath58934982013-08-30 08:52:28 +000011768 // Builds the "this" pointer.
11769 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +000011770
Sebastian Redl22653ba2011-08-30 19:58:05 +000011771 // Assign base classes.
11772 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000011773 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +000011774 // C++11 [class.copy]p28:
11775 // It is unspecified whether subobjects representing virtual base classes
11776 // are assigned more than once by the implicitly-defined copy assignment
11777 // operator.
11778 // FIXME: Do not assign to a vbase that will be assigned by some other base
11779 // class. For a move-assignment, this can result in the vbase being moved
11780 // multiple times.
11781
Sebastian Redl22653ba2011-08-30 19:58:05 +000011782 // Form the assignment:
11783 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000011784 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +000011785 if (!BaseType->isRecordType()) {
11786 Invalid = true;
11787 continue;
11788 }
11789
11790 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000011791 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011792
11793 // Construct the "from" expression, which is an implicit cast to the
11794 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000011795 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011796
11797 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000011798 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011799
11800 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000011801 CastBuilder To(DerefThis,
11802 Context.getCVRQualifiedType(
11803 BaseType, MoveAssignOperator->getTypeQualifiers()),
11804 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011805
11806 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +000011807 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000011808 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000011809 /*CopyingBaseSubobject=*/true,
11810 /*Copying=*/false);
11811 if (Move.isInvalid()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000011812 MoveAssignOperator->setInvalidDecl();
11813 return;
11814 }
11815
11816 // Success! Record the move.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011817 Statements.push_back(Move.getAs<Expr>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011818 }
11819
Sebastian Redl22653ba2011-08-30 19:58:05 +000011820 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011821 for (auto *Field : ClassDecl->fields()) {
Richard Smith419bd092015-04-29 19:26:57 +000011822 // FIXME: We should form some kind of AST representation for the implied
11823 // memcpy in a union copy operation.
11824 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
Douglas Gregor556e5862011-10-10 17:22:13 +000011825 continue;
11826
Eli Friedmanc9817fd2013-06-07 01:48:56 +000011827 if (Field->isInvalidDecl()) {
11828 Invalid = true;
11829 continue;
11830 }
11831
Sebastian Redl22653ba2011-08-30 19:58:05 +000011832 // Check for members of reference type; we can't move those.
11833 if (Field->getType()->isReferenceType()) {
11834 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11835 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11836 Diag(Field->getLocation(), diag::note_declared_at);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011837 Invalid = true;
11838 continue;
11839 }
11840
11841 // Check for members of const-qualified, non-class type.
11842 QualType BaseType = Context.getBaseElementType(Field->getType());
11843 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11844 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11845 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11846 Diag(Field->getLocation(), diag::note_declared_at);
Erich Keanebb863642017-09-20 22:28:24 +000011847 Invalid = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +000011848 continue;
11849 }
11850
11851 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000011852 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11853 continue;
Erich Keanebb863642017-09-20 22:28:24 +000011854
Sebastian Redl22653ba2011-08-30 19:58:05 +000011855 QualType FieldType = Field->getType().getNonReferenceType();
11856 if (FieldType->isIncompleteArrayType()) {
Erich Keanebb863642017-09-20 22:28:24 +000011857 assert(ClassDecl->hasFlexibleArrayMember() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000011858 "Incomplete array type is not valid");
11859 continue;
11860 }
Erich Keanebb863642017-09-20 22:28:24 +000011861
Sebastian Redl22653ba2011-08-30 19:58:05 +000011862 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +000011863 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11864 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011865 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011866 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000011867 MemberBuilder From(MoveOther, OtherRefType,
11868 /*IsArrow=*/false, MemberLookup);
11869 MemberBuilder To(This, getCurrentThisType(),
11870 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011871
Pavel Labath58934982013-08-30 08:52:28 +000011872 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +000011873 "Member reference with rvalue base must be rvalue except for reference "
11874 "members, which aren't allowed for move assignment.");
11875
Sebastian Redl22653ba2011-08-30 19:58:05 +000011876 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000011877 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000011878 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000011879 /*CopyingBaseSubobject=*/false,
11880 /*Copying=*/false);
11881 if (Move.isInvalid()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000011882 MoveAssignOperator->setInvalidDecl();
11883 return;
11884 }
Richard Smith11d19592012-11-12 23:33:00 +000011885
Sebastian Redl22653ba2011-08-30 19:58:05 +000011886 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011887 Statements.push_back(Move.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011888 }
11889
11890 if (!Invalid) {
11891 // Add a "return *this;"
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011892 ExprResult ThisObj =
11893 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11894
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000011895 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011896 if (Return.isInvalid())
11897 Invalid = true;
Richard Smith883dbc42017-05-25 22:47:05 +000011898 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011899 Statements.push_back(Return.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011900 }
11901
11902 if (Invalid) {
11903 MoveAssignOperator->setInvalidDecl();
11904 return;
11905 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011906
11907 StmtResult Body;
11908 {
11909 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011910 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011911 /*isStmtExpr=*/false);
11912 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11913 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011914 MoveAssignOperator->setBody(Body.getAs<Stmt>());
Richard Smith883dbc42017-05-25 22:47:05 +000011915 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011916
11917 if (ASTMutationListener *L = getASTMutationListener()) {
11918 L->CompletedImplicitDefinition(MoveAssignOperator);
11919 }
11920}
11921
Alexis Hunt913820d2011-05-13 06:10:58 +000011922CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
11923 CXXRecordDecl *ClassDecl) {
11924 // C++ [class.copy]p4:
11925 // If the class definition does not explicitly declare a copy
11926 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000011927 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000011928
Richard Smith8bf22e52012-11-29 01:34:07 +000011929 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
11930 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000011931 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000011932
Alexis Hunt913820d2011-05-13 06:10:58 +000011933 QualType ClassType = Context.getTypeDeclType(ClassDecl);
11934 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000011935 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000011936 if (Const)
11937 ArgType = ArgType.withConst();
11938 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000011939
Richard Smithb5800092012-06-10 05:43:50 +000011940 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11941 CXXCopyConstructor,
11942 Const);
11943
Douglas Gregor54be3392010-07-01 17:57:27 +000011944 DeclarationName Name
11945 = Context.DeclarationNames.getCXXConstructorName(
11946 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000011947 SourceLocation ClassLoc = ClassDecl->getLocation();
11948 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000011949
11950 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000011951 // member of its class.
11952 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000011953 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000011954 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000011955 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000011956 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000011957 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000011958
Eli Bendersky9a220fc2014-09-29 20:38:29 +000011959 if (getLangOpts().CUDA) {
11960 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
11961 CopyConstructor,
11962 /* ConstRHS */ Const,
11963 /* Diagnose */ false);
11964 }
11965
Richard Smithd3b5c9082012-07-27 04:22:15 +000011966 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000011967 FunctionProtoType::ExtProtoInfo EPI =
11968 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000011969 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000011970 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000011971
Douglas Gregor54be3392010-07-01 17:57:27 +000011972 // Add the parameter to the constructor.
11973 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011974 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000011975 /*IdentifierInfo=*/nullptr,
11976 ArgType, /*TInfo=*/nullptr,
11977 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000011978 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000011979
Richard Smith6b02d462012-12-08 08:32:28 +000011980 CopyConstructor->setTrivial(
11981 ClassDecl->needsOverloadResolutionForCopyConstructor()
11982 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
11983 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000011984
Richard Smith6b02d462012-12-08 08:32:28 +000011985 // Note that we have declared this constructor.
11986 ++ASTContext::NumImplicitCopyConstructorsDeclared;
11987
Richard Smith12e79312016-05-13 06:47:56 +000011988 Scope *S = getScopeForContext(ClassDecl);
11989 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
11990
Richard Smith96cd6712017-08-16 01:49:53 +000011991 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
11992 ClassDecl->setImplicitCopyConstructorIsDeleted();
Richard Smith12e79312016-05-13 06:47:56 +000011993 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith96cd6712017-08-16 01:49:53 +000011994 }
Richard Smith12e79312016-05-13 06:47:56 +000011995
11996 if (S)
Richard Smith6b02d462012-12-08 08:32:28 +000011997 PushOnScopeChains(CopyConstructor, S, false);
11998 ClassDecl->addDecl(CopyConstructor);
11999
Douglas Gregor54be3392010-07-01 17:57:27 +000012000 return CopyConstructor;
12001}
12002
Fariborz Jahanian477d2422009-06-22 23:34:40 +000012003void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Richard Smith883dbc42017-05-25 22:47:05 +000012004 CXXConstructorDecl *CopyConstructor) {
Alexis Hunt913820d2011-05-13 06:10:58 +000012005 assert((CopyConstructor->isDefaulted() &&
12006 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000012007 !CopyConstructor->doesThisDeclarationHaveABody() &&
12008 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000012009 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Richard Smith883dbc42017-05-25 22:47:05 +000012010 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
12011 return;
Mike Stump11289f42009-09-09 15:08:12 +000012012
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000012013 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000012014 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000012015
Richard Smith883dbc42017-05-25 22:47:05 +000012016 SynthesizedFunctionScope Scope(*this, CopyConstructor);
12017
12018 // The exception specification is needed because we are defining the
12019 // function.
12020 ResolveExceptionSpec(CurrentLocation,
12021 CopyConstructor->getType()->castAs<FunctionProtoType>());
12022 MarkVTableUsed(CurrentLocation, ClassDecl);
12023
12024 // Add a context note for diagnostics produced after this point.
12025 Scope.addContextNote(CurrentLocation);
12026
Richard Smithd577fbb2013-06-13 03:23:42 +000012027 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000012028 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000012029 // deprecated if the class has a user-declared copy assignment operator
12030 // or a user-declared destructor.
12031 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
Richard Smith883dbc42017-05-25 22:47:05 +000012032 diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
Richard Smithd577fbb2013-06-13 03:23:42 +000012033
Richard Smith883dbc42017-05-25 22:47:05 +000012034 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
Anders Carlsson79111502010-05-01 16:39:01 +000012035 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000012036 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000012037 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
12038 ? CopyConstructor->getLocEnd()
12039 : CopyConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012040 Sema::CompoundScopeRAII CompoundScope(*this);
Daniel Jasperb3b0b802014-06-20 08:44:22 +000012041 CopyConstructor->setBody(
12042 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
Richard Smith883dbc42017-05-25 22:47:05 +000012043 CopyConstructor->markUsed(Context);
Anders Carlsson53e1ba92010-04-25 00:52:09 +000012044 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000012045
Sebastian Redlab238a72011-04-24 16:28:06 +000012046 if (ASTMutationListener *L = getASTMutationListener()) {
12047 L->CompletedImplicitDefinition(CopyConstructor);
12048 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000012049}
12050
Sebastian Redl22653ba2011-08-30 19:58:05 +000012051CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12052 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000012053 assert(ClassDecl->needsImplicitMoveConstructor());
12054
Richard Smith8bf22e52012-11-29 01:34:07 +000012055 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12056 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000012057 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000012058
Sebastian Redl22653ba2011-08-30 19:58:05 +000012059 QualType ClassType = Context.getTypeDeclType(ClassDecl);
12060 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012061
Richard Smithb5800092012-06-10 05:43:50 +000012062 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12063 CXXMoveConstructor,
12064 false);
12065
Sebastian Redl22653ba2011-08-30 19:58:05 +000012066 DeclarationName Name
12067 = Context.DeclarationNames.getCXXConstructorName(
12068 Context.getCanonicalType(ClassType));
12069 SourceLocation ClassLoc = ClassDecl->getLocation();
12070 DeclarationNameInfo NameInfo(Name, ClassLoc);
12071
Richard Smith99005e62013-05-07 03:19:20 +000012072 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000012073 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000012074 // member of its class.
12075 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000012076 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000012077 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000012078 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012079 MoveConstructor->setAccess(AS_public);
12080 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000012081
Eli Bendersky9a220fc2014-09-29 20:38:29 +000012082 if (getLangOpts().CUDA) {
12083 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12084 MoveConstructor,
12085 /* ConstRHS */ false,
12086 /* Diagnose */ false);
12087 }
12088
Richard Smithd3b5c9082012-07-27 04:22:15 +000012089 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000012090 FunctionProtoType::ExtProtoInfo EPI =
12091 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000012092 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000012093 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000012094
Sebastian Redl22653ba2011-08-30 19:58:05 +000012095 // Add the parameter to the constructor.
12096 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12097 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000012098 /*IdentifierInfo=*/nullptr,
12099 ArgType, /*TInfo=*/nullptr,
12100 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000012101 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012102
Richard Smith6b02d462012-12-08 08:32:28 +000012103 MoveConstructor->setTrivial(
12104 ClassDecl->needsOverloadResolutionForMoveConstructor()
12105 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12106 : ClassDecl->hasTrivialMoveConstructor());
12107
Richard Smith12e79312016-05-13 06:47:56 +000012108 // Note that we have declared this constructor.
12109 ++ASTContext::NumImplicitMoveConstructorsDeclared;
12110
12111 Scope *S = getScopeForContext(ClassDecl);
12112 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12113
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000012114 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000012115 ClassDecl->setImplicitMoveConstructorIsDeleted();
12116 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012117 }
12118
Richard Smith12e79312016-05-13 06:47:56 +000012119 if (S)
Sebastian Redl22653ba2011-08-30 19:58:05 +000012120 PushOnScopeChains(MoveConstructor, S, false);
12121 ClassDecl->addDecl(MoveConstructor);
12122
12123 return MoveConstructor;
12124}
12125
12126void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
Richard Smith883dbc42017-05-25 22:47:05 +000012127 CXXConstructorDecl *MoveConstructor) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000012128 assert((MoveConstructor->isDefaulted() &&
12129 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000012130 !MoveConstructor->doesThisDeclarationHaveABody() &&
12131 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000012132 "DefineImplicitMoveConstructor - call it for implicit move ctor");
Richard Smith883dbc42017-05-25 22:47:05 +000012133 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
12134 return;
Sebastian Redl22653ba2011-08-30 19:58:05 +000012135
12136 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12137 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12138
Eli Friedmaneaf34142012-10-18 20:14:08 +000012139 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012140
Richard Smith883dbc42017-05-25 22:47:05 +000012141 // The exception specification is needed because we are defining the
12142 // function.
12143 ResolveExceptionSpec(CurrentLocation,
12144 MoveConstructor->getType()->castAs<FunctionProtoType>());
12145 MarkVTableUsed(CurrentLocation, ClassDecl);
12146
12147 // Add a context note for diagnostics produced after this point.
12148 Scope.addContextNote(CurrentLocation);
12149
12150 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000012151 MoveConstructor->setInvalidDecl();
Richard Smith883dbc42017-05-25 22:47:05 +000012152 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000012153 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
12154 ? MoveConstructor->getLocEnd()
12155 : MoveConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012156 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000012157 MoveConstructor->setBody(ActOnCompoundStmt(
Daniel Jasperb3b0b802014-06-20 08:44:22 +000012158 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
Richard Smith883dbc42017-05-25 22:47:05 +000012159 MoveConstructor->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012160 }
12161
Sebastian Redl22653ba2011-08-30 19:58:05 +000012162 if (ASTMutationListener *L = getASTMutationListener()) {
12163 L->CompletedImplicitDefinition(MoveConstructor);
12164 }
12165}
12166
Douglas Gregor74f7d502012-02-15 19:33:52 +000012167bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000012168 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000012169}
Douglas Gregord3b672c2012-02-16 01:06:16 +000012170
12171void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000012172 SourceLocation CurrentLocation,
12173 CXXConversionDecl *Conv) {
Richard Smith883dbc42017-05-25 22:47:05 +000012174 SynthesizedFunctionScope Scope(*this, Conv);
Erich Keanebb863642017-09-20 22:28:24 +000012175
Faisal Vali571df122013-09-29 08:45:24 +000012176 CXXRecordDecl *Lambda = Conv->getParent();
12177 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
12178 // If we are defining a specialization of a conversion to function-ptr
12179 // cache the deduced template arguments for this specialization
12180 // so that we can use them to retrieve the corresponding call-operator
Erich Keanebb863642017-09-20 22:28:24 +000012181 // and static-invoker.
Craig Topperc3ec1492014-05-26 06:22:03 +000012182 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
12183
Faisal Vali571df122013-09-29 08:45:24 +000012184 // Retrieve the corresponding call-operator specialization.
12185 if (Lambda->isGenericLambda()) {
12186 assert(Conv->isFunctionTemplateSpecialization());
Erich Keanebb863642017-09-20 22:28:24 +000012187 FunctionTemplateDecl *CallOpTemplate =
Faisal Vali571df122013-09-29 08:45:24 +000012188 CallOp->getDescribedFunctionTemplate();
12189 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
Craig Topperc3ec1492014-05-26 06:22:03 +000012190 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000012191 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000012192 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000012193 InsertPos);
Erich Keanebb863642017-09-20 22:28:24 +000012194 assert(CallOpSpec &&
Faisal Vali571df122013-09-29 08:45:24 +000012195 "Conversion operator must have a corresponding call operator");
12196 CallOp = cast<CXXMethodDecl>(CallOpSpec);
12197 }
Richard Smith883dbc42017-05-25 22:47:05 +000012198
Faisal Vali571df122013-09-29 08:45:24 +000012199 // Mark the call operator referenced (and add to pending instantiations
12200 // if necessary).
12201 // For both the conversion and static-invoker template specializations
12202 // we construct their body's in this function, so no need to add them
12203 // to the PendingInstantiations.
12204 MarkFunctionReferenced(CurrentLocation, CallOp);
12205
Alp Tokerf6a24ce2013-12-05 16:25:25 +000012206 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000012207 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
12208 // ... and get the corresponding specialization for a generic lambda.
12209 if (Lambda->isGenericLambda()) {
Erich Keanebb863642017-09-20 22:28:24 +000012210 assert(DeducedTemplateArgs &&
Faisal Vali571df122013-09-29 08:45:24 +000012211 "Must have deduced template arguments from Conversion Operator");
Erich Keanebb863642017-09-20 22:28:24 +000012212 FunctionTemplateDecl *InvokeTemplate =
Faisal Vali571df122013-09-29 08:45:24 +000012213 Invoker->getDescribedFunctionTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +000012214 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000012215 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000012216 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000012217 InsertPos);
Erich Keanebb863642017-09-20 22:28:24 +000012218 assert(InvokeSpec &&
Faisal Vali571df122013-09-29 08:45:24 +000012219 "Must have a corresponding static invoker specialization");
12220 Invoker = cast<CXXMethodDecl>(InvokeSpec);
12221 }
12222 // Construct the body of the conversion function { return __invoke; }.
12223 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012224 VK_LValue, Conv->getLocation()).get();
Faisal Vali571df122013-09-29 08:45:24 +000012225 assert(FunctionRef && "Can't refer to __invoke function?");
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012226 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
Faisal Vali571df122013-09-29 08:45:24 +000012227 Conv->setBody(new (Context) CompoundStmt(Context, Return,
12228 Conv->getLocation(),
12229 Conv->getLocation()));
12230
12231 Conv->markUsed(Context);
12232 Conv->setReferenced();
Erich Keanebb863642017-09-20 22:28:24 +000012233
Faisal Vali571df122013-09-29 08:45:24 +000012234 // Fill in the __invoke function with a dummy implementation. IR generation
12235 // will fill in the actual details.
12236 Invoker->markUsed(Context);
12237 Invoker->setReferenced();
12238 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Erich Keanebb863642017-09-20 22:28:24 +000012239
Douglas Gregord3b672c2012-02-16 01:06:16 +000012240 if (ASTMutationListener *L = getASTMutationListener()) {
12241 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000012242 L->CompletedImplicitDefinition(Invoker);
Richard Smith883dbc42017-05-25 22:47:05 +000012243 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000012244}
12245
Faisal Vali571df122013-09-29 08:45:24 +000012246
12247
Douglas Gregord3b672c2012-02-16 01:06:16 +000012248void Sema::DefineImplicitLambdaToBlockPointerConversion(
12249 SourceLocation CurrentLocation,
Erich Keanebb863642017-09-20 22:28:24 +000012250 CXXConversionDecl *Conv)
Douglas Gregord3b672c2012-02-16 01:06:16 +000012251{
Faisal Vali850da1a2013-09-29 17:08:32 +000012252 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000012253
Eli Friedmaneaf34142012-10-18 20:14:08 +000012254 SynthesizedFunctionScope Scope(*this, Conv);
Erich Keanebb863642017-09-20 22:28:24 +000012255
Douglas Gregored90df32012-02-22 05:02:47 +000012256 // Copy-initialize the lambda object as needed to capture it.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012257 Expr *This = ActOnCXXThis(CurrentLocation).get();
12258 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
Erich Keanebb863642017-09-20 22:28:24 +000012259
Eli Friedman98b01ed2012-03-01 04:01:32 +000012260 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12261 Conv->getLocation(),
12262 Conv, DerefThis);
12263
12264 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12265 // behavior. Note that only the general conversion function does this
12266 // (since it's unusable otherwise); in the case where we inline the
12267 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012268 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000012269 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12270 CK_CopyAndAutoreleaseBlockObject,
Craig Topperc3ec1492014-05-26 06:22:03 +000012271 BuildBlock.get(), nullptr, VK_RValue);
Eli Friedman98b01ed2012-03-01 04:01:32 +000012272
12273 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000012274 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000012275 Conv->setInvalidDecl();
12276 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000012277 }
Douglas Gregored90df32012-02-22 05:02:47 +000012278
Douglas Gregored90df32012-02-22 05:02:47 +000012279 // Create the return statement that returns the block from the conversion
12280 // function.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000012281 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000012282 if (Return.isInvalid()) {
12283 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12284 Conv->setInvalidDecl();
12285 return;
12286 }
12287
12288 // Set the body of the conversion function.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012289 Stmt *ReturnS = Return.get();
Nico Webera2a0eb92012-12-29 20:03:39 +000012290 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Brian Kelley4afdfe82017-03-29 17:18:05 +000012291 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000012292 Conv->getLocation()));
Richard Smith883dbc42017-05-25 22:47:05 +000012293 Conv->markUsed(Context);
Erich Keanebb863642017-09-20 22:28:24 +000012294
Douglas Gregored90df32012-02-22 05:02:47 +000012295 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000012296 if (ASTMutationListener *L = getASTMutationListener()) {
12297 L->CompletedImplicitDefinition(Conv);
12298 }
12299}
12300
Erich Keanebb863642017-09-20 22:28:24 +000012301/// \brief Determine whether the given list arguments contains exactly one
Douglas Gregord2f70072012-03-10 06:53:13 +000012302/// "real" (non-default) argument.
12303static bool hasOneRealArgument(MultiExprArg Args) {
12304 switch (Args.size()) {
12305 case 0:
12306 return false;
Erich Keanebb863642017-09-20 22:28:24 +000012307
Douglas Gregord2f70072012-03-10 06:53:13 +000012308 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012309 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000012310 return false;
Erich Keanebb863642017-09-20 22:28:24 +000012311
Douglas Gregord2f70072012-03-10 06:53:13 +000012312 // fall through
12313 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012314 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000012315 }
Erich Keanebb863642017-09-20 22:28:24 +000012316
Douglas Gregord2f70072012-03-10 06:53:13 +000012317 return false;
12318}
12319
John McCalldadc5752010-08-24 06:29:42 +000012320ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000012321Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Richard Smithc2bebe92016-05-11 20:37:46 +000012322 NamedDecl *FoundDecl,
Mike Stump11289f42009-09-09 15:08:12 +000012323 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000012324 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012325 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000012326 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000012327 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000012328 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000012329 unsigned ConstructKind,
12330 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000012331 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000012332
Douglas Gregor45cf7e32010-04-02 18:24:57 +000012333 // C++0x [class.copy]p34:
12334 // When certain criteria are met, an implementation is allowed to
12335 // omit the copy/move construction of a class object, even if the
12336 // copy/move constructor and/or destructor for the object have
12337 // side effects. [...]
12338 // - when a temporary class object that has not been bound to a
12339 // reference (12.2) would be copied/moved to a class object
12340 // with the same cv-unqualified type, the copy/move operation
12341 // can be omitted by constructing the temporary object
12342 // directly into the target of the omitted copy/move
Richard Smith5179eb72016-06-28 19:03:57 +000012343 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
Douglas Gregord2f70072012-03-10 06:53:13 +000012344 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000012345 Expr *SubExpr = ExprArgs[0];
Richard Smith5179eb72016-06-28 19:03:57 +000012346 Elidable = SubExpr->isTemporaryObject(
12347 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
Anders Carlsson250aada2009-08-16 05:13:48 +000012348 }
Mike Stump11289f42009-09-09 15:08:12 +000012349
Richard Smithc2bebe92016-05-11 20:37:46 +000012350 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12351 FoundDecl, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012352 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithf8adcdc2014-07-17 05:12:35 +000012353 IsListInitialization,
12354 IsStdInitListInitialization, RequiresZeroInit,
Richard Smithd59b8322012-12-19 01:39:02 +000012355 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000012356}
12357
John McCalldadc5752010-08-24 06:29:42 +000012358ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000012359Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Richard Smithc2bebe92016-05-11 20:37:46 +000012360 NamedDecl *FoundDecl,
12361 CXXConstructorDecl *Constructor,
12362 bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000012363 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012364 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000012365 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000012366 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000012367 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000012368 unsigned ConstructKind,
12369 SourceRange ParenRange) {
Richard Smith80a47022016-06-29 01:10:27 +000012370 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
Richard Smith5179eb72016-06-28 19:03:57 +000012371 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
Richard Smith80a47022016-06-29 01:10:27 +000012372 if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
Erich Keanebb863642017-09-20 22:28:24 +000012373 return ExprError();
Richard Smith80a47022016-06-29 01:10:27 +000012374 }
Richard Smith5179eb72016-06-28 19:03:57 +000012375
Richard Smithc83bf822016-06-10 00:58:19 +000012376 return BuildCXXConstructExpr(
12377 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12378 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12379 RequiresZeroInit, ConstructKind, ParenRange);
12380}
12381
12382/// BuildCXXConstructExpr - Creates a complete call to a constructor,
12383/// including handling of its default argument expressions.
12384ExprResult
12385Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12386 CXXConstructorDecl *Constructor,
12387 bool Elidable,
12388 MultiExprArg ExprArgs,
12389 bool HadMultipleCandidates,
12390 bool IsListInitialization,
12391 bool IsStdInitListInitialization,
12392 bool RequiresZeroInit,
12393 unsigned ConstructKind,
12394 SourceRange ParenRange) {
Richard Smith5179eb72016-06-28 19:03:57 +000012395 assert(declaresSameEntity(
12396 Constructor->getParent(),
12397 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12398 "given constructor for wrong type");
Eli Friedmanfa0df832012-02-02 03:46:19 +000012399 MarkFunctionReferenced(ConstructLoc, Constructor);
Justin Lebar18e2d822016-08-15 23:00:49 +000012400 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
12401 return ExprError();
Richard Smith5179eb72016-06-28 19:03:57 +000012402
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012403 return CXXConstructExpr::Create(
Richard Smithc83bf822016-06-10 00:58:19 +000012404 Context, DeclInitType, ConstructLoc, Constructor, Elidable,
Richard Smithc2bebe92016-05-11 20:37:46 +000012405 ExprArgs, HadMultipleCandidates, IsListInitialization,
12406 IsStdInitListInitialization, RequiresZeroInit,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012407 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12408 ParenRange);
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000012409}
12410
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012411ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12412 assert(Field->hasInClassInitializer());
12413
12414 // If we already have the in-class initializer nothing needs to be done.
12415 if (Field->getInClassInitializer())
12416 return CXXDefaultInitExpr::Create(Context, Loc, Field);
12417
Richard Smithd6a15082017-01-07 00:48:55 +000012418 // If we might have already tried and failed to instantiate, don't try again.
12419 if (Field->isInvalidDecl())
12420 return ExprError();
12421
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012422 // Maybe we haven't instantiated the in-class initializer. Go check the
12423 // pattern FieldDecl to see if it has one.
12424 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12425
12426 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12427 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12428 DeclContext::lookup_result Lookup =
12429 ClassPattern->lookup(Field->getDeclName());
Reid Kleckner327b0642016-04-29 18:06:53 +000012430
12431 // Lookup can return at most two results: the pattern for the field, or the
12432 // injected class name of the parent record. No other member can have the
12433 // same name as the field.
Vassil Vassileve53a4b72016-10-26 10:24:29 +000012434 // In modules mode, lookup can return multiple results (coming from
12435 // different modules).
12436 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
Reid Kleckner327b0642016-04-29 18:06:53 +000012437 "more than two lookup results for field name");
12438 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
12439 if (!Pattern) {
12440 assert(isa<CXXRecordDecl>(Lookup[0]) &&
12441 "cannot have other non-field member with same name");
Vassil Vassileve53a4b72016-10-26 10:24:29 +000012442 for (auto L : Lookup)
12443 if (isa<FieldDecl>(L)) {
12444 Pattern = cast<FieldDecl>(L);
12445 break;
12446 }
12447 assert(Pattern && "We must have set the Pattern!");
Reid Kleckner327b0642016-04-29 18:06:53 +000012448 }
12449
Erich Keane0ac95242017-09-18 21:28:55 +000012450 if (!Pattern->hasInClassInitializer() ||
12451 InstantiateInClassInitializer(Loc, Field, Pattern,
Richard Smithd6a15082017-01-07 00:48:55 +000012452 getTemplateInstantiationArgs(Field))) {
12453 // Don't diagnose this again.
12454 Field->setInvalidDecl();
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012455 return ExprError();
Richard Smithd6a15082017-01-07 00:48:55 +000012456 }
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012457 return CXXDefaultInitExpr::Create(Context, Loc, Field);
12458 }
12459
12460 // DR1351:
12461 // If the brace-or-equal-initializer of a non-static data member
12462 // invokes a defaulted default constructor of its class or of an
12463 // enclosing class in a potentially evaluated subexpression, the
12464 // program is ill-formed.
12465 //
12466 // This resolution is unworkable: the exception specification of the
12467 // default constructor can be needed in an unevaluated context, in
12468 // particular, in the operand of a noexcept-expression, and we can be
12469 // unable to compute an exception specification for an enclosed class.
12470 //
12471 // Any attempt to resolve the exception specification of a defaulted default
12472 // constructor before the initializer is lexically complete will ultimately
12473 // come here at which point we can diagnose it.
12474 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
Richard Smith8dbc6b22016-11-22 22:55:12 +000012475 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
12476 << OutermostClass << Field;
12477 Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
Richard Smith8d148352017-01-23 23:14:23 +000012478 // Recover by marking the field invalid, unless we're in a SFINAE context.
12479 if (!isSFINAEContext())
12480 Field->setInvalidDecl();
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012481 return ExprError();
12482}
12483
John McCall03c48482010-02-02 09:10:11 +000012484void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000012485 if (VD->isInvalidDecl()) return;
12486
John McCall03c48482010-02-02 09:10:11 +000012487 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000012488 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000012489 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000012490 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000012491
Chandler Carruth86d17d32011-03-27 21:26:48 +000012492 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000012493 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000012494 CheckDestructorAccess(VD->getLocation(), Destructor,
12495 PDiag(diag::err_access_dtor_var)
12496 << VD->getDeclName()
12497 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000012498 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000012499
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000012500 if (Destructor->isTrivial()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000012501 if (!VD->hasGlobalStorage()) return;
12502
12503 // Emit warning for non-trivial dtor in global scope (a real global,
12504 // class-static, function-static).
12505 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
12506
12507 // TODO: this should be re-enabled for static locals by !CXAAtExit
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000012508 if (!VD->isStaticLocal())
Chandler Carruth86d17d32011-03-27 21:26:48 +000012509 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000012510}
12511
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012512/// \brief Given a constructor and the set of arguments provided for the
12513/// constructor, convert the arguments and add any required default arguments
12514/// to form a proper call to this constructor.
12515///
12516/// \returns true if an error occurred, false otherwise.
Erich Keanebb863642017-09-20 22:28:24 +000012517bool
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012518Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
12519 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000012520 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000012521 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000012522 bool AllowExplicit,
12523 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012524 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
12525 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000012526 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012527
Erich Keanebb863642017-09-20 22:28:24 +000012528 const FunctionProtoType *Proto
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012529 = Constructor->getType()->getAs<FunctionProtoType>();
12530 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012531 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000012532
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012533 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012534 if (NumArgs < NumParams)
12535 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012536 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012537 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012538
Erich Keanebb863642017-09-20 22:28:24 +000012539 VariadicCallType CallType =
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012540 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012541 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012542 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012543 Proto, 0,
12544 llvm::makeArrayRef(Args, NumArgs),
12545 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000012546 CallType, AllowExplicit,
12547 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000012548 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000012549
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012550 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012551
Dmitri Gribenko765396f2013-01-13 20:46:02 +000012552 CheckConstructorCall(Constructor,
Craig Topper8c2a2a02014-08-30 16:55:39 +000012553 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000012554 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012555
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012556 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000012557}
12558
Anders Carlssone363c8e2009-12-12 00:32:00 +000012559static inline bool
Erich Keanebb863642017-09-20 22:28:24 +000012560CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
Anders Carlssone363c8e2009-12-12 00:32:00 +000012561 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000012562 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000012563 if (isa<NamespaceDecl>(DC)) {
Erich Keanebb863642017-09-20 22:28:24 +000012564 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlssone363c8e2009-12-12 00:32:00 +000012565 diag::err_operator_new_delete_declared_in_namespace)
12566 << FnDecl->getDeclName();
12567 }
Erich Keanebb863642017-09-20 22:28:24 +000012568
12569 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000012570 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000012571 return SemaRef.Diag(FnDecl->getLocation(),
12572 diag::err_operator_new_delete_declared_static)
12573 << FnDecl->getDeclName();
12574 }
Erich Keanebb863642017-09-20 22:28:24 +000012575
Anders Carlsson60659a82009-12-12 02:43:16 +000012576 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000012577}
12578
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012579static inline bool
12580CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
12581 CanQualType ExpectedResultType,
12582 CanQualType ExpectedFirstParamType,
12583 unsigned DependentParamTypeDiag,
12584 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000012585 QualType ResultType =
12586 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012587
12588 // Check that the result type is not dependent.
12589 if (ResultType->isDependentType())
12590 return SemaRef.Diag(FnDecl->getLocation(),
12591 diag::err_operator_new_delete_dependent_result_type)
12592 << FnDecl->getDeclName() << ExpectedResultType;
12593
12594 // Check that the result type is what we expect.
12595 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
12596 return SemaRef.Diag(FnDecl->getLocation(),
Erich Keanebb863642017-09-20 22:28:24 +000012597 diag::err_operator_new_delete_invalid_result_type)
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012598 << FnDecl->getDeclName() << ExpectedResultType;
Erich Keanebb863642017-09-20 22:28:24 +000012599
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012600 // A function template must have at least 2 parameters.
12601 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
12602 return SemaRef.Diag(FnDecl->getLocation(),
12603 diag::err_operator_new_delete_template_too_few_parameters)
12604 << FnDecl->getDeclName();
Erich Keanebb863642017-09-20 22:28:24 +000012605
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012606 // The function decl must have at least 1 parameter.
12607 if (FnDecl->getNumParams() == 0)
12608 return SemaRef.Diag(FnDecl->getLocation(),
12609 diag::err_operator_new_delete_too_few_parameters)
12610 << FnDecl->getDeclName();
Erich Keanebb863642017-09-20 22:28:24 +000012611
Sylvestre Ledru830885c2012-07-23 08:59:39 +000012612 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012613 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
12614 if (FirstParamType->isDependentType())
12615 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
12616 << FnDecl->getDeclName() << ExpectedFirstParamType;
12617
12618 // Check that the first parameter type is what we expect.
Erich Keanebb863642017-09-20 22:28:24 +000012619 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012620 ExpectedFirstParamType)
12621 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
12622 << FnDecl->getDeclName() << ExpectedFirstParamType;
Erich Keanebb863642017-09-20 22:28:24 +000012623
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012624 return false;
12625}
12626
Anders Carlsson12308f42009-12-11 23:23:22 +000012627static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012628CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000012629 // C++ [basic.stc.dynamic.allocation]p1:
12630 // A program is ill-formed if an allocation function is declared in a
Erich Keanebb863642017-09-20 22:28:24 +000012631 // namespace scope other than global scope or declared static in global
Anders Carlssone363c8e2009-12-12 00:32:00 +000012632 // scope.
12633 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12634 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012635
Erich Keanebb863642017-09-20 22:28:24 +000012636 CanQualType SizeTy =
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012637 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
12638
12639 // C++ [basic.stc.dynamic.allocation]p1:
Erich Keanebb863642017-09-20 22:28:24 +000012640 // The return type shall be void*. The first parameter shall have type
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012641 // std::size_t.
Erich Keanebb863642017-09-20 22:28:24 +000012642 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012643 SizeTy,
12644 diag::err_operator_new_dependent_param_type,
12645 diag::err_operator_new_param_type))
12646 return true;
12647
12648 // C++ [basic.stc.dynamic.allocation]p1:
12649 // The first parameter shall not have an associated default argument.
12650 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000012651 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012652 diag::err_operator_new_default_arg)
12653 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
12654
12655 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000012656}
12657
12658static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000012659CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000012660 // C++ [basic.stc.dynamic.deallocation]p1:
12661 // A program is ill-formed if deallocation functions are declared in a
Erich Keanebb863642017-09-20 22:28:24 +000012662 // namespace scope other than global scope or declared static in global
Anders Carlsson12308f42009-12-11 23:23:22 +000012663 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000012664 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12665 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000012666
12667 // C++ [basic.stc.dynamic.deallocation]p2:
Erich Keanebb863642017-09-20 22:28:24 +000012668 // Each deallocation function shall return void and its first parameter
Anders Carlsson12308f42009-12-11 23:23:22 +000012669 // shall be void*.
Erich Keanebb863642017-09-20 22:28:24 +000012670 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012671 SemaRef.Context.VoidPtrTy,
12672 diag::err_operator_delete_dependent_param_type,
12673 diag::err_operator_delete_param_type))
12674 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000012675
Anders Carlsson12308f42009-12-11 23:23:22 +000012676 return false;
12677}
12678
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012679/// CheckOverloadedOperatorDeclaration - Check whether the declaration
12680/// of this overloaded operator is well-formed. If so, returns false;
12681/// otherwise, emits appropriate diagnostics and returns true.
12682bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000012683 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012684 "Expected an overloaded operator declaration");
12685
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012686 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
12687
Mike Stump11289f42009-09-09 15:08:12 +000012688 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012689 // The allocation and deallocation functions, operator new,
12690 // operator new[], operator delete and operator delete[], are
12691 // described completely in 3.7.3. The attributes and restrictions
12692 // found in the rest of this subclause do not apply to them unless
12693 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000012694 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000012695 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Erich Keanebb863642017-09-20 22:28:24 +000012696
Anders Carlsson22f443f2009-12-12 00:26:23 +000012697 if (Op == OO_New || Op == OO_Array_New)
12698 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012699
12700 // C++ [over.oper]p6:
12701 // An operator function shall either be a non-static member
12702 // function or be a non-member function and have at least one
12703 // parameter whose type is a class, a reference to a class, an
12704 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000012705 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
12706 if (MethodDecl->isStatic())
12707 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012708 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012709 } else {
12710 bool ClassOrEnumParam = false;
David Majnemer59f77922016-06-24 04:05:48 +000012711 for (auto Param : FnDecl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012712 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000012713 if (ParamType->isDependentType() || ParamType->isRecordType() ||
12714 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012715 ClassOrEnumParam = true;
12716 break;
12717 }
12718 }
12719
Douglas Gregord69246b2008-11-17 16:14:12 +000012720 if (!ClassOrEnumParam)
12721 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000012722 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012723 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012724 }
12725
12726 // C++ [over.oper]p8:
12727 // An operator function cannot have default arguments (8.3.6),
12728 // except where explicitly stated below.
12729 //
Mike Stump11289f42009-09-09 15:08:12 +000012730 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012731 // (C++ [over.call]p1).
12732 if (Op != OO_Call) {
David Majnemer59f77922016-06-24 04:05:48 +000012733 for (auto Param : FnDecl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012734 if (Param->hasDefaultArg())
12735 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000012736 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012737 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012738 }
12739 }
12740
Douglas Gregor6cf08062008-11-10 13:38:07 +000012741 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
12742 { false, false, false }
12743#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
12744 , { Unary, Binary, MemberOnly }
12745#include "clang/Basic/OperatorKinds.def"
12746 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012747
Douglas Gregor6cf08062008-11-10 13:38:07 +000012748 bool CanBeUnaryOperator = OperatorUses[Op][0];
12749 bool CanBeBinaryOperator = OperatorUses[Op][1];
12750 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012751
12752 // C++ [over.oper]p8:
12753 // [...] Operator functions cannot have more or fewer parameters
12754 // than the number required for the corresponding operator, as
12755 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000012756 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000012757 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012758 if (Op != OO_Call &&
12759 ((NumParams == 1 && !CanBeUnaryOperator) ||
12760 (NumParams == 2 && !CanBeBinaryOperator) ||
12761 (NumParams < 1) || (NumParams > 2))) {
12762 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012763 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000012764 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012765 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000012766 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012767 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000012768 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000012769 assert(CanBeBinaryOperator &&
12770 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012771 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000012772 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012773
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012774 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012775 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012776 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000012777
Douglas Gregord69246b2008-11-17 16:14:12 +000012778 // Overloaded operators other than operator() cannot be variadic.
12779 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000012780 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000012781 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012782 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012783 }
12784
12785 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000012786 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
12787 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000012788 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012789 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012790 }
12791
12792 // C++ [over.inc]p1:
12793 // The user-defined function called operator++ implements the
12794 // prefix and postfix ++ operator. If this function is a member
12795 // function with no parameters, or a non-member function with one
12796 // parameter of class or enumeration type, it defines the prefix
12797 // increment operator ++ for objects of that type. If the function
12798 // is a member function with one parameter (which shall be of type
12799 // int) or a non-member function with two parameters (the second
12800 // of which shall be of type int), it defines the postfix
12801 // increment operator ++ for objects of that type.
12802 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
12803 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000012804 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012805
Richard Smith538b52a2014-01-30 22:24:05 +000012806 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
12807 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000012808 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000012809 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000012810 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012811 }
12812
Douglas Gregord69246b2008-11-17 16:14:12 +000012813 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012814}
Chris Lattner3b024a32008-12-17 07:09:26 +000012815
Richard Smithc28aee62016-02-17 00:04:04 +000012816static bool
12817checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
12818 FunctionTemplateDecl *TpDecl) {
12819 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
12820
12821 // Must have one or two template parameters.
12822 if (TemplateParams->size() == 1) {
12823 NonTypeTemplateParmDecl *PmDecl =
12824 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
12825
12826 // The template parameter must be a char parameter pack.
12827 if (PmDecl && PmDecl->isTemplateParameterPack() &&
12828 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
12829 return false;
12830
12831 } else if (TemplateParams->size() == 2) {
12832 TemplateTypeParmDecl *PmType =
12833 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
12834 NonTypeTemplateParmDecl *PmArgs =
12835 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
12836
12837 // The second template parameter must be a parameter pack with the
12838 // first template parameter as its type.
12839 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
12840 PmArgs->isTemplateParameterPack()) {
12841 const TemplateTypeParmType *TArgs =
12842 PmArgs->getType()->getAs<TemplateTypeParmType>();
12843 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
12844 TArgs->getIndex() == PmType->getIndex()) {
Richard Smith51ec0cf2017-02-21 01:17:38 +000012845 if (!SemaRef.inTemplateInstantiation())
Richard Smithc28aee62016-02-17 00:04:04 +000012846 SemaRef.Diag(TpDecl->getLocation(),
12847 diag::ext_string_literal_operator_template);
12848 return false;
12849 }
12850 }
12851 }
12852
12853 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
12854 diag::err_literal_operator_template)
12855 << TpDecl->getTemplateParameters()->getSourceRange();
12856 return true;
12857}
12858
Alexis Huntc88db062010-01-13 09:01:02 +000012859/// CheckLiteralOperatorDeclaration - Check whether the declaration
12860/// of this literal operator function is well-formed. If so, returns
12861/// false; otherwise, emits appropriate diagnostics and returns true.
12862bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000012863 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000012864 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
12865 << FnDecl->getDeclName();
12866 return true;
12867 }
12868
Richard Smith72eebee2012-03-04 09:41:16 +000012869 if (FnDecl->isExternC()) {
12870 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
Alex Lorenz560ae562016-11-02 15:46:34 +000012871 if (const LinkageSpecDecl *LSD =
12872 FnDecl->getDeclContext()->getExternCContext())
12873 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
Richard Smith72eebee2012-03-04 09:41:16 +000012874 return true;
12875 }
12876
Richard Smithbcc22fc2012-03-09 08:00:36 +000012877 // This might be the definition of a literal operator template.
12878 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
Richard Smithc28aee62016-02-17 00:04:04 +000012879
Richard Smithbcc22fc2012-03-09 08:00:36 +000012880 // This might be a specialization of a literal operator template.
12881 if (!TpDecl)
12882 TpDecl = FnDecl->getPrimaryTemplate();
12883
Richard Smithb8b41d32013-10-07 19:57:58 +000012884 // template <char...> type operator "" name() and
12885 // template <class T, T...> type operator "" name() are the only valid
12886 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000012887 if (TpDecl) {
Richard Smithc28aee62016-02-17 00:04:04 +000012888 if (FnDecl->param_size() != 0) {
12889 Diag(FnDecl->getLocation(),
12890 diag::err_literal_operator_template_with_params);
12891 return true;
Alexis Hunt7dd26172010-04-07 23:11:06 +000012892 }
Richard Smithc28aee62016-02-17 00:04:04 +000012893
12894 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
12895 return true;
12896
12897 } else if (FnDecl->param_size() == 1) {
12898 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
12899
12900 QualType ParamType = Param->getType().getUnqualifiedType();
12901
12902 // Only unsigned long long int, long double, any character type, and const
12903 // char * are allowed as the only parameters.
12904 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
12905 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
12906 Context.hasSameType(ParamType, Context.CharTy) ||
12907 Context.hasSameType(ParamType, Context.WideCharTy) ||
12908 Context.hasSameType(ParamType, Context.Char16Ty) ||
12909 Context.hasSameType(ParamType, Context.Char32Ty)) {
12910 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
12911 QualType InnerType = Ptr->getPointeeType();
12912
12913 // Pointer parameter must be a const char *.
12914 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
12915 Context.CharTy) &&
12916 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
12917 Diag(Param->getSourceRange().getBegin(),
12918 diag::err_literal_operator_param)
12919 << ParamType << "'const char *'" << Param->getSourceRange();
12920 return true;
12921 }
12922
12923 } else if (ParamType->isRealFloatingType()) {
12924 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12925 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
12926 return true;
12927
12928 } else if (ParamType->isIntegerType()) {
12929 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12930 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
12931 return true;
12932
12933 } else {
12934 Diag(Param->getSourceRange().getBegin(),
12935 diag::err_literal_operator_invalid_param)
12936 << ParamType << Param->getSourceRange();
12937 return true;
12938 }
12939
12940 } else if (FnDecl->param_size() == 2) {
Alexis Hunt7dd26172010-04-07 23:11:06 +000012941 FunctionDecl::param_iterator Param = FnDecl->param_begin();
12942
Richard Smithc28aee62016-02-17 00:04:04 +000012943 // First, verify that the first parameter is correct.
Alexis Huntc88db062010-01-13 09:01:02 +000012944
Richard Smithc28aee62016-02-17 00:04:04 +000012945 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
12946
12947 // Two parameter function must have a pointer to const as a
12948 // first parameter; let's strip those qualifiers.
12949 const PointerType *PT = FirstParamType->getAs<PointerType>();
12950
12951 if (!PT) {
12952 Diag((*Param)->getSourceRange().getBegin(),
12953 diag::err_literal_operator_param)
12954 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12955 return true;
Alexis Huntc88db062010-01-13 09:01:02 +000012956 }
12957
Richard Smithc28aee62016-02-17 00:04:04 +000012958 QualType PointeeType = PT->getPointeeType();
12959 // First parameter must be const
12960 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
12961 Diag((*Param)->getSourceRange().getBegin(),
12962 diag::err_literal_operator_param)
12963 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12964 return true;
12965 }
Alexis Huntc88db062010-01-13 09:01:02 +000012966
Richard Smithc28aee62016-02-17 00:04:04 +000012967 QualType InnerType = PointeeType.getUnqualifiedType();
12968 // Only const char *, const wchar_t*, const char16_t*, and const char32_t*
12969 // are allowed as the first parameter to a two-parameter function
12970 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
12971 Context.hasSameType(InnerType, Context.WideCharTy) ||
12972 Context.hasSameType(InnerType, Context.Char16Ty) ||
12973 Context.hasSameType(InnerType, Context.Char32Ty))) {
12974 Diag((*Param)->getSourceRange().getBegin(),
12975 diag::err_literal_operator_param)
12976 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12977 return true;
12978 }
12979
12980 // Move on to the second and final parameter.
Alexis Huntc88db062010-01-13 09:01:02 +000012981 ++Param;
12982
Richard Smithc28aee62016-02-17 00:04:04 +000012983 // The second parameter must be a std::size_t.
12984 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
12985 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
12986 Diag((*Param)->getSourceRange().getBegin(),
12987 diag::err_literal_operator_param)
12988 << SecondParamType << Context.getSizeType()
12989 << (*Param)->getSourceRange();
12990 return true;
Alexis Huntc88db062010-01-13 09:01:02 +000012991 }
Richard Smithc28aee62016-02-17 00:04:04 +000012992 } else {
12993 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
Alexis Huntc88db062010-01-13 09:01:02 +000012994 return true;
12995 }
12996
Richard Smithc28aee62016-02-17 00:04:04 +000012997 // Parameters are good.
12998
Richard Smith768cecc2012-03-09 08:16:22 +000012999 // A parameter-declaration-clause containing a default argument is not
13000 // equivalent to any of the permitted forms.
David Majnemer59f77922016-06-24 04:05:48 +000013001 for (auto Param : FnDecl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000013002 if (Param->hasDefaultArg()) {
13003 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000013004 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000013005 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000013006 break;
13007 }
13008 }
13009
Richard Smith0df56f42012-03-08 02:39:21 +000013010 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000013011 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13012 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000013013 // C++11 [usrlit.suffix]p1:
13014 // Literal suffix identifiers that do not start with an underscore
13015 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000013016 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
Eric Fiseliercb2f3262016-12-30 04:51:10 +000013017 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000013018 }
Richard Smith0df56f42012-03-08 02:39:21 +000013019
Alexis Huntc88db062010-01-13 09:01:02 +000013020 return false;
13021}
13022
Douglas Gregor07665a62009-01-05 19:45:36 +000013023/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13024/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000013025/// the '{'. ExternLoc is the location of the 'extern', Lang is the
13026/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000013027/// the '{' brace. Otherwise, this linkage specification does not
13028/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000013029Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000013030 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000013031 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000013032 StringLiteral *Lit = cast<StringLiteral>(LangStr);
13033 if (!Lit->isAscii()) {
13034 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13035 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000013036 return nullptr;
Richard Smith4ee696d2014-02-17 23:25:27 +000013037 }
13038
13039 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000013040 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000013041 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000013042 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000013043 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000013044 Language = LinkageSpecDecl::lang_cxx;
13045 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000013046 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13047 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000013048 return nullptr;
Chris Lattner438e5012008-12-17 07:13:27 +000013049 }
Mike Stump11289f42009-09-09 15:08:12 +000013050
Chris Lattner438e5012008-12-17 07:13:27 +000013051 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000013052
Richard Smith4ee696d2014-02-17 23:25:27 +000013053 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13054 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000013055 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000013056 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000013057 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000013058 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000013059}
13060
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000013061/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000013062/// the C++ linkage specification LinkageSpec. If RBraceLoc is
13063/// valid, it's the position of the closing '}' brace in a linkage
13064/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000013065Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000013066 Decl *LinkageSpec,
13067 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000013068 if (RBraceLoc.isValid()) {
13069 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13070 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000013071 }
Richard Smith4ee696d2014-02-17 23:25:27 +000013072 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000013073 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000013074}
13075
Michael Han84324352013-02-22 17:15:32 +000013076Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13077 AttributeList *AttrList,
13078 SourceLocation SemiLoc) {
13079 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13080 // Attribute declarations appertain to empty declaration so we handle
13081 // them here.
13082 if (AttrList)
13083 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000013084
Michael Han84324352013-02-22 17:15:32 +000013085 CurContext->addDecl(ED);
13086 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000013087}
13088
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013089/// \brief Perform semantic analysis for the variable declaration that
13090/// occurs within a C++ catch clause, returning the newly-created
13091/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000013092VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000013093 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000013094 SourceLocation StartLoc,
13095 SourceLocation Loc,
13096 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013097 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000013098 QualType ExDeclType = TInfo->getType();
Erich Keanebb863642017-09-20 22:28:24 +000013099
Sebastian Redl54c04d42008-12-22 19:15:10 +000013100 // Arrays and functions decay.
13101 if (ExDeclType->isArrayType())
13102 ExDeclType = Context.getArrayDecayedType(ExDeclType);
13103 else if (ExDeclType->isFunctionType())
13104 ExDeclType = Context.getPointerType(ExDeclType);
13105
13106 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13107 // The exception-declaration shall not denote a pointer or reference to an
13108 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000013109 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000013110 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000013111 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000013112 Invalid = true;
13113 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013114
David Majnemere56d1a02016-06-08 16:05:07 +000013115 if (ExDeclType->isVariablyModifiedType()) {
13116 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13117 Invalid = true;
13118 }
13119
Sebastian Redl54c04d42008-12-22 19:15:10 +000013120 QualType BaseType = ExDeclType;
13121 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000013122 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000013123 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000013124 BaseType = Ptr->getPointeeType();
13125 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000013126 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000013127 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000013128 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000013129 BaseType = Ref->getPointeeType();
13130 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000013131 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000013132 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000013133 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000013134 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000013135 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000013136
Mike Stump11289f42009-09-09 15:08:12 +000013137 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013138 RequireNonAbstractType(Loc, ExDeclType,
13139 diag::err_abstract_type_in_decl,
13140 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000013141 Invalid = true;
13142
John McCall2ca705e2010-07-24 00:37:23 +000013143 // Only the non-fragile NeXT runtime currently supports C++ catches
13144 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000013145 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000013146 QualType T = ExDeclType;
13147 if (const ReferenceType *RT = T->getAs<ReferenceType>())
13148 T = RT->getPointeeType();
13149
13150 if (T->isObjCObjectType()) {
13151 Diag(Loc, diag::err_objc_object_catch);
13152 Invalid = true;
13153 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000013154 // FIXME: should this be a test for macosx-fragile specifically?
13155 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000013156 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000013157 }
13158 }
13159
Abramo Bagnaradff19302011-03-08 08:55:46 +000013160 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000013161 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000013162 ExDecl->setExceptionVariable(true);
Erich Keanebb863642017-09-20 22:28:24 +000013163
Douglas Gregor8ca0c642011-12-10 01:22:52 +000013164 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000013165 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000013166 Invalid = true;
13167
Douglas Gregor750734c2011-07-06 18:14:43 +000013168 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000013169 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000013170 // Insulate this from anything else we might currently be parsing.
Faisal Valid143a0c2017-04-01 21:30:49 +000013171 EnterExpressionEvaluationContext scope(
13172 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
John McCalleaef89b2013-03-22 02:10:40 +000013173
Douglas Gregor6de584c2010-03-05 23:38:39 +000013174 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000013175 // The object declared in an exception-declaration or, if the
13176 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000013177 // copy-initialized (8.5) from the exception object. [...]
13178 // The object is destroyed when the handler exits, after the destruction
13179 // of any automatic objects initialized within the handler.
13180 //
Nick Lewycky0f292892013-09-22 10:06:57 +000013181 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000013182 // it can be destroyed later.
David Majnemerfba75df2015-03-03 04:38:34 +000013183 QualType initType = Context.getExceptionObjectType(ExDeclType);
John McCall1bf58462011-02-16 08:02:54 +000013184
13185 InitializedEntity entity =
13186 InitializedEntity::InitializeVariable(ExDecl);
13187 InitializationKind initKind =
13188 InitializationKind::CreateCopy(Loc, SourceLocation());
13189
13190 Expr *opaqueValue =
13191 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000013192 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13193 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000013194 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000013195 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000013196 else {
13197 // If the constructor used was non-trivial, set this as the
13198 // "initializer".
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013199 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000013200 if (!construct->getConstructor()->isTrivial()) {
13201 Expr *init = MaybeCreateExprWithCleanups(construct);
13202 ExDecl->setInit(init);
13203 }
Erich Keanebb863642017-09-20 22:28:24 +000013204
John McCall1bf58462011-02-16 08:02:54 +000013205 // And make sure it's destructable.
13206 FinalizeVarWithDestructor(ExDecl, recordType);
13207 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000013208 }
13209 }
Erich Keanebb863642017-09-20 22:28:24 +000013210
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013211 if (Invalid)
13212 ExDecl->setInvalidDecl();
13213
13214 return ExDecl;
13215}
13216
13217/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13218/// handler.
John McCall48871652010-08-21 09:40:31 +000013219Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000013220 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000013221 bool Invalid = D.isInvalidType();
13222
13223 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000013224 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13225 UPPC_ExceptionType)) {
Erich Keanebb863642017-09-20 22:28:24 +000013226 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
Douglas Gregor72772f62010-12-16 17:48:04 +000013227 D.getIdentifierLoc());
13228 Invalid = true;
13229 }
13230
Sebastian Redl54c04d42008-12-22 19:15:10 +000013231 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000013232 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000013233 LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +000013234 ForVisibleRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000013235 // The scope should be freshly made just for us. There is just no way
Aaron Ballman9ef622e2014-06-02 13:10:07 +000013236 // it contains any previous declaration, except for function parameters in
13237 // a function-try-block's catch statement.
John McCall48871652010-08-21 09:40:31 +000013238 assert(!S->isDeclScope(PrevDecl));
Aaron Ballman9ef622e2014-06-02 13:10:07 +000013239 if (isDeclInScope(PrevDecl, CurContext, S)) {
13240 Diag(D.getIdentifierLoc(), diag::err_redefinition)
13241 << D.getIdentifier();
13242 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13243 Invalid = true;
13244 } else if (PrevDecl->isTemplateParameter())
Sebastian Redl54c04d42008-12-22 19:15:10 +000013245 // Maybe we will complain about the shadowed template parameter.
13246 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000013247 }
13248
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000013249 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000013250 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13251 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000013252 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000013253 }
13254
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000013255 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013256 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000013257 D.getIdentifierLoc(),
13258 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000013259 if (Invalid)
13260 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000013261
Sebastian Redl54c04d42008-12-22 19:15:10 +000013262 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000013263 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013264 PushOnScopeChains(ExDecl, S);
13265 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000013266 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000013267
Douglas Gregor758a8692009-06-17 21:51:59 +000013268 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000013269 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000013270}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000013271
Abramo Bagnaraea947882011-03-08 16:41:52 +000013272Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000013273 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000013274 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000013275 SourceLocation RParenLoc) {
Richard Smith085a64f2014-06-20 19:57:12 +000013276 StringLiteral *AssertMessage =
13277 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000013278
Richard Smithded9c2e2012-07-11 22:37:56 +000013279 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
Craig Topperc3ec1492014-05-26 06:22:03 +000013280 return nullptr;
Richard Smithded9c2e2012-07-11 22:37:56 +000013281
13282 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13283 AssertMessage, RParenLoc, false);
13284}
13285
13286Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13287 Expr *AssertExpr,
13288 StringLiteral *AssertMessage,
13289 SourceLocation RParenLoc,
13290 bool Failed) {
Richard Smith085a64f2014-06-20 19:57:12 +000013291 assert(AssertExpr != nullptr && "Expected non-null condition");
Richard Smithded9c2e2012-07-11 22:37:56 +000013292 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13293 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000013294 // In a static_assert-declaration, the constant-expression shall be a
13295 // constant expression that can be contextually converted to bool.
13296 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13297 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000013298 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000013299
Richard Smith902ca212011-12-14 23:32:26 +000013300 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000013301 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000013302 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000013303 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000013304 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000013305
Richard Smithded9c2e2012-07-11 22:37:56 +000013306 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013307 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000013308 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith085a64f2014-06-20 19:57:12 +000013309 if (AssertMessage)
13310 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
Douglas Gregor672281a2017-09-14 23:38:42 +000013311
13312 Expr *InnerCond = nullptr;
13313 std::string InnerCondDescription;
13314 std::tie(InnerCond, InnerCondDescription) =
13315 findFailedBooleanCondition(Converted.get(),
13316 /*AllowTopLevelCond=*/false);
13317 if (InnerCond) {
13318 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
13319 << InnerCondDescription << !AssertMessage
13320 << Msg.str() << InnerCond->getSourceRange();
13321 } else {
13322 Diag(StaticAssertLoc, diag::err_static_assert_failed)
13323 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
13324 }
Richard Smithded9c2e2012-07-11 22:37:56 +000013325 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000013326 }
Anders Carlsson54b26982009-03-14 00:33:21 +000013327 }
Mike Stump11289f42009-09-09 15:08:12 +000013328
Richard Smithb3018062017-06-06 01:34:24 +000013329 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
13330 /*DiscardedValue*/false,
13331 /*IsConstexpr*/true);
13332 if (FullAssertExpr.isInvalid())
13333 Failed = true;
13334 else
13335 AssertExpr = FullAssertExpr.get();
13336
Abramo Bagnaraea947882011-03-08 16:41:52 +000013337 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000013338 AssertExpr, AssertMessage, RParenLoc,
13339 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000013340
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000013341 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000013342 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000013343}
Sebastian Redlf769df52009-03-24 22:27:57 +000013344
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013345/// \brief Perform semantic analysis of the given friend type declaration.
13346///
13347/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000013348FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000013349 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013350 TypeSourceInfo *TSInfo) {
13351 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
Erich Keanebb863642017-09-20 22:28:24 +000013352
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013353 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000013354 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Erich Keanebb863642017-09-20 22:28:24 +000013355
Richard Smithc8239732011-10-18 21:39:00 +000013356 // C++03 [class.friend]p2:
13357 // An elaborated-type-specifier shall be used in a friend declaration
13358 // for a class.*
13359 //
13360 // * The class-key of the elaborated-type-specifier is required.
Richard Smith696e3122017-02-23 01:43:54 +000013361 if (!CodeSynthesisContexts.empty()) {
13362 // Do not complain about the form of friend template types during any kind
13363 // of code synthesis. For template instantiation, we will have complained
13364 // when the template was defined.
Nick Lewycky36722d22013-02-06 05:59:33 +000013365 } else {
13366 if (!T->isElaboratedTypeSpecifier()) {
13367 // If we evaluated the type to a record type, suggest putting
13368 // a tag in front.
13369 if (const RecordType *RT = T->getAs<RecordType>()) {
13370 RecordDecl *RD = RT->getDecl();
Alp Tokera030cd02014-05-05 12:38:48 +000013371
13372 SmallString<16> InsertionText(" ");
13373 InsertionText += RD->getKindName();
13374
Nick Lewycky36722d22013-02-06 05:59:33 +000013375 Diag(TypeRange.getBegin(),
13376 getLangOpts().CPlusPlus11 ?
13377 diag::warn_cxx98_compat_unelaborated_friend_type :
13378 diag::ext_unelaborated_friend_type)
13379 << (unsigned) RD->getTagKind()
13380 << T
Craig Topper07fa1762015-11-15 02:31:46 +000013381 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
Nick Lewycky36722d22013-02-06 05:59:33 +000013382 InsertionText);
13383 } else {
13384 Diag(FriendLoc,
13385 getLangOpts().CPlusPlus11 ?
13386 diag::warn_cxx98_compat_nonclass_type_friend :
13387 diag::ext_nonclass_type_friend)
13388 << T
13389 << TypeRange;
13390 }
13391 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000013392 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013393 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000013394 diag::warn_cxx98_compat_enum_friend :
13395 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013396 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000013397 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013398 }
Erich Keanebb863642017-09-20 22:28:24 +000013399
Nick Lewycky36722d22013-02-06 05:59:33 +000013400 // C++11 [class.friend]p3:
13401 // A friend declaration that does not declare a function shall have one
13402 // of the following forms:
13403 // friend elaborated-type-specifier ;
13404 // friend simple-type-specifier ;
13405 // friend typename-specifier ;
13406 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
13407 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
13408 }
Richard Smitha31a89a2012-09-20 01:31:00 +000013409
Douglas Gregor3b4abb62010-04-07 17:57:12 +000013410 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000013411 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000013412 // the friend declaration is ignored.
Nikola Smiljanic3a01af02014-05-23 12:48:27 +000013413 return FriendDecl::Create(Context, CurContext,
13414 TSInfo->getTypeLoc().getLocStart(), TSInfo,
13415 FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013416}
13417
John McCallace48cd2010-10-19 01:40:49 +000013418/// Handle a friend tag declaration where the scope specifier was
13419/// templated.
13420Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
13421 unsigned TagSpec, SourceLocation TagLoc,
13422 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000013423 IdentifierInfo *Name,
13424 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000013425 AttributeList *Attr,
13426 MultiTemplateParamsArg TempParamLists) {
13427 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13428
Richard Smithf445f192017-02-09 21:04:43 +000013429 bool IsMemberSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000013430 bool Invalid = false;
13431
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000013432 if (TemplateParameterList *TemplateParams =
13433 MatchTemplateParametersToScopeSpecifier(
Craig Topperc3ec1492014-05-26 06:22:03 +000013434 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
Richard Smithf445f192017-02-09 21:04:43 +000013435 IsMemberSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000013436 if (TemplateParams->size() > 0) {
13437 // This is a declaration of a class template.
13438 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +000013439 return nullptr;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000013440
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000013441 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
13442 NameLoc, Attr, TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000013443 /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000013444 FriendLoc, TempParamLists.size() - 1,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013445 TempParamLists.data()).get();
John McCallace48cd2010-10-19 01:40:49 +000013446 } else {
13447 // The "template<>" header is extraneous.
13448 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13449 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Richard Smithf445f192017-02-09 21:04:43 +000013450 IsMemberSpecialization = true;
John McCallace48cd2010-10-19 01:40:49 +000013451 }
13452 }
13453
Craig Topperc3ec1492014-05-26 06:22:03 +000013454 if (Invalid) return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000013455
John McCallace48cd2010-10-19 01:40:49 +000013456 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000013457 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000013458 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000013459 isAllExplicitSpecializations = false;
13460 break;
13461 }
13462 }
13463
13464 // FIXME: don't ignore attributes.
13465
13466 // If it's explicit specializations all the way down, just forget
13467 // about the template header and build an appropriate non-templated
13468 // friend. TODO: for source fidelity, remember the headers.
13469 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013470 if (SS.isEmpty()) {
13471 bool Owned = false;
13472 bool IsDependent = false;
13473 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000013474 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013475 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000013476 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000013477 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013478 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000013479 /*UnderlyingType=*/TypeResult(),
Akira Hatanaka12ddcee2017-06-26 18:46:12 +000013480 /*IsTypeSpecifier=*/false,
13481 /*IsTemplateParamOrArg=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013482 }
Richard Smith649c7b062014-01-08 00:56:48 +000013483
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000013484 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000013485 ElaboratedTypeKeyword Keyword
13486 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000013487 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000013488 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000013489 if (T.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +000013490 return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000013491
13492 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13493 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000013494 DependentNameTypeLoc TL =
13495 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000013496 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000013497 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000013498 TL.setNameLoc(NameLoc);
13499 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000013500 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000013501 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000013502 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000013503 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000013504 }
13505
13506 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000013507 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000013508 Friend->setAccess(AS_public);
13509 CurContext->addDecl(Friend);
13510 return Friend;
13511 }
Erich Keanebb863642017-09-20 22:28:24 +000013512
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013513 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
Erich Keanebb863642017-09-20 22:28:24 +000013514
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013515
John McCallace48cd2010-10-19 01:40:49 +000013516
13517 // Handle the case of a templated-scope friend class. e.g.
13518 // template <class T> class A<T>::B;
13519 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000013520 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
13521 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000013522 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13523 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
13524 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000013525 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000013526 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000013527 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000013528 TL.setNameLoc(NameLoc);
13529
13530 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000013531 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000013532 Friend->setAccess(AS_public);
13533 Friend->setUnsupportedFriend(true);
13534 CurContext->addDecl(Friend);
13535 return Friend;
13536}
13537
13538
John McCall11083da2009-09-16 22:47:08 +000013539/// Handle a friend type declaration. This works in tandem with
13540/// ActOnTag.
13541///
13542/// Notes on friend class templates:
13543///
13544/// We generally treat friend class declarations as if they were
13545/// declaring a class. So, for example, the elaborated type specifier
13546/// in a friend declaration is required to obey the restrictions of a
13547/// class-head (i.e. no typedefs in the scope chain), template
13548/// parameters are required to match up with simple template-ids, &c.
13549/// However, unlike when declaring a template specialization, it's
13550/// okay to refer to a template specialization without an empty
13551/// template parameter declaration, e.g.
13552/// friend class A<T>::B<unsigned>;
13553/// We permit this as a special case; if there are any template
13554/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000013555/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000013556Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000013557 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013558 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000013559
13560 assert(DS.isFriendSpecified());
13561 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13562
John McCall11083da2009-09-16 22:47:08 +000013563 // Try to convert the decl specifier to a type. This works for
13564 // friend templates because ActOnTag never produces a ClassTemplateDecl
13565 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000013566 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000013567 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
13568 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000013569 if (TheDeclarator.isInvalidType())
Craig Topperc3ec1492014-05-26 06:22:03 +000013570 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000013571
Douglas Gregor6c110f32010-12-16 01:14:37 +000013572 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000013573 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000013574
John McCall11083da2009-09-16 22:47:08 +000013575 // This is definitely an error in C++98. It's probably meant to
13576 // be forbidden in C++0x, too, but the specification is just
13577 // poorly written.
13578 //
13579 // The problem is with declarations like the following:
13580 // template <T> friend A<T>::foo;
13581 // where deciding whether a class C is a friend or not now hinges
13582 // on whether there exists an instantiation of A that causes
13583 // 'foo' to equal C. There are restrictions on class-heads
13584 // (which we declare (by fiat) elaborated friend declarations to
13585 // be) that makes this tractable.
13586 //
13587 // FIXME: handle "template <> friend class A<T>;", which
13588 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000013589 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000013590 Diag(Loc, diag::err_tagless_friend_type_template)
13591 << DS.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000013592 return nullptr;
John McCall11083da2009-09-16 22:47:08 +000013593 }
Erich Keanebb863642017-09-20 22:28:24 +000013594
John McCallaa74a0c2009-08-28 07:59:38 +000013595 // C++98 [class.friend]p1: A friend of a class is a function
13596 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000013597 // This is fixed in DR77, which just barely didn't make the C++03
13598 // deadline. It's also a very silly restriction that seriously
13599 // affects inner classes and which nobody else seems to implement;
13600 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000013601 //
13602 // But note that we could warn about it: it's always useless to
13603 // friend one of your own members (it's not, however, worthless to
13604 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000013605
John McCall11083da2009-09-16 22:47:08 +000013606 Decl *D;
David Majnemerdfecf1a2016-07-06 04:19:16 +000013607 if (!TempParams.empty())
John McCall11083da2009-09-16 22:47:08 +000013608 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
David Majnemerdfecf1a2016-07-06 04:19:16 +000013609 TempParams,
John McCall15ad0962010-03-25 18:04:51 +000013610 TSI,
John McCall11083da2009-09-16 22:47:08 +000013611 DS.getFriendSpecLoc());
13612 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000013613 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Erich Keanebb863642017-09-20 22:28:24 +000013614
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013615 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +000013616 return nullptr;
13617
John McCall11083da2009-09-16 22:47:08 +000013618 D->setAccess(AS_public);
13619 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000013620
John McCall48871652010-08-21 09:40:31 +000013621 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000013622}
13623
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000013624NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
13625 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000013626 const DeclSpec &DS = D.getDeclSpec();
13627
13628 assert(DS.isFriendSpecified());
13629 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13630
13631 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000013632 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000013633
13634 // C++ [class.friend]p1
13635 // A friend of a class is a function or class....
13636 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000013637 // It *doesn't* see through dependent types, which is correct
13638 // according to [temp.arg.type]p3:
13639 // If a declaration acquires a function type through a
13640 // type dependent on a template-parameter and this causes
13641 // a declaration that does not use the syntactic form of a
13642 // function declarator to have a function type, the program
13643 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013644 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000013645 Diag(Loc, diag::err_unexpected_friend);
13646
13647 // It might be worthwhile to try to recover by creating an
13648 // appropriate declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000013649 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000013650 }
13651
13652 // C++ [namespace.memdef]p3
13653 // - If a friend declaration in a non-local class first declares a
13654 // class or function, the friend class or function is a member
13655 // of the innermost enclosing namespace.
13656 // - The name of the friend is not found by simple name lookup
13657 // until a matching declaration is provided in that namespace
13658 // scope (either before or after the class declaration granting
13659 // friendship).
13660 // - If a friend function is called, its name may be found by the
13661 // name lookup that considers functions from namespaces and
13662 // classes associated with the types of the function arguments.
13663 // - When looking for a prior declaration of a class or a function
13664 // declared as a friend, scopes outside the innermost enclosing
13665 // namespace scope are not considered.
13666
John McCallde3fd222010-10-12 23:13:28 +000013667 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000013668 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
13669 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000013670 assert(Name);
13671
Douglas Gregor6c110f32010-12-16 01:14:37 +000013672 // Check for unexpanded parameter packs.
13673 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
13674 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
13675 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000013676 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000013677
John McCall07e91c02009-08-06 02:15:43 +000013678 // The context we found the declaration in, or in which we should
13679 // create the declaration.
13680 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000013681 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000013682 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +000013683 ForExternalRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000013684
Richard Smith114394f2013-08-09 04:35:01 +000013685 // There are five cases here.
13686 // - There's no scope specifier and we're in a local class. Only look
13687 // for functions declared in the immediately-enclosing block scope.
13688 // We recover from invalid scope qualifiers as if they just weren't there.
Craig Topperc3ec1492014-05-26 06:22:03 +000013689 FunctionDecl *FunctionContainingLocalClass = nullptr;
Richard Smith114394f2013-08-09 04:35:01 +000013690 if ((SS.isInvalid() || !SS.isSet()) &&
13691 (FunctionContainingLocalClass =
13692 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
13693 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000013694 // If a friend declaration appears in a local class and the name
13695 // specified is an unqualified name, a prior declaration is
13696 // looked up without considering scopes that are outside the
13697 // innermost enclosing non-class scope. For a friend function
13698 // declaration, if there is no prior declaration, the program is
13699 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000013700
13701 // Find the innermost enclosing non-class scope. This is the block
13702 // scope containing the local class definition (or for a nested class,
13703 // the outer local class).
13704 DCScope = S->getFnParent();
13705
13706 // Look up the function name in the scope.
13707 Previous.clear(LookupLocalFriendName);
13708 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
13709
13710 if (!Previous.empty()) {
13711 // All possible previous declarations must have the same context:
13712 // either they were declared at block scope or they are members of
13713 // one of the enclosing local classes.
13714 DC = Previous.getRepresentativeDecl()->getDeclContext();
13715 } else {
13716 // This is ill-formed, but provide the context that we would have
13717 // declared the function in, if we were permitted to, for error recovery.
13718 DC = FunctionContainingLocalClass;
13719 }
Richard Smith541b38b2013-09-20 01:15:31 +000013720 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000013721
13722 // C++ [class.friend]p6:
13723 // A function can be defined in a friend declaration of a class if and
13724 // only if the class is a non-local class (9.8), the function name is
13725 // unqualified, and the function has namespace scope.
13726 if (D.isFunctionDefinition()) {
13727 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
13728 }
13729
13730 // - There's no scope specifier, in which case we just go to the
13731 // appropriate scope and look for a function or function template
13732 // there as appropriate.
13733 } else if (SS.isInvalid() || !SS.isSet()) {
13734 // C++11 [namespace.memdef]p3:
13735 // If the name in a friend declaration is neither qualified nor
13736 // a template-id and the declaration is a function or an
13737 // elaborated-type-specifier, the lookup to determine whether
13738 // the entity has been previously declared shall not consider
13739 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000013740 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000013741
John McCallf7cfb222010-10-13 05:45:15 +000013742 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000013743 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000013744
Rafael Espindola3626b7e2013-04-25 20:12:36 +000013745 // Skip class contexts. If someone can cite chapter and verse
13746 // for this behavior, that would be nice --- it's what GCC and
13747 // EDG do, and it seems like a reasonable intent, but the spec
13748 // really only says that checks for unqualified existing
13749 // declarations should stop at the nearest enclosing namespace,
13750 // not that they should only consider the nearest enclosing
13751 // namespace.
13752 while (DC->isRecord())
13753 DC = DC->getParent();
13754
13755 DeclContext *LookupDC = DC;
13756 while (LookupDC->isTransparentContext())
13757 LookupDC = LookupDC->getParent();
13758
13759 while (true) {
13760 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000013761
Rafael Espindola3626b7e2013-04-25 20:12:36 +000013762 if (!Previous.empty()) {
13763 DC = LookupDC;
13764 break;
John McCallf4776592010-10-14 22:22:28 +000013765 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000013766
13767 if (isTemplateId) {
13768 if (isa<TranslationUnitDecl>(LookupDC)) break;
13769 } else {
13770 if (LookupDC->isFileContext()) break;
13771 }
13772 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000013773 }
13774
John McCallccbc0322010-10-13 06:22:15 +000013775 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000013776
John McCallde3fd222010-10-12 23:13:28 +000013777 // - There's a non-dependent scope specifier, in which case we
13778 // compute it and do a previous lookup there for a function
13779 // or function template.
13780 } else if (!SS.getScopeRep()->isDependent()) {
13781 DC = computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +000013782 if (!DC) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000013783
Craig Topperc3ec1492014-05-26 06:22:03 +000013784 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000013785
13786 LookupQualifiedName(Previous, DC);
13787
13788 // Ignore things found implicitly in the wrong scope.
13789 // TODO: better diagnostics for this case. Suggesting the right
13790 // qualified scope would be nice...
13791 LookupResult::Filter F = Previous.makeFilter();
13792 while (F.hasNext()) {
13793 NamedDecl *D = F.next();
13794 if (!DC->InEnclosingNamespaceSetOf(
13795 D->getDeclContext()->getRedeclContext()))
13796 F.erase();
13797 }
13798 F.done();
13799
13800 if (Previous.empty()) {
13801 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013802 Diag(Loc, diag::err_qualified_friend_not_found)
13803 << Name << TInfo->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +000013804 return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000013805 }
13806
13807 // C++ [class.friend]p1: A friend of a class is a function or
13808 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000013809 if (DC->Equals(CurContext))
13810 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013811 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000013812 diag::warn_cxx98_compat_friend_is_member :
13813 diag::err_friend_is_member);
Erich Keanebb863642017-09-20 22:28:24 +000013814
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013815 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000013816 // C++ [class.friend]p6:
Erich Keanebb863642017-09-20 22:28:24 +000013817 // A function can be defined in a friend declaration of a class if and
Douglas Gregor16e65612011-10-10 01:11:59 +000013818 // only if the class is a non-local class (9.8), the function name is
13819 // unqualified, and the function has namespace scope.
13820 SemaDiagnosticBuilder DB
13821 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
Erich Keanebb863642017-09-20 22:28:24 +000013822
Douglas Gregor16e65612011-10-10 01:11:59 +000013823 DB << SS.getScopeRep();
13824 if (DC->isFileContext())
13825 DB << FixItHint::CreateRemoval(SS.getRange());
13826 SS.clear();
13827 }
John McCallde3fd222010-10-12 23:13:28 +000013828
13829 // - There's a scope specifier that does not match any template
13830 // parameter lists, in which case we use some arbitrary context,
13831 // create a method or method template, and wait for instantiation.
13832 // - There's a scope specifier that does match some template
13833 // parameter lists, which we don't handle right now.
13834 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013835 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000013836 // C++ [class.friend]p6:
Erich Keanebb863642017-09-20 22:28:24 +000013837 // A function can be defined in a friend declaration of a class if and
Douglas Gregor16e65612011-10-10 01:11:59 +000013838 // only if the class is a non-local class (9.8), the function name is
13839 // unqualified, and the function has namespace scope.
13840 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
13841 << SS.getScopeRep();
13842 }
Erich Keanebb863642017-09-20 22:28:24 +000013843
John McCallde3fd222010-10-12 23:13:28 +000013844 DC = CurContext;
13845 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000013846 }
David Majnemere14d5302015-09-30 22:07:43 +000013847
John McCallf7cfb222010-10-13 05:45:15 +000013848 if (!DC->isRecord()) {
David Majnemere14d5302015-09-30 22:07:43 +000013849 int DiagArg = -1;
13850 switch (D.getName().getKind()) {
13851 case UnqualifiedId::IK_ConstructorTemplateId:
13852 case UnqualifiedId::IK_ConstructorName:
13853 DiagArg = 0;
13854 break;
13855 case UnqualifiedId::IK_DestructorName:
13856 DiagArg = 1;
13857 break;
13858 case UnqualifiedId::IK_ConversionFunctionId:
13859 DiagArg = 2;
13860 break;
Richard Smith35845152017-02-07 01:37:30 +000013861 case UnqualifiedId::IK_DeductionGuideName:
13862 DiagArg = 3;
13863 break;
David Majnemere14d5302015-09-30 22:07:43 +000013864 case UnqualifiedId::IK_Identifier:
13865 case UnqualifiedId::IK_ImplicitSelfParam:
13866 case UnqualifiedId::IK_LiteralOperatorId:
13867 case UnqualifiedId::IK_OperatorFunctionId:
13868 case UnqualifiedId::IK_TemplateId:
13869 break;
David Majnemere14d5302015-09-30 22:07:43 +000013870 }
John McCall07e91c02009-08-06 02:15:43 +000013871 // This implies that it has to be an operator or function.
David Majnemere14d5302015-09-30 22:07:43 +000013872 if (DiagArg >= 0) {
13873 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
Craig Topperc3ec1492014-05-26 06:22:03 +000013874 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000013875 }
John McCall07e91c02009-08-06 02:15:43 +000013876 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013877
Douglas Gregordd847ba2011-11-03 16:37:14 +000013878 // FIXME: This is an egregious hack to cope with cases where the scope stack
Erich Keanebb863642017-09-20 22:28:24 +000013879 // does not contain the declaration context, i.e., in an out-of-line
Douglas Gregordd847ba2011-11-03 16:37:14 +000013880 // definition of a class.
13881 Scope FakeDCScope(S, Scope::DeclScope, Diags);
13882 if (!DCScope) {
13883 FakeDCScope.setEntity(DC);
13884 DCScope = &FakeDCScope;
13885 }
Richard Smith114394f2013-08-09 04:35:01 +000013886
Francois Pichet00c7e6c2011-08-14 03:52:19 +000013887 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013888 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000013889 TemplateParams, AddToScope);
Craig Topperc3ec1492014-05-26 06:22:03 +000013890 if (!ND) return nullptr;
John McCall759e32b2009-08-31 22:39:49 +000013891
Douglas Gregora29a3ff2009-09-28 00:08:27 +000013892 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000013893
Richard Smith114394f2013-08-09 04:35:01 +000013894 // If we performed typo correction, we might have added a scope specifier
13895 // and changed the decl context.
13896 DC = ND->getDeclContext();
13897
John McCall759e32b2009-08-31 22:39:49 +000013898 // Add the function declaration to the appropriate lookup tables,
13899 // adjusting the redeclarations list as necessary. We don't
13900 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000013901 //
John McCall759e32b2009-08-31 22:39:49 +000013902 // Also update the scope-based lookup if the target context's
13903 // lookup context is in lexical scope.
13904 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000013905 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000013906 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000013907 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000013908 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000013909 }
John McCallaa74a0c2009-08-28 07:59:38 +000013910
13911 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000013912 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000013913 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000013914 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000013915 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000013916
John McCalla0a96892012-08-10 03:15:35 +000013917 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000013918 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000013919 } else {
13920 if (DC->isRecord()) CheckFriendAccess(ND);
13921
John McCall2c2eb122010-10-16 06:59:13 +000013922 FunctionDecl *FD;
13923 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
13924 FD = FTD->getTemplatedDecl();
13925 else
13926 FD = cast<FunctionDecl>(ND);
13927
David Majnemer502b0ed2013-06-25 23:09:30 +000013928 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
13929 // default argument expression, that declaration shall be a definition
13930 // and shall be the only declaration of the function or function
13931 // template in the translation unit.
13932 if (functionDeclHasDefaultArgument(FD)) {
Serge Pavlov06b7a872016-10-04 10:11:43 +000013933 // We can't look at FD->getPreviousDecl() because it may not have been set
Richard Smithfdf08882016-10-21 03:15:03 +000013934 // if we're in a dependent context. If the function is known to be a
13935 // redeclaration, we will have narrowed Previous down to the right decl.
13936 if (D.isRedeclaration()) {
David Majnemer502b0ed2013-06-25 23:09:30 +000013937 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
Serge Pavlov06b7a872016-10-04 10:11:43 +000013938 Diag(Previous.getRepresentativeDecl()->getLocation(),
13939 diag::note_previous_declaration);
David Majnemer502b0ed2013-06-25 23:09:30 +000013940 } else if (!D.isFunctionDefinition())
13941 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
13942 }
13943
John McCall2c2eb122010-10-16 06:59:13 +000013944 // Mark templated-scope function declarations as unsupported.
Richard Smith04b35e92014-09-29 05:57:29 +000013945 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
13946 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
13947 << SS.getScopeRep() << SS.getRange()
13948 << cast<CXXRecordDecl>(CurContext);
John McCall2c2eb122010-10-16 06:59:13 +000013949 FrD->setUnsupportedFriend(true);
Richard Smith04b35e92014-09-29 05:57:29 +000013950 }
John McCall2c2eb122010-10-16 06:59:13 +000013951 }
John McCallde3fd222010-10-12 23:13:28 +000013952
John McCall48871652010-08-21 09:40:31 +000013953 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000013954}
13955
John McCall48871652010-08-21 09:40:31 +000013956void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
13957 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000013958
Aaron Ballmanf96361e2013-01-16 23:39:10 +000013959 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000013960 if (!Fn) {
13961 Diag(DelLoc, diag::err_deleted_non_function);
13962 return;
13963 }
Richard Smithb4d2a152013-04-02 19:38:47 +000013964
Serge Pavlov25dbe1a2017-06-21 12:46:57 +000013965 // Deleted function does not have a body.
13966 Fn->setWillHaveBody(false);
13967
Douglas Gregorec9fd132012-01-14 16:38:05 +000013968 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000013969 // Don't consider the implicit declaration we generate for explicit
13970 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000013971 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
13972 Prev->getPreviousDecl()) &&
13973 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000013974 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000013975 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
13976 Prev->isImplicit() ? diag::note_previous_implicit_declaration
13977 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000013978 }
Sebastian Redlf769df52009-03-24 22:27:57 +000013979 // If the declaration wasn't the first, we delete the function anyway for
13980 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000013981 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000013982 }
Richard Smithb4d2a152013-04-02 19:38:47 +000013983
Nico Rieck9de0a572014-05-29 16:51:19 +000013984 // dllimport/dllexport cannot be deleted.
13985 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
13986 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
13987 Fn->setInvalidDecl();
13988 }
13989
Richard Smithb4d2a152013-04-02 19:38:47 +000013990 if (Fn->isDeleted())
13991 return;
13992
13993 // See if we're deleting a function which is already known to override a
13994 // non-deleted virtual function.
Richard Smithf3cec652016-10-31 18:18:29 +000013995 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
Richard Smithb4d2a152013-04-02 19:38:47 +000013996 bool IssuedDiagnostic = false;
13997 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
13998 E = MD->end_overridden_methods();
13999 I != E; ++I) {
14000 if (!(*MD->begin_overridden_methods())->isDeleted()) {
14001 if (!IssuedDiagnostic) {
14002 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14003 IssuedDiagnostic = true;
14004 }
14005 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
14006 }
14007 }
Richard Smithf3cec652016-10-31 18:18:29 +000014008 // If this function was implicitly deleted because it was defaulted,
14009 // explain why it was deleted.
14010 if (IssuedDiagnostic && MD->isDefaulted())
14011 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14012 /*Diagnose*/true);
Richard Smithb4d2a152013-04-02 19:38:47 +000014013 }
14014
Richard Smithb63b6ee2014-01-22 01:43:19 +000014015 // C++11 [basic.start.main]p3:
14016 // A program that defines main as deleted [...] is ill-formed.
14017 if (Fn->isMain())
14018 Diag(DelLoc, diag::err_deleted_main);
14019
Eric Fiselier525a3512016-10-31 23:07:15 +000014020 // C++11 [dcl.fct.def.delete]p4:
14021 // A deleted function is implicitly inline.
14022 Fn->setImplicitlyInline();
Alexis Hunt4a8ea102011-05-06 20:44:56 +000014023 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000014024}
Sebastian Redl4c018662009-04-27 21:33:24 +000014025
Alexis Hunt5a7fa252011-05-12 06:15:49 +000014026void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000014027 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000014028
14029 if (MD) {
Richard Trieu3d1235a2016-09-27 23:44:07 +000014030 if (MD->getParent()->isDependentType()) {
14031 MD->setDefaulted();
14032 MD->setExplicitlyDefaulted();
14033 return;
14034 }
14035
Alexis Hunt5a7fa252011-05-12 06:15:49 +000014036 CXXSpecialMember Member = getSpecialMember(MD);
14037 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000014038 if (!MD->isInvalidDecl())
14039 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000014040 return;
14041 }
14042
14043 MD->setDefaulted();
14044 MD->setExplicitlyDefaulted();
14045
Richard Smith883dbc42017-05-25 22:47:05 +000014046 // Unset that we will have a body for this function. We might not,
14047 // if it turns out to be trivial, and we don't need this marking now
14048 // that we've marked it as defaulted.
14049 MD->setWillHaveBody(false);
14050
Alexis Hunt61ae8d32011-05-23 23:14:04 +000014051 // If this definition appears within the record, do the checking when
14052 // the record is complete.
14053 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000014054 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Vassil Vassilev8ffe3be2016-05-24 12:10:36 +000014055 // Ask the template instantiation pattern that actually had the
14056 // '= default' on it.
14057 Primary = Pattern;
Alexis Hunt61ae8d32011-05-23 23:14:04 +000014058
Richard Smith3901dfe2013-03-27 00:22:47 +000014059 // If the method was defaulted on its first declaration, we will have
14060 // already performed the checking in CheckCompletedCXXClass. Such a
14061 // declaration doesn't trigger an implicit definition.
Vassil Vassilev8ffe3be2016-05-24 12:10:36 +000014062 if (Primary->getCanonicalDecl()->isDefaulted())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000014063 return;
14064
Richard Smithd3b5c9082012-07-27 04:22:15 +000014065 CheckExplicitlyDefaultedSpecialMember(MD);
14066
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +000014067 if (!MD->isInvalidDecl())
14068 DefineImplicitSpecialMember(*this, MD, DefaultLoc);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000014069 } else {
14070 Diag(DefaultLoc, diag::err_default_special_members);
14071 }
14072}
14073
Sebastian Redl4c018662009-04-27 21:33:24 +000014074static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
Benjamin Kramer642f1732015-07-02 21:03:14 +000014075 for (Stmt *SubStmt : S->children()) {
Sebastian Redl4c018662009-04-27 21:33:24 +000014076 if (!SubStmt)
14077 continue;
14078 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000014079 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000014080 diag::err_return_in_constructor_handler);
14081 if (!isa<Expr>(SubStmt))
14082 SearchForReturnInStmt(Self, SubStmt);
14083 }
14084}
14085
14086void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14087 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14088 CXXCatchStmt *Handler = TryBlock->getHandler(I);
14089 SearchForReturnInStmt(*this, Handler);
14090 }
14091}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000014092
David Blaikie68f71a32013-01-18 23:03:15 +000014093bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000014094 const CXXMethodDecl *Old) {
Akira Hatanaka98a49332017-09-22 00:41:05 +000014095 const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
14096 const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
14097
14098 if (OldFT->hasExtParameterInfos()) {
14099 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
14100 // A parameter of the overriding method should be annotated with noescape
14101 // if the corresponding parameter of the overridden method is annotated.
14102 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
14103 !NewFT->getExtParameterInfo(I).isNoEscape()) {
14104 Diag(New->getParamDecl(I)->getLocation(),
14105 diag::warn_overriding_method_missing_noescape);
14106 Diag(Old->getParamDecl(I)->getLocation(),
14107 diag::note_overridden_marked_noescape);
14108 }
14109 }
Aaron Ballman02df2e02012-12-09 17:45:41 +000014110
14111 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14112
14113 // If the calling conventions match, everything is fine
14114 if (NewCC == OldCC)
14115 return false;
14116
Hans Wennborg2545efe2013-12-11 17:42:11 +000014117 // If the calling conventions mismatch because the new function is static,
14118 // suppress the calling convention mismatch error; the error about static
14119 // function override (err_static_overrides_virtual from
14120 // Sema::CheckFunctionDeclaration) is more clear.
14121 if (New->getStorageClass() == SC_Static)
14122 return false;
14123
Reid Kleckner78af0702013-08-27 23:08:25 +000014124 Diag(New->getLocation(),
14125 diag::err_conflicting_overriding_cc_attributes)
14126 << New->getDeclName() << New->getType() << Old->getType();
14127 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14128 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000014129}
14130
Mike Stump11289f42009-09-09 15:08:12 +000014131bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000014132 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000014133 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14134 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000014135
Chandler Carruth284bb2e2010-02-15 11:53:20 +000014136 if (Context.hasSameType(NewTy, OldTy) ||
14137 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000014138 return false;
Mike Stump11289f42009-09-09 15:08:12 +000014139
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014140 // Check if the return types are covariant
14141 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000014142
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014143 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000014144 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14145 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014146 NewClassTy = NewPT->getPointeeType();
14147 OldClassTy = OldPT->getPointeeType();
14148 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000014149 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14150 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14151 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14152 NewClassTy = NewRT->getPointeeType();
14153 OldClassTy = OldRT->getPointeeType();
14154 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014155 }
14156 }
Mike Stump11289f42009-09-09 15:08:12 +000014157
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014158 // The return types aren't either both pointers or references to a class type.
14159 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000014160 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014161 diag::err_different_return_type_for_overriding_virtual_function)
Alp Tokerd0787eb2014-07-02 01:47:15 +000014162 << New->getDeclName() << NewTy << OldTy
14163 << New->getReturnTypeSourceRange();
14164 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14165 << Old->getReturnTypeSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000014166
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014167 return true;
14168 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000014169
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000014170 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
David Majnemerd3d91bd2016-01-26 01:37:01 +000014171 // C++14 [class.virtual]p8:
14172 // If the class type in the covariant return type of D::f differs from
14173 // that of B::f, the class type in the return type of D::f shall be
14174 // complete at the point of declaration of D::f or shall be the class
14175 // type D.
14176 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14177 if (!RT->isBeingDefined() &&
14178 RequireCompleteType(New->getLocation(), NewClassTy,
14179 diag::err_covariant_return_incomplete,
14180 New->getDeclName()))
14181 return true;
14182 }
14183
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014184 // Check if the new class derives from the old class.
Richard Smith0f59cb32015-12-18 21:45:41 +000014185 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
Alp Tokerd0787eb2014-07-02 01:47:15 +000014186 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14187 << New->getDeclName() << NewTy << OldTy
14188 << New->getReturnTypeSourceRange();
14189 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14190 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014191 return true;
14192 }
Mike Stump11289f42009-09-09 15:08:12 +000014193
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014194 // Check if we the conversion from derived to base is valid.
Alp Tokerd0787eb2014-07-02 01:47:15 +000014195 if (CheckDerivedToBaseConversion(
14196 NewClassTy, OldClassTy,
14197 diag::err_covariant_return_inaccessible_base,
14198 diag::err_covariant_return_ambiguous_derived_to_base_conv,
14199 New->getLocation(), New->getReturnTypeSourceRange(),
14200 New->getDeclName(), nullptr)) {
John McCallc1465822011-02-14 07:13:47 +000014201 // FIXME: this note won't trigger for delayed access control
14202 // diagnostics, and it's impossible to get an undelayed error
14203 // here from access control during the original parse because
14204 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Alp Tokerd0787eb2014-07-02 01:47:15 +000014205 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14206 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014207 return true;
14208 }
14209 }
Mike Stump11289f42009-09-09 15:08:12 +000014210
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014211 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000014212 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014213 Diag(New->getLocation(),
14214 diag::err_covariant_return_type_different_qualifications)
Alp Tokerd0787eb2014-07-02 01:47:15 +000014215 << New->getDeclName() << NewTy << OldTy
14216 << New->getReturnTypeSourceRange();
14217 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14218 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014219 return true;
David Majnemerfedb8d42016-01-26 01:39:17 +000014220 }
Mike Stump11289f42009-09-09 15:08:12 +000014221
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014222
14223 // The new class type must have the same or less qualifiers as the old type.
14224 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14225 Diag(New->getLocation(),
14226 diag::err_covariant_return_type_class_type_more_qualified)
Alp Tokerd0787eb2014-07-02 01:47:15 +000014227 << New->getDeclName() << NewTy << OldTy
14228 << New->getReturnTypeSourceRange();
14229 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14230 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014231 return true;
David Majnemerfedb8d42016-01-26 01:39:17 +000014232 }
Mike Stump11289f42009-09-09 15:08:12 +000014233
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014234 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000014235}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014236
Douglas Gregor21920e372009-12-01 17:24:26 +000014237/// \brief Mark the given method pure.
14238///
14239/// \param Method the method to be marked pure.
14240///
14241/// \param InitRange the source range that covers the "0" initializer.
14242bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000014243 SourceLocation EndLoc = InitRange.getEnd();
14244 if (EndLoc.isValid())
14245 Method->setRangeEnd(EndLoc);
14246
Douglas Gregor21920e372009-12-01 17:24:26 +000014247 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14248 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000014249 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000014250 }
Douglas Gregor21920e372009-12-01 17:24:26 +000014251
14252 if (!Method->isInvalidDecl())
14253 Diag(Method->getLocation(), diag::err_non_virtual_pure)
14254 << Method->getDeclName() << InitRange;
14255 return true;
14256}
14257
Richard Smith9ba0fec2015-06-30 01:28:56 +000014258void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14259 if (D->getFriendObjectKind())
14260 Diag(D->getLocation(), diag::err_pure_friend);
14261 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14262 CheckPureMethod(M, ZeroLoc);
14263 else
14264 Diag(D->getLocation(), diag::err_illegal_initializer);
14265}
14266
Richard Smithc95d2c52017-09-22 04:25:05 +000014267/// \brief Determine whether the given declaration is a global variable or
14268/// static data member.
14269static bool isNonlocalVariable(const Decl *D) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014270 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
Richard Smithc95d2c52017-09-22 04:25:05 +000014271 return Var->hasGlobalStorage();
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014272
14273 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000014274}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014275
Richard Smithc95d2c52017-09-22 04:25:05 +000014276/// Invoked when we are about to parse an initializer for the declaration
14277/// 'Dcl'.
John McCall1f4ee7b2009-12-19 09:28:58 +000014278///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014279/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14280/// static data member of class X, names should be looked up in the scope of
Richard Smithc95d2c52017-09-22 04:25:05 +000014281/// class X. If the declaration had a scope specifier, a scope will have
14282/// been created and passed in for this purpose. Otherwise, S will be null.
John McCall48871652010-08-21 09:40:31 +000014283void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014284 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000014285 if (!D || D->isInvalidDecl())
14286 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014287
Richard Smitha2302242013-12-05 07:51:02 +000014288 // We will always have a nested name specifier here, but this declaration
14289 // might not be out of line if the specifier names the current namespace:
14290 // extern int n;
14291 // int ::n = 0;
Richard Smithc95d2c52017-09-22 04:25:05 +000014292 if (S && D->isOutOfLine())
Richard Smitha2302242013-12-05 07:51:02 +000014293 EnterDeclaratorContext(S, D->getDeclContext());
14294
Douglas Gregor926410d2012-02-21 02:22:07 +000014295 // If we are parsing the initializer for a static data member, push a
14296 // new expression evaluation context that is associated with this static
14297 // data member.
Richard Smithc95d2c52017-09-22 04:25:05 +000014298 if (isNonlocalVariable(D))
Faisal Valid143a0c2017-04-01 21:30:49 +000014299 PushExpressionEvaluationContext(
14300 ExpressionEvaluationContext::PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014301}
14302
Richard Smithc95d2c52017-09-22 04:25:05 +000014303/// Invoked after we are finished parsing an initializer for the declaration D.
John McCall48871652010-08-21 09:40:31 +000014304void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014305 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000014306 if (!D || D->isInvalidDecl())
14307 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014308
Richard Smithc95d2c52017-09-22 04:25:05 +000014309 if (isNonlocalVariable(D))
Richard Smitha2302242013-12-05 07:51:02 +000014310 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000014311
Richard Smithc95d2c52017-09-22 04:25:05 +000014312 if (S && D->isOutOfLine())
Richard Smitha2302242013-12-05 07:51:02 +000014313 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014314}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014315
14316/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14317/// C++ if/switch/while/for statement.
14318/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000014319DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014320 // C++ 6.4p2:
14321 // The declarator shall not specify a function or an array.
14322 // The type-specifier-seq shall not contain typedef and shall not declare a
14323 // new class or enumeration.
14324 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14325 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000014326
14327 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000014328 if (!Dcl)
14329 return true;
14330
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000014331 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14332 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014333 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000014334 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014335 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014336
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014337 return Dcl;
14338}
Anders Carlssonf98849e2009-12-02 17:15:43 +000014339
Douglas Gregor4daf6a32011-07-28 19:11:31 +000014340void Sema::LoadExternalVTableUses() {
14341 if (!ExternalSource)
14342 return;
Erich Keanebb863642017-09-20 22:28:24 +000014343
Douglas Gregor4daf6a32011-07-28 19:11:31 +000014344 SmallVector<ExternalVTableUse, 4> VTables;
14345 ExternalSource->ReadUsedVTables(VTables);
14346 SmallVector<VTableUse, 4> NewUses;
14347 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14348 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14349 = VTablesUsed.find(VTables[I].Record);
14350 // Even if a definition wasn't required before, it may be required now.
14351 if (Pos != VTablesUsed.end()) {
14352 if (!Pos->second && VTables[I].DefinitionRequired)
14353 Pos->second = true;
14354 continue;
14355 }
Erich Keanebb863642017-09-20 22:28:24 +000014356
Douglas Gregor4daf6a32011-07-28 19:11:31 +000014357 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14358 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14359 }
Erich Keanebb863642017-09-20 22:28:24 +000014360
Douglas Gregor4daf6a32011-07-28 19:11:31 +000014361 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14362}
14363
Douglas Gregor88d292c2010-05-13 16:44:06 +000014364void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
14365 bool DefinitionRequired) {
14366 // Ignore any vtable uses in unevaluated operands or for classes that do
14367 // not have a vtable.
14368 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000014369 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000014370 return;
14371
Douglas Gregor88d292c2010-05-13 16:44:06 +000014372 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000014373 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014374 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
14375 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
14376 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
14377 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000014378 // If we already had an entry, check to see if we are promoting this vtable
Nico Weberf1cebf02015-01-06 23:54:59 +000014379 // to require a definition. If so, we need to reappend to the VTableUses
Daniel Dunbar53217762010-05-25 00:33:13 +000014380 // list, since we may have already processed the first entry.
14381 if (DefinitionRequired && !Pos.first->second) {
14382 Pos.first->second = true;
14383 } else {
14384 // Otherwise, we can early exit.
14385 return;
14386 }
Hans Wennborg3d791542014-02-24 15:58:24 +000014387 } else {
14388 // The Microsoft ABI requires that we perform the destructor body
14389 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
14390 // the deleting destructor is emitted with the vtable, not with the
14391 // destructor definition as in the Itanium ABI.
Hans Wennborg34804352016-04-13 20:21:15 +000014392 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Reid Klecknerad1e22b2016-06-29 18:29:21 +000014393 CXXDestructorDecl *DD = Class->getDestructor();
14394 if (DD && DD->isVirtual() && !DD->isDeleted()) {
14395 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
14396 // If this is an out-of-line declaration, marking it referenced will
14397 // not do anything. Manually call CheckDestructor to look up operator
14398 // delete().
14399 ContextRAII SavedContext(*this, DD);
14400 CheckDestructor(DD);
14401 } else {
14402 MarkFunctionReferenced(Loc, Class->getDestructor());
14403 }
Hans Wennborg34804352016-04-13 20:21:15 +000014404 }
Hans Wennborg3d791542014-02-24 15:58:24 +000014405 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000014406 }
14407
14408 // Local classes need to have their virtual members marked
14409 // immediately. For all other classes, we mark their virtual members
14410 // at the end of the translation unit.
14411 if (Class->isLocalClass())
14412 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000014413 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000014414 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000014415}
14416
Douglas Gregor88d292c2010-05-13 16:44:06 +000014417bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000014418 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014419 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000014420 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000014421
Douglas Gregor88d292c2010-05-13 16:44:06 +000014422 // Note: The VTableUses vector could grow as a result of marking
14423 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000014424 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000014425 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000014426 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014427 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000014428 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014429 if (!Class)
14430 continue;
Reid Klecknerb792e062016-12-06 21:44:41 +000014431 TemplateSpecializationKind ClassTSK =
14432 Class->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014433
14434 SourceLocation Loc = VTableUses[I].second;
14435
Richard Smithd3b5c9082012-07-27 04:22:15 +000014436 bool DefineVTable = true;
14437
Douglas Gregor88d292c2010-05-13 16:44:06 +000014438 // If this class has a key function, but that key function is
14439 // defined in another translation unit, we don't need to emit the
14440 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000014441 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000014442 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000014443 // The key function is in another translation unit.
14444 DefineVTable = false;
14445 TemplateSpecializationKind TSK =
14446 KeyFunction->getTemplateSpecializationKind();
14447 assert(TSK != TSK_ExplicitInstantiationDefinition &&
14448 TSK != TSK_ImplicitInstantiation &&
14449 "Instantiations don't have key functions");
14450 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014451 } else if (!KeyFunction) {
14452 // If we have a class with no key function that is the subject
14453 // of an explicit instantiation declaration, suppress the
14454 // vtable; it will live with the explicit instantiation
14455 // definition.
Reid Klecknerb792e062016-12-06 21:44:41 +000014456 bool IsExplicitInstantiationDeclaration =
14457 ClassTSK == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000014458 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000014459 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000014460 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014461 if (TSK == TSK_ExplicitInstantiationDeclaration)
14462 IsExplicitInstantiationDeclaration = true;
14463 else if (TSK == TSK_ExplicitInstantiationDefinition) {
14464 IsExplicitInstantiationDeclaration = false;
14465 break;
14466 }
14467 }
14468
14469 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000014470 DefineVTable = false;
14471 }
14472
14473 // The exception specifications for all virtual members may be needed even
14474 // if we are not providing an authoritative form of the vtable in this TU.
14475 // We may choose to emit it available_externally anyway.
14476 if (!DefineVTable) {
14477 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
14478 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014479 }
14480
14481 // Mark all of the virtual members of this class as referenced, so
14482 // that we can build a vtable. Then, tell the AST consumer that a
14483 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000014484 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014485 MarkVirtualMembersReferenced(Loc, Class);
14486 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
Nico Weberb6a5d052015-01-15 04:07:35 +000014487 if (VTablesUsed[Canonical])
14488 Consumer.HandleVTable(Class);
Douglas Gregor88d292c2010-05-13 16:44:06 +000014489
Reid Klecknerb792e062016-12-06 21:44:41 +000014490 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
14491 // no key function or the key function is inlined. Don't warn in C++ ABIs
14492 // that lack key functions, since the user won't be able to make one.
14493 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
14494 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +000014495 const FunctionDecl *KeyFunctionDef = nullptr;
Reid Klecknerb792e062016-12-06 21:44:41 +000014496 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
14497 KeyFunctionDef->isInlined())) {
14498 Diag(Class->getLocation(),
14499 ClassTSK == TSK_ExplicitInstantiationDefinition
14500 ? diag::warn_weak_template_vtable
14501 : diag::warn_weak_vtable)
14502 << Class;
14503 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000014504 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000014505 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000014506 VTableUses.clear();
14507
Douglas Gregor97509692011-04-22 22:25:37 +000014508 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000014509}
Anders Carlsson82fccd02009-12-07 08:24:59 +000014510
Richard Smithd3b5c9082012-07-27 04:22:15 +000014511void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
14512 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000014513 for (const auto *I : RD->methods())
14514 if (I->isVirtual() && !I->isPure())
14515 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000014516}
14517
Rafael Espindola5b334082010-03-26 00:36:59 +000014518void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
14519 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000014520 // Mark all functions which will appear in RD's vtable as used.
14521 CXXFinalOverriderMap FinalOverriders;
14522 RD->getFinalOverriders(FinalOverriders);
14523 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
14524 E = FinalOverriders.end();
14525 I != E; ++I) {
14526 for (OverridingMethods::const_iterator OI = I->second.begin(),
14527 OE = I->second.end();
14528 OI != OE; ++OI) {
14529 assert(OI->second.size() > 0 && "no final overrider");
14530 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000014531
Richard Smith4ff9ff92012-07-07 06:59:51 +000014532 // C++ [basic.def.odr]p2:
14533 // [...] A virtual member function is used if it is not pure. [...]
14534 if (!Overrider->isPure())
14535 MarkFunctionReferenced(Loc, Overrider);
14536 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000014537 }
Rafael Espindola5b334082010-03-26 00:36:59 +000014538
14539 // Only classes that have virtual bases need a VTT.
14540 if (RD->getNumVBases() == 0)
14541 return;
14542
Aaron Ballman574705e2014-03-13 15:41:46 +000014543 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000014544 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000014545 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000014546 if (Base->getNumVBases() == 0)
14547 continue;
14548 MarkVirtualMembersReferenced(Loc, Base);
14549 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000014550}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014551
14552/// SetIvarInitializers - This routine builds initialization ASTs for the
14553/// Objective-C implementation whose ivars need be initialized.
14554void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000014555 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014556 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000014557 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000014558 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014559 CollectIvarsToConstructOrDestruct(OID, ivars);
14560 if (ivars.empty())
14561 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000014562 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014563 for (unsigned i = 0; i < ivars.size(); i++) {
14564 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000014565 if (Field->isInvalidDecl())
14566 continue;
Erich Keanebb863642017-09-20 22:28:24 +000014567
Alexis Hunt1d792652011-01-08 20:30:50 +000014568 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014569 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Erich Keanebb863642017-09-20 22:28:24 +000014570 InitializationKind InitKind =
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014571 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000014572
14573 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
14574 ExprResult MemberInit =
14575 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000014576 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Erich Keanebb863642017-09-20 22:28:24 +000014577 // Note, MemberInit could actually come back empty if no initialization
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014578 // is required (e.g., because it would call a trivial default constructor)
14579 if (!MemberInit.get() || MemberInit.isInvalid())
14580 continue;
John McCallacf0ee52010-10-08 02:01:28 +000014581
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014582 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000014583 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
14584 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014585 MemberInit.getAs<Expr>(),
Alexis Hunt1d792652011-01-08 20:30:50 +000014586 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014587 AllToInit.push_back(Member);
Erich Keanebb863642017-09-20 22:28:24 +000014588
Douglas Gregor527786e2010-05-20 02:24:22 +000014589 // Be sure that the destructor is accessible and is marked as referenced.
Nico Weberaa0117c2014-11-12 03:44:43 +000014590 if (const RecordType *RecordTy =
14591 Context.getBaseElementType(Field->getType())
14592 ->getAs<RecordType>()) {
14593 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000014594 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000014595 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000014596 CheckDestructorAccess(Field->getLocation(), Destructor,
14597 PDiag(diag::err_access_dtor_ivar)
14598 << Context.getBaseElementType(Field->getType()));
14599 }
Erich Keanebb863642017-09-20 22:28:24 +000014600 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014601 }
Erich Keanebb863642017-09-20 22:28:24 +000014602 ObjCImplementation->setIvarInitializers(Context,
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014603 AllToInit.data(), AllToInit.size());
14604 }
14605}
Alexis Hunt6118d662011-05-04 05:57:24 +000014606
Alexis Hunt27a761d2011-05-04 23:29:54 +000014607static
14608void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
14609 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
14610 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
14611 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
14612 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000014613 if (Ctor->isInvalidDecl())
14614 return;
14615
Richard Smith802c4b72012-08-23 06:16:52 +000014616 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
14617
14618 // Target may not be determinable yet, for instance if this is a dependent
14619 // call in an uninstantiated template.
14620 if (Target) {
Craig Topperc3ec1492014-05-26 06:22:03 +000014621 const FunctionDecl *FNTarget = nullptr;
Richard Smith802c4b72012-08-23 06:16:52 +000014622 (void)Target->hasBody(FNTarget);
14623 Target = const_cast<CXXConstructorDecl*>(
14624 cast_or_null<CXXConstructorDecl>(FNTarget));
14625 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000014626
14627 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
14628 // Avoid dereferencing a null pointer here.
Craig Topperc3ec1492014-05-26 06:22:03 +000014629 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000014630
David Blaikie82e95a32014-11-19 07:49:47 +000014631 if (!Current.insert(Canonical).second)
Alexis Hunt27a761d2011-05-04 23:29:54 +000014632 return;
14633
14634 // We know that beyond here, we aren't chaining into a cycle.
14635 if (!Target || !Target->isDelegatingConstructor() ||
14636 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014637 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000014638 Current.clear();
14639 // We've hit a cycle.
14640 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
14641 Current.count(TCanonical)) {
14642 // If we haven't diagnosed this cycle yet, do so now.
14643 if (!Invalid.count(TCanonical)) {
14644 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000014645 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000014646 << Ctor;
14647
Richard Smith802c4b72012-08-23 06:16:52 +000014648 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000014649 if (TCanonical != Canonical)
14650 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
14651
14652 CXXConstructorDecl *C = Target;
14653 while (C->getCanonicalDecl() != Canonical) {
Craig Topperc3ec1492014-05-26 06:22:03 +000014654 const FunctionDecl *FNTarget = nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000014655 (void)C->getTargetConstructor()->hasBody(FNTarget);
14656 assert(FNTarget && "Ctor cycle through bodiless function");
14657
Richard Smith802c4b72012-08-23 06:16:52 +000014658 C = const_cast<CXXConstructorDecl*>(
14659 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000014660 S.Diag(C->getLocation(), diag::note_which_delegates_to);
14661 }
14662 }
14663
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014664 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000014665 Current.clear();
14666 } else {
14667 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
14668 }
14669}
Erich Keanebb863642017-09-20 22:28:24 +000014670
Alexis Hunt27a761d2011-05-04 23:29:54 +000014671
Alexis Hunt6118d662011-05-04 05:57:24 +000014672void Sema::CheckDelegatingCtorCycles() {
14673 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
14674
Douglas Gregorbae31202011-07-27 21:57:17 +000014675 for (DelegatingCtorDeclsType::iterator
14676 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000014677 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000014678 I != E; ++I)
14679 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000014680
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014681 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
14682 CE = Invalid.end();
14683 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000014684 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000014685}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000014686
Douglas Gregor3024f072012-04-16 07:05:22 +000014687namespace {
14688 /// \brief AST visitor that finds references to the 'this' expression.
14689 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
14690 Sema &S;
Erich Keanebb863642017-09-20 22:28:24 +000014691
Douglas Gregor3024f072012-04-16 07:05:22 +000014692 public:
14693 explicit FindCXXThisExpr(Sema &S) : S(S) { }
Erich Keanebb863642017-09-20 22:28:24 +000014694
Douglas Gregor3024f072012-04-16 07:05:22 +000014695 bool VisitCXXThisExpr(CXXThisExpr *E) {
14696 S.Diag(E->getLocation(), diag::err_this_static_member_func)
14697 << E->isImplicit();
14698 return false;
14699 }
14700 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000014701}
Douglas Gregor3024f072012-04-16 07:05:22 +000014702
14703bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
14704 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14705 if (!TSInfo)
14706 return false;
Erich Keanebb863642017-09-20 22:28:24 +000014707
Douglas Gregor3024f072012-04-16 07:05:22 +000014708 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000014709 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000014710 if (!ProtoTL)
14711 return false;
Erich Keanebb863642017-09-20 22:28:24 +000014712
Douglas Gregor3024f072012-04-16 07:05:22 +000014713 // C++11 [expr.prim.general]p3:
Erich Keanebb863642017-09-20 22:28:24 +000014714 // [The expression this] shall not appear before the optional
14715 // cv-qualifier-seq and it shall not appear within the declaration of a
Douglas Gregor3024f072012-04-16 07:05:22 +000014716 // static member function (although its type and value category are defined
14717 // within a static member function as they are within a non-static member
14718 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000014719 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000014720 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000014721 FindCXXThisExpr Finder(*this);
Erich Keanebb863642017-09-20 22:28:24 +000014722
Douglas Gregor3024f072012-04-16 07:05:22 +000014723 // If the return type came after the cv-qualifier-seq, check it now.
14724 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000014725 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000014726 return true;
14727
14728 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000014729 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
14730 return true;
Erich Keanebb863642017-09-20 22:28:24 +000014731
Douglas Gregor433e0532012-04-16 18:27:27 +000014732 return checkThisInStaticMemberFunctionAttributes(Method);
14733}
14734
14735bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
14736 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14737 if (!TSInfo)
14738 return false;
Erich Keanebb863642017-09-20 22:28:24 +000014739
Douglas Gregor433e0532012-04-16 18:27:27 +000014740 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000014741 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000014742 if (!ProtoTL)
14743 return false;
Erich Keanebb863642017-09-20 22:28:24 +000014744
David Blaikie6adc78e2013-02-18 22:06:02 +000014745 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000014746 FindCXXThisExpr Finder(*this);
14747
Douglas Gregor3024f072012-04-16 07:05:22 +000014748 switch (Proto->getExceptionSpecType()) {
Richard Smith0b3a4622014-11-13 20:01:57 +000014749 case EST_Unparsed:
Richard Smithf623c962012-04-17 00:58:00 +000014750 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000014751 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000014752 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000014753 case EST_DynamicNone:
14754 case EST_MSAny:
14755 case EST_None:
14756 break;
Erich Keanebb863642017-09-20 22:28:24 +000014757
Douglas Gregor3024f072012-04-16 07:05:22 +000014758 case EST_ComputedNoexcept:
14759 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
14760 return true;
Galina Kistanova33399112017-06-03 06:35:06 +000014761 LLVM_FALLTHROUGH;
Erich Keanebb863642017-09-20 22:28:24 +000014762
Douglas Gregor3024f072012-04-16 07:05:22 +000014763 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000014764 for (const auto &E : Proto->exceptions()) {
14765 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000014766 return true;
14767 }
14768 break;
14769 }
Douglas Gregor433e0532012-04-16 18:27:27 +000014770
14771 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000014772}
14773
14774bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
14775 FindCXXThisExpr Finder(*this);
14776
14777 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014778 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000014779 // FIXME: This should be emitted by tblgen.
Craig Topperc3ec1492014-05-26 06:22:03 +000014780 Expr *Arg = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +000014781 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014782 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000014783 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014784 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000014785 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014786 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014787 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014788 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014789 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014790 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000014791 Arg = ETLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000014792 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014793 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000014794 Arg = STLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000014795 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
Aaron Ballman18d85ae2014-03-20 16:02:49 +000014796 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000014797 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014798 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014799 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014800 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014801 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014802 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014803 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014804 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014805 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014806 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014807 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000014808
14809 if (Arg && !Finder.TraverseStmt(Arg))
14810 return true;
Erich Keanebb863642017-09-20 22:28:24 +000014811
Douglas Gregor3024f072012-04-16 07:05:22 +000014812 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
14813 if (!Finder.TraverseStmt(Args[I]))
14814 return true;
14815 }
14816 }
Erich Keanebb863642017-09-20 22:28:24 +000014817
Douglas Gregor3024f072012-04-16 07:05:22 +000014818 return false;
14819}
14820
Richard Smith2e321552014-11-12 02:00:47 +000014821void Sema::checkExceptionSpecification(
14822 bool IsTopLevel, ExceptionSpecificationType EST,
14823 ArrayRef<ParsedType> DynamicExceptions,
14824 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
14825 SmallVectorImpl<QualType> &Exceptions,
14826 FunctionProtoType::ExceptionSpecInfo &ESI) {
Douglas Gregor433e0532012-04-16 18:27:27 +000014827 Exceptions.clear();
Richard Smith8acb4282014-07-31 21:57:55 +000014828 ESI.Type = EST;
Douglas Gregor433e0532012-04-16 18:27:27 +000014829 if (EST == EST_Dynamic) {
14830 Exceptions.reserve(DynamicExceptions.size());
14831 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
14832 // FIXME: Preserve type source info.
14833 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
14834
Richard Smith2e321552014-11-12 02:00:47 +000014835 if (IsTopLevel) {
14836 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
14837 collectUnexpandedParameterPacks(ET, Unexpanded);
14838 if (!Unexpanded.empty()) {
14839 DiagnoseUnexpandedParameterPacks(
14840 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
14841 Unexpanded);
14842 continue;
14843 }
Douglas Gregor433e0532012-04-16 18:27:27 +000014844 }
14845
14846 // Check that the type is valid for an exception spec, and
14847 // drop it if not.
14848 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
14849 Exceptions.push_back(ET);
14850 }
Richard Smith8acb4282014-07-31 21:57:55 +000014851 ESI.Exceptions = Exceptions;
Douglas Gregor433e0532012-04-16 18:27:27 +000014852 return;
14853 }
Richard Smith8acb4282014-07-31 21:57:55 +000014854
Douglas Gregor433e0532012-04-16 18:27:27 +000014855 if (EST == EST_ComputedNoexcept) {
14856 // If an error occurred, there's no expression here.
14857 if (NoexceptExpr) {
14858 assert((NoexceptExpr->isTypeDependent() ||
14859 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
14860 Context.BoolTy) &&
14861 "Parser should have made sure that the expression is boolean");
Richard Smith2e321552014-11-12 02:00:47 +000014862 if (IsTopLevel && NoexceptExpr &&
14863 DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
Richard Smith8acb4282014-07-31 21:57:55 +000014864 ESI.Type = EST_BasicNoexcept;
Douglas Gregor433e0532012-04-16 18:27:27 +000014865 return;
14866 }
Richard Smith8acb4282014-07-31 21:57:55 +000014867
Douglas Gregor433e0532012-04-16 18:27:27 +000014868 if (!NoexceptExpr->isValueDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +000014869 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
Douglas Gregore2b37442012-05-04 22:38:52 +000014870 diag::err_noexcept_needs_constant_expression,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014871 /*AllowFold*/ false).get();
Richard Smith8acb4282014-07-31 21:57:55 +000014872 ESI.NoexceptExpr = NoexceptExpr;
Douglas Gregor433e0532012-04-16 18:27:27 +000014873 }
14874 return;
14875 }
14876}
14877
Richard Smith0b3a4622014-11-13 20:01:57 +000014878void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
14879 ExceptionSpecificationType EST,
14880 SourceRange SpecificationRange,
14881 ArrayRef<ParsedType> DynamicExceptions,
14882 ArrayRef<SourceRange> DynamicExceptionRanges,
14883 Expr *NoexceptExpr) {
14884 if (!MethodD)
14885 return;
14886
14887 // Dig out the method we're referring to.
14888 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
14889 MethodD = FunTmpl->getTemplatedDecl();
14890
14891 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
14892 if (!Method)
14893 return;
14894
14895 // Check the exception specification.
14896 llvm::SmallVector<QualType, 4> Exceptions;
14897 FunctionProtoType::ExceptionSpecInfo ESI;
14898 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
14899 DynamicExceptionRanges, NoexceptExpr, Exceptions,
14900 ESI);
14901
14902 // Update the exception specification on the function type.
14903 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
14904
14905 if (Method->isStatic())
14906 checkThisInStaticMemberFunctionExceptionSpec(Method);
14907
14908 if (Method->isVirtual()) {
14909 // Check overrides, which we previously had to delay.
14910 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
14911 OEnd = Method->end_overridden_methods();
14912 O != OEnd; ++O)
14913 CheckOverridingFunctionExceptionSpec(Method, *O);
14914 }
14915}
14916
John McCall5e77d762013-04-16 07:28:30 +000014917/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
14918///
14919MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
14920 SourceLocation DeclStart,
14921 Declarator &D, Expr *BitWidth,
14922 InClassInitStyle InitStyle,
14923 AccessSpecifier AS,
14924 AttributeList *MSPropertyAttr) {
14925 IdentifierInfo *II = D.getIdentifier();
14926 if (!II) {
14927 Diag(DeclStart, diag::err_anonymous_property);
Craig Topperc3ec1492014-05-26 06:22:03 +000014928 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +000014929 }
14930 SourceLocation Loc = D.getIdentifierLoc();
14931
14932 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14933 QualType T = TInfo->getType();
14934 if (getLangOpts().CPlusPlus) {
14935 CheckExtraCXXDefaultArguments(D);
14936
14937 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14938 UPPC_DataMemberType)) {
14939 D.setInvalidType();
14940 T = Context.IntTy;
14941 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14942 }
14943 }
14944
14945 DiagnoseFunctionSpecifiers(D.getDeclSpec());
14946
Richard Smith62f19e72016-06-25 00:15:56 +000014947 if (D.getDeclSpec().isInlineSpecified())
14948 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14949 << getLangOpts().CPlusPlus1z;
John McCall5e77d762013-04-16 07:28:30 +000014950 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14951 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14952 diag::err_invalid_thread)
14953 << DeclSpec::getSpecifierName(TSCS);
14954
14955 // Check to see if this name was declared as a member previously
Craig Topperc3ec1492014-05-26 06:22:03 +000014956 NamedDecl *PrevDecl = nullptr;
Richard Smithbecb92d2017-10-10 22:33:17 +000014957 LookupResult Previous(*this, II, Loc, LookupMemberName,
14958 ForVisibleRedeclaration);
John McCall5e77d762013-04-16 07:28:30 +000014959 LookupName(Previous, S);
14960 switch (Previous.getResultKind()) {
14961 case LookupResult::Found:
14962 case LookupResult::FoundUnresolvedValue:
14963 PrevDecl = Previous.getAsSingle<NamedDecl>();
14964 break;
14965
14966 case LookupResult::FoundOverloaded:
14967 PrevDecl = Previous.getRepresentativeDecl();
14968 break;
14969
14970 case LookupResult::NotFound:
14971 case LookupResult::NotFoundInCurrentInstantiation:
14972 case LookupResult::Ambiguous:
14973 break;
14974 }
14975
14976 if (PrevDecl && PrevDecl->isTemplateParameter()) {
14977 // Maybe we will complain about the shadowed template parameter.
14978 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14979 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000014980 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000014981 }
14982
14983 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Craig Topperc3ec1492014-05-26 06:22:03 +000014984 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000014985
14986 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000014987 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000014988 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
14989 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000014990 ProcessDeclAttributes(TUScope, NewPD, D);
14991 NewPD->setAccess(AS);
14992
14993 if (NewPD->isInvalidDecl())
14994 Record->setInvalidDecl();
14995
14996 if (D.getDeclSpec().isModulePrivateSpecified())
14997 NewPD->setModulePrivate();
14998
14999 if (NewPD->isInvalidDecl() && PrevDecl) {
15000 // Don't introduce NewFD into scope; there's already something
15001 // with the same name in the same scope.
15002 } else if (II) {
15003 PushOnScopeChains(NewPD, S);
15004 } else
15005 Record->addDecl(NewPD);
15006
15007 return NewPD;
15008}