blob: c12c9b27bb923c3d41ec7abed25f5afc747874b5 [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
146 return S->Diag(Lambda->getLocStart(),
147 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
Davide Italiano1a7f6482015-07-16 22:37:54 +0000170 switch(EST) {
171 // If this function can throw any exceptions, make a note of that.
172 case EST_MSAny:
173 case EST_None:
174 ClearExceptions();
175 ComputedEST = EST;
176 return;
177 // FIXME: If the call to this decl is using any of its default arguments, we
178 // need to search them for potentially-throwing calls.
179 // If this function has a basic noexcept, it doesn't affect the outcome.
180 case EST_BasicNoexcept:
181 return;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000182 // If we're still at noexcept(true) and there's a nothrow() callee,
183 // change to that specification.
Davide Italiano1a7f6482015-07-16 22:37:54 +0000184 case EST_DynamicNone:
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000185 if (ComputedEST == EST_BasicNoexcept)
186 ComputedEST = EST_DynamicNone;
187 return;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000188 // Check out noexcept specs.
Davide Italiano1a7f6482015-07-16 22:37:54 +0000189 case EST_ComputedNoexcept:
190 {
Richard Smithf623c962012-04-17 00:58:00 +0000191 FunctionProtoType::NoexceptResult NR =
192 Proto->getNoexceptSpec(Self->Context);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000193 assert(NR != FunctionProtoType::NR_NoNoexcept &&
194 "Must have noexcept result for EST_ComputedNoexcept.");
195 assert(NR != FunctionProtoType::NR_Dependent &&
196 "Should not generate implicit declarations for dependent cases, "
197 "and don't know how to handle them anyway.");
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000198 // noexcept(false) -> no spec on the new function
199 if (NR == FunctionProtoType::NR_Throw) {
200 ClearExceptions();
201 ComputedEST = EST_None;
202 }
203 // noexcept(true) won't change anything either.
204 return;
205 }
Davide Italiano1a7f6482015-07-16 22:37:54 +0000206 default:
207 break;
208 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000209 assert(EST == EST_Dynamic && "EST case not considered earlier.");
210 assert(ComputedEST != EST_None &&
211 "Shouldn't collect exceptions when throw-all is guaranteed.");
212 ComputedEST = EST_Dynamic;
213 // Record the exceptions in this function's exception specification.
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000214 for (const auto &E : Proto->exceptions())
David Blaikie82e95a32014-11-19 07:49:47 +0000215 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
Aaron Ballmanb088fbe2014-03-17 15:38:09 +0000216 Exceptions.push_back(E);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000217}
218
Richard Smith938f40b2011-06-11 17:19:42 +0000219void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithd3b5c9082012-07-27 04:22:15 +0000220 if (!E || ComputedEST == EST_MSAny)
Richard Smith938f40b2011-06-11 17:19:42 +0000221 return;
222
223 // FIXME:
224 //
225 // C++0x [except.spec]p14:
NAKAMURA Takumi53648472011-06-21 03:19:28 +0000226 // [An] implicit exception-specification specifies the type-id T if and
227 // only if T is allowed by the exception-specification of a function directly
228 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith938f40b2011-06-11 17:19:42 +0000229 // function it directly invokes allows all exceptions, and f shall allow no
230 // exceptions if every function it directly invokes allows no exceptions.
231 //
232 // Note in particular that if an implicit exception-specification is generated
233 // for a function containing a throw-expression, that specification can still
234 // be noexcept(true).
235 //
236 // Note also that 'directly invoked' is not defined in the standard, and there
237 // is no indication that we should only consider potentially-evaluated calls.
238 //
239 // Ultimately we should implement the intent of the standard: the exception
240 // specification should be the set of exceptions which can be thrown by the
241 // implicit definition. For now, we assume that any non-nothrow expression can
242 // throw any exception.
243
Richard Smithf623c962012-04-17 00:58:00 +0000244 if (Self->canThrow(E))
Richard Smith938f40b2011-06-11 17:19:42 +0000245 ComputedEST = EST_None;
246}
247
Anders Carlssonc80a1272009-08-25 02:29:20 +0000248bool
John McCallb268a282010-08-23 23:25:46 +0000249Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000250 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000251 if (RequireCompleteType(Param->getLocation(), Param->getType(),
252 diag::err_typecheck_decl_incomplete_type)) {
253 Param->setInvalidDecl();
254 return true;
255 }
256
Anders Carlssonc80a1272009-08-25 02:29:20 +0000257 // C++ [dcl.fct.default]p5
258 // A default argument expression is implicitly converted (clause
259 // 4) to the parameter type. The default argument expression has
260 // the same semantic constraints as the initializer expression in
261 // a declaration of a variable of the parameter type, using the
262 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000263 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
264 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000265 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
266 EqualLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000267 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000268 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman5f101b92009-12-22 02:46:13 +0000269 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000270 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000271 Arg = Result.getAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000272
Richard Smithc406cb72013-01-17 01:17:56 +0000273 CheckCompletedExpr(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000274 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000275
Anders Carlssonc80a1272009-08-25 02:29:20 +0000276 // Okay: add the default argument to the parameter
277 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000278
Douglas Gregor758cb672010-10-12 18:23:32 +0000279 // We have already instantiated this parameter; provide each of the
280 // instantiations with the uninstantiated default argument.
281 UnparsedDefaultArgInstantiationsMap::iterator InstPos
282 = UnparsedDefaultArgInstantiations.find(Param);
283 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
284 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
285 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
286
287 // We're done tracking this parameter's instantiations.
288 UnparsedDefaultArgInstantiations.erase(InstPos);
289 }
290
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000291 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000292}
293
Chris Lattner58258242008-04-10 02:22:51 +0000294/// ActOnParamDefaultArgument - Check whether the default argument
295/// provided for a function parameter is well-formed. If so, attach it
296/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000297void
John McCall48871652010-08-21 09:40:31 +0000298Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000299 Expr *DefaultArg) {
300 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000301 return;
Mike Stump11289f42009-09-09 15:08:12 +0000302
John McCall48871652010-08-21 09:40:31 +0000303 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000304 UnparsedDefaultArgLocs.erase(Param);
305
Chris Lattner199abbc2008-04-08 05:04:30 +0000306 // Default arguments are only permitted in C++
David Blaikiebbafb8a2012-03-11 07:00:24 +0000307 if (!getLangOpts().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000308 Diag(EqualLoc, diag::err_param_default_argument)
309 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000310 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000311 return;
312 }
313
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000314 // Check for unexpanded parameter packs.
315 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
316 Param->setInvalidDecl();
317 return;
Benjamin Kramer3b8044c2015-03-27 13:58:31 +0000318 }
319
320 // C++11 [dcl.fct.default]p3
321 // A default argument expression [...] shall not be specified for a
322 // parameter pack.
323 if (Param->isParameterPack()) {
324 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
325 << DefaultArg->getSourceRange();
326 return;
327 }
328
Anders Carlssonf1c26952009-08-25 01:02:06 +0000329 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000330 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
331 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000332 Param->setInvalidDecl();
333 return;
334 }
Mike Stump11289f42009-09-09 15:08:12 +0000335
John McCallb268a282010-08-23 23:25:46 +0000336 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000337}
338
Douglas Gregor58354032008-12-24 00:01:03 +0000339/// ActOnParamUnparsedDefaultArgument - We've seen a default
340/// argument for a function parameter, but we can't parse it yet
341/// because we're inside a class definition. Note that this default
342/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000343void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000344 SourceLocation EqualLoc,
345 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000346 if (!param)
347 return;
Mike Stump11289f42009-09-09 15:08:12 +0000348
John McCall48871652010-08-21 09:40:31 +0000349 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Nick Lewycky0f292892013-09-22 10:06:57 +0000350 Param->setUnparsedDefaultArg();
Anders Carlsson84613c42009-06-12 16:51:40 +0000351 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000352}
353
Douglas Gregor4d87df52008-12-16 21:30:33 +0000354/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
355/// the default argument for the parameter param failed.
Serge Pavlovb4b35782014-07-22 01:54:49 +0000356void Sema::ActOnParamDefaultArgumentError(Decl *param,
357 SourceLocation EqualLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000358 if (!param)
359 return;
Mike Stump11289f42009-09-09 15:08:12 +0000360
John McCall48871652010-08-21 09:40:31 +0000361 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000362 Param->setInvalidDecl();
Anders Carlsson84613c42009-06-12 16:51:40 +0000363 UnparsedDefaultArgLocs.erase(Param);
Serge Pavlovb4b35782014-07-22 01:54:49 +0000364 Param->setDefaultArg(new(Context)
Fariborz Jahanian7bd22e92014-10-01 18:03:51 +0000365 OpaqueValueExpr(EqualLoc,
366 Param->getType().getNonReferenceType(),
367 VK_RValue));
Douglas Gregor4d87df52008-12-16 21:30:33 +0000368}
369
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000370/// CheckExtraCXXDefaultArguments - Check for any extra default
371/// arguments in the declarator, which is not a function declaration
372/// or definition and therefore is not permitted to have default
373/// arguments. This routine should be invoked for every declarator
374/// that is not a function declaration or definition.
375void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
376 // C++ [dcl.fct.default]p3
377 // A default argument expression shall be specified only in the
378 // parameter-declaration-clause of a function declaration or in a
379 // template-parameter (14.1). It shall not be specified for a
380 // parameter pack. If it is specified in a
381 // parameter-declaration-clause, it shall not occur within a
382 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000383 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattner83f095c2009-03-28 19:18:32 +0000384 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000385 DeclaratorChunk &chunk = D.getTypeObject(i);
386 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000387 if (MightBeFunction) {
388 // This is a function declaration. It can have default arguments, but
389 // keep looking in case its return type is a function type with default
390 // arguments.
391 MightBeFunction = false;
392 continue;
393 }
Alp Tokerc5350722014-02-26 22:27:52 +0000394 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
395 ++argIdx) {
396 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000397 if (Param->hasUnparsedDefaultArg()) {
Malcolm Parsonsca9d8342016-11-17 21:00:09 +0000398 std::unique_ptr<CachedTokens> Toks =
399 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
David Majnemerb3c6d522015-01-13 07:42:33 +0000400 SourceRange SR;
401 if (Toks->size() > 1)
402 SR = SourceRange((*Toks)[1].getLocation(),
403 Toks->back().getLocation());
404 else
405 SR = UnparsedDefaultArgLocs[Param];
Douglas Gregor4d87df52008-12-16 21:30:33 +0000406 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
David Majnemerb3c6d522015-01-13 07:42:33 +0000407 << SR;
Douglas Gregor58354032008-12-24 00:01:03 +0000408 } else if (Param->getDefaultArg()) {
409 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
410 << Param->getDefaultArg()->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +0000411 Param->setDefaultArg(nullptr);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000412 }
413 }
Richard Smith5afcdf3f2013-03-06 01:37:38 +0000414 } else if (chunk.Kind != DeclaratorChunk::Paren) {
415 MightBeFunction = false;
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000416 }
417 }
418}
419
David Majnemer502b0ed2013-06-25 23:09:30 +0000420static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
421 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
422 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
423 if (!PVD->hasDefaultArg())
424 return false;
425 if (!PVD->hasInheritedDefaultArg())
426 return true;
427 }
428 return false;
429}
430
Craig Toppere4794282012-09-21 04:33:26 +0000431/// MergeCXXFunctionDecl - Merge two declarations of the same C++
432/// function, once we already know that they have the same
433/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
434/// error, false otherwise.
James Molloye9430032012-03-13 08:55:35 +0000435bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
436 Scope *S) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000437 bool Invalid = false;
438
Richard Smithc7d48d12015-05-20 17:50:35 +0000439 // The declaration context corresponding to the scope is the semantic
440 // parent, unless this is a local function declaration, in which case
441 // it is that surrounding function.
442 DeclContext *ScopeDC = New->isLocalExternDecl()
443 ? New->getLexicalDeclContext()
444 : New->getDeclContext();
445
446 // Find the previous declaration for the purpose of default arguments.
447 FunctionDecl *PrevForDefaultArgs = Old;
448 for (/**/; PrevForDefaultArgs;
449 // Don't bother looking back past the latest decl if this is a local
450 // extern declaration; nothing else could work.
451 PrevForDefaultArgs = New->isLocalExternDecl()
452 ? nullptr
453 : PrevForDefaultArgs->getPreviousDecl()) {
454 // Ignore hidden declarations.
455 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
456 continue;
457
458 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
459 !New->isCXXClassMember()) {
460 // Ignore default arguments of old decl if they are not in
461 // the same scope and this is not an out-of-line definition of
462 // a member function.
463 continue;
464 }
465
466 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
467 // If only one of these is a local function declaration, then they are
468 // declared in different scopes, even though isDeclInScope may think
469 // they're in the same scope. (If both are local, the scope check is
470 // sufficent, and if neither is local, then they are in the same scope.)
471 continue;
472 }
473
Nico Webera6916892016-06-10 18:53:04 +0000474 // We found the right previous declaration.
Richard Smithc7d48d12015-05-20 17:50:35 +0000475 break;
476 }
477
Chris Lattner199abbc2008-04-08 05:04:30 +0000478 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000479 // For non-template functions, default arguments can be added in
480 // later declarations of a function in the same
481 // scope. Declarations in different scopes have completely
482 // distinct sets of default arguments. That is, declarations in
483 // inner scopes do not acquire default arguments from
484 // declarations in outer scopes, and vice versa. In a given
485 // function declaration, all parameters subsequent to a
486 // parameter with a default argument shall have default
487 // arguments supplied in this or previous declarations. A
488 // default argument shall not be redefined by a later
489 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000490 //
491 // C++ [dcl.fct.default]p6:
Richard Smith541b38b2013-09-20 01:15:31 +0000492 // Except for member functions of class templates, the default arguments
493 // in a member function definition that appears outside of the class
494 // definition are added to the set of default arguments provided by the
Douglas Gregorc732aba2009-09-11 18:44:32 +0000495 // member function declaration in the class definition.
Richard Smithc7d48d12015-05-20 17:50:35 +0000496 for (unsigned p = 0, NumParams = PrevForDefaultArgs
497 ? PrevForDefaultArgs->getNumParams()
498 : 0;
499 p < NumParams; ++p) {
500 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
Chris Lattner199abbc2008-04-08 05:04:30 +0000501 ParmVarDecl *NewParam = New->getParamDecl(p);
502
Richard Smithc7d48d12015-05-20 17:50:35 +0000503 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
James Molloye9430032012-03-13 08:55:35 +0000504 bool NewParamHasDfl = NewParam->hasDefaultArg();
505
James Molloye9430032012-03-13 08:55:35 +0000506 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000507 unsigned DiagDefaultParamID =
508 diag::err_param_default_argument_redefinition;
509
510 // MSVC accepts that default parameters be redefined for member functions
511 // of template class. The new default parameter's value is ignored.
512 Invalid = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000513 if (getLangOpts().MicrosoftExt) {
Richard Smithc7d48d12015-05-20 17:50:35 +0000514 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000515 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000516 // Merge the old default argument into the new parameter.
517 NewParam->setHasInheritedDefaultArg();
518 if (OldParam->hasUninstantiatedDefaultArg())
519 NewParam->setUninstantiatedDefaultArg(
520 OldParam->getUninstantiatedDefaultArg());
521 else
522 NewParam->setDefaultArg(OldParam->getInit());
Richard Smith1b98ccc2014-07-19 01:39:17 +0000523 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000524 Invalid = false;
525 }
526 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000527
Francois Pichet8cb243a2011-04-10 04:58:30 +0000528 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
529 // hint here. Alternatively, we could walk the type-source information
530 // for NewParam to find the last source location in the type... but it
531 // isn't worth the effort right now. This is the kind of test case that
532 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000533 // int f(int);
534 // void g(int (*fp)(int) = f);
535 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000536 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000537 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000538
539 // Look for the function declaration where the default argument was
540 // actually written, which may be a declaration prior to Old.
Richard Smithc7d48d12015-05-20 17:50:35 +0000541 for (auto Older = PrevForDefaultArgs;
542 OldParam->hasInheritedDefaultArg(); /**/) {
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000543 Older = Older->getPreviousDecl();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000544 OldParam = Older->getParamDecl(p);
Nathan Sidwell55d53fe2015-01-30 14:21:35 +0000545 }
546
Douglas Gregorc732aba2009-09-11 18:44:32 +0000547 Diag(OldParam->getLocation(), diag::note_previous_definition)
548 << OldParam->getDefaultArgRange();
James Molloye9430032012-03-13 08:55:35 +0000549 } else if (OldParamHasDfl) {
John McCalle61b02b2010-05-04 01:53:42 +0000550 // Merge the old default argument into the new parameter.
551 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000552 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000553 NewParam->setHasInheritedDefaultArg();
Nathan Sidwell5bb231c2015-02-19 14:03:22 +0000554 if (OldParam->hasUnparsedDefaultArg())
555 NewParam->setUnparsedDefaultArg();
556 else if (OldParam->hasUninstantiatedDefaultArg())
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000557 NewParam->setUninstantiatedDefaultArg(
558 OldParam->getUninstantiatedDefaultArg());
559 else
John McCalle61b02b2010-05-04 01:53:42 +0000560 NewParam->setDefaultArg(OldParam->getInit());
James Molloye9430032012-03-13 08:55:35 +0000561 } else if (NewParamHasDfl) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000562 if (New->getDescribedFunctionTemplate()) {
563 // Paragraph 4, quoted above, only applies to non-template functions.
564 Diag(NewParam->getLocation(),
565 diag::err_param_default_argument_template_redecl)
566 << NewParam->getDefaultArgRange();
Richard Smithc7d48d12015-05-20 17:50:35 +0000567 Diag(PrevForDefaultArgs->getLocation(),
568 diag::note_template_prev_declaration)
569 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000570 } else if (New->getTemplateSpecializationKind()
571 != TSK_ImplicitInstantiation &&
572 New->getTemplateSpecializationKind() != TSK_Undeclared) {
573 // C++ [temp.expr.spec]p21:
574 // Default function arguments shall not be specified in a declaration
575 // or a definition for one of the following explicit specializations:
576 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000577 // - the explicit specialization of a member function template;
578 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000579 // template where the class template specialization to which the
580 // member function specialization belongs is implicitly
581 // instantiated.
582 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
583 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
584 << New->getDeclName()
585 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000586 } else if (New->getDeclContext()->isDependentContext()) {
587 // C++ [dcl.fct.default]p6 (DR217):
588 // Default arguments for a member function of a class template shall
589 // be specified on the initial declaration of the member function
590 // within the class template.
591 //
592 // Reading the tea leaves a bit in DR217 and its reference to DR205
593 // leads me to the conclusion that one cannot add default function
594 // arguments for an out-of-line definition of a member function of a
595 // dependent type.
596 int WhichKind = 2;
597 if (CXXRecordDecl *Record
598 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
599 if (Record->getDescribedClassTemplate())
600 WhichKind = 0;
601 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
602 WhichKind = 1;
603 else
604 WhichKind = 2;
605 }
606
607 Diag(NewParam->getLocation(),
608 diag::err_param_default_argument_member_template_redecl)
609 << WhichKind
610 << NewParam->getDefaultArgRange();
611 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000612 }
613 }
614
Richard Smith58c3cc12012-11-28 03:45:24 +0000615 // DR1344: If a default argument is added outside a class definition and that
616 // default argument makes the function a special member function, the program
617 // is ill-formed. This can only happen for constructors.
618 if (isa<CXXConstructorDecl>(New) &&
619 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
620 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
621 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
622 if (NewSM != OldSM) {
623 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
624 assert(NewParam->hasDefaultArg());
625 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
626 << NewParam->getDefaultArgRange() << NewSM;
627 Diag(Old->getLocation(), diag::note_previous_declaration);
628 }
629 }
630
David Majnemeree4f4022014-03-30 06:44:54 +0000631 const FunctionDecl *Def;
Richard Smith5b8b3db2012-02-20 23:28:05 +0000632 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smitheb3c10c2011-10-01 02:31:28 +0000633 // template has a constexpr specifier then all its declarations shall
Richard Smith5b8b3db2012-02-20 23:28:05 +0000634 // contain the constexpr specifier.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000635 if (New->isConstexpr() != Old->isConstexpr()) {
636 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
637 << New << New->isConstexpr();
638 Diag(Old->getLocation(), diag::note_previous_declaration);
639 Invalid = true;
Reid Kleckner93864172015-04-08 00:04:47 +0000640 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
641 Old->isDefined(Def)) {
David Majnemeree4f4022014-03-30 06:44:54 +0000642 // C++11 [dcl.fcn.spec]p4:
643 // If the definition of a function appears in a translation unit before its
644 // first declaration as inline, the program is ill-formed.
645 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
646 Diag(Def->getLocation(), diag::note_previous_definition);
647 Invalid = true;
Richard Smitheb3c10c2011-10-01 02:31:28 +0000648 }
649
Richard Smithafe4aa82017-02-10 02:19:05 +0000650 // FIXME: It's not clear what should happen if multiple declarations of a
651 // deduction guide have different explicitness. For now at least we simply
652 // reject any case where the explicitness changes.
653 if (New->isDeductionGuide() &&
654 New->isExplicitSpecified() != Old->isExplicitSpecified()) {
655 Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch)
656 << New->isExplicitSpecified();
657 Diag(Old->getLocation(), diag::note_previous_declaration);
658 }
659
David Majnemer502b0ed2013-06-25 23:09:30 +0000660 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000661 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000662 // the only declaration of the function or function template in the
663 // translation unit.
664 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
665 functionDeclHasDefaultArgument(Old)) {
666 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
667 Diag(Old->getLocation(), diag::note_previous_declaration);
668 Invalid = true;
669 }
670
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000671 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000672}
673
Richard Smith7873de02016-08-11 22:25:46 +0000674NamedDecl *
675Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
676 MultiTemplateParamsArg TemplateParamLists) {
677 assert(D.isDecompositionDeclarator());
678 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
679
680 // The syntax only allows a decomposition declarator as a simple-declaration
681 // or a for-range-declaration, but we parse it in more cases than that.
682 if (!D.mayHaveDecompositionDeclarator()) {
683 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
684 << Decomp.getSourceRange();
685 return nullptr;
686 }
687
688 if (!TemplateParamLists.empty()) {
689 // FIXME: There's no rule against this, but there are also no rules that
690 // would actually make it usable, so we reject it for now.
691 Diag(TemplateParamLists.front()->getTemplateLoc(),
692 diag::err_decomp_decl_template);
693 return nullptr;
694 }
695
696 Diag(Decomp.getLSquareLoc(), getLangOpts().CPlusPlus1z
697 ? diag::warn_cxx14_compat_decomp_decl
698 : diag::ext_decomp_decl)
699 << Decomp.getSourceRange();
700
701 // The semantic context is always just the current context.
702 DeclContext *const DC = CurContext;
703
704 // C++1z [dcl.dcl]/8:
705 // The decl-specifier-seq shall contain only the type-specifier auto
706 // and cv-qualifiers.
707 auto &DS = D.getDeclSpec();
708 {
709 SmallVector<StringRef, 8> BadSpecifiers;
710 SmallVector<SourceLocation, 8> BadSpecifierLocs;
711 if (auto SCS = DS.getStorageClassSpec()) {
712 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
713 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
714 }
715 if (auto TSCS = DS.getThreadStorageClassSpec()) {
716 BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
717 BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
718 }
719 if (DS.isConstexprSpecified()) {
720 BadSpecifiers.push_back("constexpr");
721 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
722 }
723 if (DS.isInlineSpecified()) {
724 BadSpecifiers.push_back("inline");
725 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
726 }
727 if (!BadSpecifiers.empty()) {
728 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
729 Err << (int)BadSpecifiers.size()
730 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
731 // Don't add FixItHints to remove the specifiers; we do still respect
732 // them when building the underlying variable.
733 for (auto Loc : BadSpecifierLocs)
734 Err << SourceRange(Loc, Loc);
735 }
736 // We can't recover from it being declared as a typedef.
737 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
738 return nullptr;
739 }
740
741 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
742 QualType R = TInfo->getType();
743
744 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
745 UPPC_DeclarationType))
746 D.setInvalidType();
747
748 // The syntax only allows a single ref-qualifier prior to the decomposition
749 // declarator. No other declarator chunks are permitted. Also check the type
750 // specifier here.
751 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
752 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
753 (D.getNumTypeObjects() == 1 &&
754 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
755 Diag(Decomp.getLSquareLoc(),
756 (D.hasGroupingParens() ||
757 (D.getNumTypeObjects() &&
758 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
759 ? diag::err_decomp_decl_parens
760 : diag::err_decomp_decl_type)
761 << R;
762
763 // In most cases, there's no actual problem with an explicitly-specified
764 // type, but a function type won't work here, and ActOnVariableDeclarator
765 // shouldn't be called for such a type.
766 if (R->isFunctionType())
767 D.setInvalidType();
768 }
769
770 // Build the BindingDecls.
771 SmallVector<BindingDecl*, 8> Bindings;
772
773 // Build the BindingDecls.
774 for (auto &B : D.getDecompositionDeclarator().bindings()) {
775 // Check for name conflicts.
776 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
777 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
778 ForRedeclaration);
779 LookupName(Previous, S,
780 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
781
782 // It's not permitted to shadow a template parameter name.
783 if (Previous.isSingleResult() &&
784 Previous.getFoundDecl()->isTemplateParameter()) {
785 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
786 Previous.getFoundDecl());
787 Previous.clear();
788 }
789
790 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
791 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
792 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
793 /*AllowInlineNamespace*/false);
794 if (!Previous.empty()) {
795 auto *Old = Previous.getRepresentativeDecl();
796 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
797 Diag(Old->getLocation(), diag::note_previous_definition);
798 }
799
Richard Smith32cb8c92016-08-12 00:53:41 +0000800 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
Richard Smith7873de02016-08-11 22:25:46 +0000801 PushOnScopeChains(BD, S, true);
802 Bindings.push_back(BD);
803 ParsingInitForAutoVars.insert(BD);
804 }
805
806 // There are no prior lookup results for the variable itself, because it
807 // is unnamed.
808 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
809 Decomp.getLSquareLoc());
810 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
811
812 // Build the variable that holds the non-decomposed object.
813 bool AddToScope = true;
814 NamedDecl *New =
815 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
816 MultiTemplateParamsArg(), AddToScope, Bindings);
817 CurContext->addHiddenDecl(New);
818
819 if (isInOpenMPDeclareTargetContext())
820 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
821
822 return New;
823}
824
825static bool checkSimpleDecomposition(
826 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
Benjamin Kramer6ca15b62016-11-24 15:36:17 +0000827 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
Richard Smith7873de02016-08-11 22:25:46 +0000828 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
829 if ((int64_t)Bindings.size() != NumElems) {
830 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
831 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
832 << (NumElems < Bindings.size());
833 return true;
834 }
835
836 unsigned I = 0;
837 for (auto *B : Bindings) {
838 SourceLocation Loc = B->getLocation();
839 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
840 if (E.isInvalid())
841 return true;
842 E = GetInit(Loc, E.get(), I++);
843 if (E.isInvalid())
844 return true;
845 B->setBinding(ElemType, E.get());
846 }
847
848 return false;
849}
850
851static bool checkArrayLikeDecomposition(Sema &S,
852 ArrayRef<BindingDecl *> Bindings,
853 ValueDecl *Src, QualType DecompType,
Benjamin Kramer6ca15b62016-11-24 15:36:17 +0000854 const llvm::APSInt &NumElems,
Richard Smith7873de02016-08-11 22:25:46 +0000855 QualType ElemType) {
856 return checkSimpleDecomposition(
857 S, Bindings, Src, DecompType, NumElems, ElemType,
858 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
859 ExprResult E = S.ActOnIntegerConstant(Loc, I);
860 if (E.isInvalid())
861 return ExprError();
862 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
863 });
864}
865
866static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
867 ValueDecl *Src, QualType DecompType,
868 const ConstantArrayType *CAT) {
869 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
870 llvm::APSInt(CAT->getSize()),
871 CAT->getElementType());
872}
873
874static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
875 ValueDecl *Src, QualType DecompType,
876 const VectorType *VT) {
877 return checkArrayLikeDecomposition(
878 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
879 S.Context.getQualifiedType(VT->getElementType(),
880 DecompType.getQualifiers()));
881}
882
883static bool checkComplexDecomposition(Sema &S,
884 ArrayRef<BindingDecl *> Bindings,
885 ValueDecl *Src, QualType DecompType,
886 const ComplexType *CT) {
887 return checkSimpleDecomposition(
888 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
889 S.Context.getQualifiedType(CT->getElementType(),
890 DecompType.getQualifiers()),
891 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
892 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
893 });
894}
895
896static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
897 TemplateArgumentListInfo &Args) {
898 SmallString<128> SS;
899 llvm::raw_svector_ostream OS(SS);
900 bool First = true;
901 for (auto &Arg : Args.arguments()) {
902 if (!First)
903 OS << ", ";
904 Arg.getArgument().print(PrintingPolicy, OS);
905 First = false;
906 }
907 return OS.str();
908}
909
910static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
911 SourceLocation Loc, StringRef Trait,
912 TemplateArgumentListInfo &Args,
913 unsigned DiagID) {
914 auto DiagnoseMissing = [&] {
915 if (DiagID)
916 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
917 Args);
918 return true;
919 };
920
921 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
922 NamespaceDecl *Std = S.getStdNamespace();
923 if (!Std)
924 return DiagnoseMissing();
925
926 // Look up the trait itself, within namespace std. We can diagnose various
927 // problems with this lookup even if we've been asked to not diagnose a
928 // missing specialization, because this can only fail if the user has been
929 // declaring their own names in namespace std or we don't support the
930 // standard library implementation in use.
931 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
932 Loc, Sema::LookupOrdinaryName);
933 if (!S.LookupQualifiedName(Result, Std))
934 return DiagnoseMissing();
935 if (Result.isAmbiguous())
936 return true;
937
938 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
939 if (!TraitTD) {
940 Result.suppressDiagnostics();
941 NamedDecl *Found = *Result.begin();
942 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
943 S.Diag(Found->getLocation(), diag::note_declared_at);
944 return true;
945 }
946
947 // Build the template-id.
948 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
949 if (TraitTy.isNull())
950 return true;
951 if (!S.isCompleteType(Loc, TraitTy)) {
952 if (DiagID)
953 S.RequireCompleteType(
954 Loc, TraitTy, DiagID,
955 printTemplateArgs(S.Context.getPrintingPolicy(), Args));
956 return true;
957 }
958
959 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
960 assert(RD && "specialization of class template is not a class?");
961
962 // Look up the member of the trait type.
963 S.LookupQualifiedName(TraitMemberLookup, RD);
964 return TraitMemberLookup.isAmbiguous();
965}
966
967static TemplateArgumentLoc
968getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
969 uint64_t I) {
970 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
971 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
972}
973
974static TemplateArgumentLoc
975getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
976 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
977}
978
979namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
980
981static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
982 llvm::APSInt &Size) {
983 EnterExpressionEvaluationContext ContextRAII(S, Sema::ConstantEvaluated);
984
985 DeclarationName Value = S.PP.getIdentifierInfo("value");
986 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
987
988 // Form template argument list for tuple_size<T>.
989 TemplateArgumentListInfo Args(Loc, Loc);
990 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
991
992 // If there's no tuple_size specialization, it's not tuple-like.
993 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
994 return IsTupleLike::NotTupleLike;
995
Richard Smith208732e2016-12-08 03:24:55 +0000996 // If we get this far, we've committed to the tuple interpretation, but
997 // we can still fail if there actually isn't a usable ::value.
Richard Smith7873de02016-08-11 22:25:46 +0000998
999 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1000 LookupResult &R;
1001 TemplateArgumentListInfo &Args;
1002 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1003 : R(R), Args(Args) {}
1004 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1005 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1006 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1007 }
1008 } Diagnoser(R, Args);
1009
1010 if (R.empty()) {
1011 Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1012 return IsTupleLike::Error;
1013 }
1014
1015 ExprResult E =
1016 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1017 if (E.isInvalid())
1018 return IsTupleLike::Error;
1019
1020 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1021 if (E.isInvalid())
1022 return IsTupleLike::Error;
1023
1024 return IsTupleLike::TupleLike;
1025}
1026
1027/// \return std::tuple_element<I, T>::type.
1028static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1029 unsigned I, QualType T) {
1030 // Form template argument list for tuple_element<I, T>.
1031 TemplateArgumentListInfo Args(Loc, Loc);
1032 Args.addArgument(
1033 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1034 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1035
1036 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1037 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1038 if (lookupStdTypeTraitMember(
1039 S, R, Loc, "tuple_element", Args,
1040 diag::err_decomp_decl_std_tuple_element_not_specialized))
1041 return QualType();
1042
1043 auto *TD = R.getAsSingle<TypeDecl>();
1044 if (!TD) {
1045 R.suppressDiagnostics();
1046 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1047 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1048 if (!R.empty())
1049 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1050 return QualType();
1051 }
1052
1053 return S.Context.getTypeDeclType(TD);
1054}
1055
1056namespace {
1057struct BindingDiagnosticTrap {
1058 Sema &S;
1059 DiagnosticErrorTrap Trap;
1060 BindingDecl *BD;
1061
1062 BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1063 : S(S), Trap(S.Diags), BD(BD) {}
1064 ~BindingDiagnosticTrap() {
1065 if (Trap.hasErrorOccurred())
1066 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1067 }
1068};
1069}
1070
Richard Smith3997b1b2016-08-12 01:55:21 +00001071static bool checkTupleLikeDecomposition(Sema &S,
1072 ArrayRef<BindingDecl *> Bindings,
Richard Smith97fcf4b2016-08-14 23:15:52 +00001073 VarDecl *Src, QualType DecompType,
Benjamin Kramer6ca15b62016-11-24 15:36:17 +00001074 const llvm::APSInt &TupleSize) {
Richard Smith7873de02016-08-11 22:25:46 +00001075 if ((int64_t)Bindings.size() != TupleSize) {
1076 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1077 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1078 << (TupleSize < Bindings.size());
1079 return true;
1080 }
1081
1082 if (Bindings.empty())
1083 return false;
1084
1085 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1086
1087 // [dcl.decomp]p3:
1088 // The unqualified-id get is looked up in the scope of E by class member
1089 // access lookup
1090 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1091 bool UseMemberGet = false;
1092 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1093 if (auto *RD = DecompType->getAsCXXRecordDecl())
1094 S.LookupQualifiedName(MemberGet, RD);
1095 if (MemberGet.isAmbiguous())
1096 return true;
1097 UseMemberGet = !MemberGet.empty();
1098 S.FilterAcceptableTemplateNames(MemberGet);
1099 }
1100
1101 unsigned I = 0;
1102 for (auto *B : Bindings) {
1103 BindingDiagnosticTrap Trap(S, B);
1104 SourceLocation Loc = B->getLocation();
1105
1106 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1107 if (E.isInvalid())
1108 return true;
1109
1110 // e is an lvalue if the type of the entity is an lvalue reference and
1111 // an xvalue otherwise
1112 if (!Src->getType()->isLValueReferenceType())
1113 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1114 E.get(), nullptr, VK_XValue);
1115
1116 TemplateArgumentListInfo Args(Loc, Loc);
1117 Args.addArgument(
1118 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1119
1120 if (UseMemberGet) {
1121 // if [lookup of member get] finds at least one declaration, the
1122 // initializer is e.get<i-1>().
1123 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1124 CXXScopeSpec(), SourceLocation(), nullptr,
1125 MemberGet, &Args, nullptr);
1126 if (E.isInvalid())
1127 return true;
1128
1129 E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
1130 } else {
1131 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1132 // in the associated namespaces.
1133 Expr *Get = UnresolvedLookupExpr::Create(
1134 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1135 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1136 UnresolvedSetIterator(), UnresolvedSetIterator());
1137
1138 Expr *Arg = E.get();
1139 E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
1140 }
1141 if (E.isInvalid())
1142 return true;
1143 Expr *Init = E.get();
1144
1145 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1146 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1147 if (T.isNull())
1148 return true;
1149
1150 // each vi is a variable of type "reference to T" initialized with the
1151 // initializer, where the reference is an lvalue reference if the
1152 // initializer is an lvalue and an rvalue reference otherwise
1153 QualType RefType =
1154 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1155 if (RefType.isNull())
1156 return true;
Richard Smith97fcf4b2016-08-14 23:15:52 +00001157 auto *RefVD = VarDecl::Create(
1158 S.Context, Src->getDeclContext(), Loc, Loc,
1159 B->getDeclName().getAsIdentifierInfo(), RefType,
1160 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1161 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1162 RefVD->setTSCSpec(Src->getTSCSpec());
1163 RefVD->setImplicit();
1164 if (Src->isInlineSpecified())
1165 RefVD->setInlineSpecified();
Richard Smithda383632016-08-15 01:33:41 +00001166 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
Richard Smith7873de02016-08-11 22:25:46 +00001167
Richard Smith97fcf4b2016-08-14 23:15:52 +00001168 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
Richard Smith7873de02016-08-11 22:25:46 +00001169 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1170 InitializationSequence Seq(S, Entity, Kind, Init);
1171 E = Seq.Perform(S, Entity, Kind, Init);
1172 if (E.isInvalid())
1173 return true;
Richard Smithda383632016-08-15 01:33:41 +00001174 E = S.ActOnFinishFullExpr(E.get(), Loc);
1175 if (E.isInvalid())
1176 return true;
Richard Smith97fcf4b2016-08-14 23:15:52 +00001177 RefVD->setInit(E.get());
1178 RefVD->checkInitIsICE();
1179
Richard Smith97fcf4b2016-08-14 23:15:52 +00001180 E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1181 DeclarationNameInfo(B->getDeclName(), Loc),
1182 RefVD);
1183 if (E.isInvalid())
1184 return true;
Richard Smith7873de02016-08-11 22:25:46 +00001185
1186 B->setBinding(T, E.get());
1187 I++;
1188 }
1189
1190 return false;
1191}
1192
1193/// Find the base class to decompose in a built-in decomposition of a class type.
1194/// This base class search is, unfortunately, not quite like any other that we
1195/// perform anywhere else in C++.
1196static const CXXRecordDecl *findDecomposableBaseClass(Sema &S,
1197 SourceLocation Loc,
1198 const CXXRecordDecl *RD,
1199 CXXCastPath &BasePath) {
1200 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1201 CXXBasePath &Path) {
1202 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1203 };
1204
1205 const CXXRecordDecl *ClassWithFields = nullptr;
1206 if (RD->hasDirectFields())
1207 // [dcl.decomp]p4:
1208 // Otherwise, all of E's non-static data members shall be public direct
1209 // members of E ...
1210 ClassWithFields = RD;
1211 else {
1212 // ... or of ...
1213 CXXBasePaths Paths;
1214 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1215 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1216 // If no classes have fields, just decompose RD itself. (This will work
1217 // if and only if zero bindings were provided.)
1218 return RD;
1219 }
1220
1221 CXXBasePath *BestPath = nullptr;
1222 for (auto &P : Paths) {
1223 if (!BestPath)
1224 BestPath = &P;
1225 else if (!S.Context.hasSameType(P.back().Base->getType(),
1226 BestPath->back().Base->getType())) {
1227 // ... the same ...
1228 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1229 << false << RD << BestPath->back().Base->getType()
1230 << P.back().Base->getType();
1231 return nullptr;
1232 } else if (P.Access < BestPath->Access) {
1233 BestPath = &P;
1234 }
1235 }
1236
1237 // ... unambiguous ...
1238 QualType BaseType = BestPath->back().Base->getType();
1239 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1240 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1241 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1242 return nullptr;
1243 }
1244
1245 // ... public base class of E.
1246 if (BestPath->Access != AS_public) {
1247 S.Diag(Loc, diag::err_decomp_decl_non_public_base)
1248 << RD << BaseType;
1249 for (auto &BS : *BestPath) {
1250 if (BS.Base->getAccessSpecifier() != AS_public) {
1251 S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path)
1252 << (BS.Base->getAccessSpecifier() == AS_protected)
1253 << (BS.Base->getAccessSpecifierAsWritten() == AS_none);
1254 break;
1255 }
1256 }
1257 return nullptr;
1258 }
1259
1260 ClassWithFields = BaseType->getAsCXXRecordDecl();
1261 S.BuildBasePathArray(Paths, BasePath);
1262 }
1263
1264 // The above search did not check whether the selected class itself has base
1265 // classes with fields, so check that now.
1266 CXXBasePaths Paths;
1267 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1268 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1269 << (ClassWithFields == RD) << RD << ClassWithFields
1270 << Paths.front().back().Base->getType();
1271 return nullptr;
1272 }
1273
1274 return ClassWithFields;
1275}
1276
1277static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1278 ValueDecl *Src, QualType DecompType,
1279 const CXXRecordDecl *RD) {
1280 CXXCastPath BasePath;
1281 RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath);
1282 if (!RD)
1283 return true;
1284 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1285 DecompType.getQualifiers());
1286
1287 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
Richard Smithf70a9062016-10-20 18:29:25 +00001288 unsigned NumFields =
1289 std::count_if(RD->field_begin(), RD->field_end(),
1290 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
Richard Smith7873de02016-08-11 22:25:46 +00001291 assert(Bindings.size() != NumFields);
1292 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1293 << DecompType << (unsigned)Bindings.size() << NumFields
1294 << (NumFields < Bindings.size());
1295 return true;
1296 };
1297
1298 // all of E's non-static data members shall be public [...] members,
1299 // E shall not have an anonymous union member, ...
1300 unsigned I = 0;
1301 for (auto *FD : RD->fields()) {
1302 if (FD->isUnnamedBitfield())
1303 continue;
1304
1305 if (FD->isAnonymousStructOrUnion()) {
1306 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1307 << DecompType << FD->getType()->isUnionType();
1308 S.Diag(FD->getLocation(), diag::note_declared_at);
1309 return true;
1310 }
1311
1312 // We have a real field to bind.
1313 if (I >= Bindings.size())
1314 return DiagnoseBadNumberOfBindings();
1315 auto *B = Bindings[I++];
1316
1317 SourceLocation Loc = B->getLocation();
1318 if (FD->getAccess() != AS_public) {
1319 S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType;
1320
1321 // Determine whether the access specifier was explicit.
1322 bool Implicit = true;
1323 for (const auto *D : RD->decls()) {
1324 if (declaresSameEntity(D, FD))
1325 break;
1326 if (isa<AccessSpecDecl>(D)) {
1327 Implicit = false;
1328 break;
1329 }
1330 }
1331
1332 S.Diag(FD->getLocation(), diag::note_access_natural)
1333 << (FD->getAccess() == AS_protected) << Implicit;
1334 return true;
1335 }
1336
1337 // Initialize the binding to Src.FD.
1338 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1339 if (E.isInvalid())
1340 return true;
1341 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1342 VK_LValue, &BasePath);
1343 if (E.isInvalid())
1344 return true;
1345 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1346 CXXScopeSpec(), FD,
1347 DeclAccessPair::make(FD, FD->getAccess()),
1348 DeclarationNameInfo(FD->getDeclName(), Loc));
1349 if (E.isInvalid())
1350 return true;
1351
1352 // If the type of the member is T, the referenced type is cv T, where cv is
1353 // the cv-qualification of the decomposition expression.
1354 //
1355 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1356 // 'const' to the type of the field.
1357 Qualifiers Q = DecompType.getQualifiers();
1358 if (FD->isMutable())
1359 Q.removeConst();
1360 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1361 }
1362
1363 if (I != Bindings.size())
1364 return DiagnoseBadNumberOfBindings();
1365
1366 return false;
1367}
1368
Richard Smith3997b1b2016-08-12 01:55:21 +00001369void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
Richard Smith7873de02016-08-11 22:25:46 +00001370 QualType DecompType = DD->getType();
1371
1372 // If the type of the decomposition is dependent, then so is the type of
1373 // each binding.
1374 if (DecompType->isDependentType()) {
1375 for (auto *B : DD->bindings())
1376 B->setType(Context.DependentTy);
1377 return;
1378 }
1379
1380 DecompType = DecompType.getNonReferenceType();
1381 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1382
1383 // C++1z [dcl.decomp]/2:
1384 // If E is an array type [...]
1385 // As an extension, we also support decomposition of built-in complex and
1386 // vector types.
1387 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1388 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1389 DD->setInvalidDecl();
1390 return;
1391 }
1392 if (auto *VT = DecompType->getAs<VectorType>()) {
1393 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1394 DD->setInvalidDecl();
1395 return;
1396 }
1397 if (auto *CT = DecompType->getAs<ComplexType>()) {
1398 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1399 DD->setInvalidDecl();
1400 return;
1401 }
1402
1403 // C++1z [dcl.decomp]/3:
1404 // if the expression std::tuple_size<E>::value is a well-formed integral
1405 // constant expression, [...]
1406 llvm::APSInt TupleSize(32);
1407 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1408 case IsTupleLike::Error:
1409 DD->setInvalidDecl();
1410 return;
1411
1412 case IsTupleLike::TupleLike:
Richard Smith3997b1b2016-08-12 01:55:21 +00001413 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
Richard Smith7873de02016-08-11 22:25:46 +00001414 DD->setInvalidDecl();
1415 return;
1416
1417 case IsTupleLike::NotTupleLike:
1418 break;
1419 }
1420
1421 // C++1z [dcl.dcl]/8:
1422 // [E shall be of array or non-union class type]
1423 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1424 if (!RD || RD->isUnion()) {
1425 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1426 << DD << !RD << DecompType;
1427 DD->setInvalidDecl();
1428 return;
1429 }
1430
1431 // C++1z [dcl.decomp]/4:
1432 // all of E's non-static data members shall be [...] direct members of
1433 // E or of the same unambiguous public base class of E, ...
1434 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1435 DD->setInvalidDecl();
1436}
1437
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001438/// \brief Merge the exception specifications of two variable declarations.
1439///
1440/// This is called when there's a redeclaration of a VarDecl. The function
1441/// checks if the redeclaration might have an exception specification and
1442/// validates compatibility and merges the specs if necessary.
1443void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1444 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001445 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001446 return;
1447
1448 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1449 "Should only be called if types are otherwise the same.");
1450
1451 QualType NewType = New->getType();
1452 QualType OldType = Old->getType();
1453
1454 // We're only interested in pointers and references to functions, as well
1455 // as pointers to member functions.
1456 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1457 NewType = R->getPointeeType();
1458 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1459 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1460 NewType = P->getPointeeType();
1461 OldType = OldType->getAs<PointerType>()->getPointeeType();
1462 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1463 NewType = M->getPointeeType();
1464 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1465 }
1466
1467 if (!NewType->isFunctionProtoType())
1468 return;
1469
1470 // There's lots of special cases for functions. For function pointers, system
1471 // libraries are hopefully not as broken so that we don't need these
1472 // workarounds.
1473 if (CheckEquivalentExceptionSpec(
1474 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1475 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1476 New->setInvalidDecl();
1477 }
1478}
1479
Chris Lattner199abbc2008-04-08 05:04:30 +00001480/// CheckCXXDefaultArguments - Verify that the default arguments for a
1481/// function declaration are well-formed according to C++
1482/// [dcl.fct.default].
1483void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1484 unsigned NumParams = FD->getNumParams();
1485 unsigned p;
1486
1487 // Find first parameter with a default argument
1488 for (p = 0; p < NumParams; ++p) {
1489 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +00001490 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +00001491 break;
1492 }
1493
Benjamin Kramerfe257592015-03-27 13:58:41 +00001494 // C++11 [dcl.fct.default]p4:
1495 // In a given function declaration, each parameter subsequent to a parameter
1496 // with a default argument shall have a default argument supplied in this or
1497 // a previous declaration or shall be a function parameter pack. A default
1498 // argument shall not be redefined by a later declaration (not even to the
1499 // same value).
Chris Lattner199abbc2008-04-08 05:04:30 +00001500 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001501 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +00001502 ParmVarDecl *Param = FD->getParamDecl(p);
Benjamin Kramerfe257592015-03-27 13:58:41 +00001503 if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00001504 if (Param->isInvalidDecl())
1505 /* We already complained about this parameter. */;
1506 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +00001507 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +00001508 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +00001509 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +00001510 else
Mike Stump11289f42009-09-09 15:08:12 +00001511 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +00001512 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +00001513
Chris Lattner199abbc2008-04-08 05:04:30 +00001514 LastMissingDefaultArg = p;
1515 }
1516 }
1517
1518 if (LastMissingDefaultArg > 0) {
1519 // Some default arguments were missing. Clear out all of the
1520 // default arguments up to (and including) the last missing
1521 // default argument, so that we leave the function parameters
1522 // in a semantically valid state.
1523 for (p = 0; p <= LastMissingDefaultArg; ++p) {
1524 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +00001525 if (Param->hasDefaultArg()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001526 Param->setDefaultArg(nullptr);
Chris Lattner199abbc2008-04-08 05:04:30 +00001527 }
1528 }
1529 }
1530}
Douglas Gregor556877c2008-04-13 21:30:24 +00001531
Richard Smitheb3c10c2011-10-01 02:31:28 +00001532// CheckConstexprParameterTypes - Check whether a function's parameter types
1533// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +00001534// diagnostic and return false.
1535static bool CheckConstexprParameterTypes(Sema &SemaRef,
1536 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001537 unsigned ArgIndex = 0;
1538 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001539 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1540 e = FT->param_type_end();
1541 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001542 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1543 SourceLocation ParamLoc = PD->getLocation();
1544 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +00001545 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +00001546 diag::err_constexpr_non_literal_param,
1547 ArgIndex+1, PD->getSourceRange(),
1548 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +00001549 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001550 }
Joao Matose9a3ed42012-08-31 22:18:20 +00001551 return true;
1552}
1553
1554/// \brief Get diagnostic %select index for tag kind for
1555/// record diagnostic message.
1556/// WARNING: Indexes apply to particular diagnostics only!
1557///
1558/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +00001559static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +00001560 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +00001561 case TTK_Struct: return 0;
1562 case TTK_Interface: return 1;
1563 case TTK_Class: return 2;
1564 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +00001565 }
Joao Matose9a3ed42012-08-31 22:18:20 +00001566}
1567
1568// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1569// the requirements of a constexpr function definition or a constexpr
1570// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +00001571// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +00001572//
Richard Smith3607ffe2012-02-13 03:54:03 +00001573// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1574bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +00001575 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1576 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +00001577 // C++11 [dcl.constexpr]p4:
1578 // The definition of a constexpr constructor shall satisfy the following
1579 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001580 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +00001581 const CXXRecordDecl *RD = MD->getParent();
1582 if (RD->getNumVBases()) {
1583 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1584 << isa<CXXConstructorDecl>(NewFD)
1585 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Aaron Ballman445a9392014-03-13 16:15:17 +00001586 for (const auto &I : RD->vbases())
1587 Diag(I.getLocStart(),
1588 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +00001589 return false;
1590 }
Richard Smith7971b692012-01-13 04:54:00 +00001591 }
1592
1593 if (!isa<CXXConstructorDecl>(NewFD)) {
1594 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001595 // The definition of a constexpr function shall satisfy the following
1596 // constraints:
1597 // - it shall not be virtual;
1598 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1599 if (Method && Method->isVirtual()) {
David Majnemerab6607a2015-05-22 05:49:41 +00001600 Method = Method->getCanonicalDecl();
1601 Diag(Method->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001602
Richard Smith3607ffe2012-02-13 03:54:03 +00001603 // If it's not obvious why this function is virtual, find an overridden
1604 // function which uses the 'virtual' keyword.
1605 const CXXMethodDecl *WrittenVirtual = Method;
1606 while (!WrittenVirtual->isVirtualAsWritten())
1607 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1608 if (WrittenVirtual != Method)
1609 Diag(WrittenVirtual->getLocation(),
1610 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001611 return false;
1612 }
1613
1614 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +00001615 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +00001616 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +00001617 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +00001618 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +00001619 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001620 }
1621
Richard Smith7971b692012-01-13 04:54:00 +00001622 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +00001623 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +00001624 return false;
1625
Richard Smitheb3c10c2011-10-01 02:31:28 +00001626 return true;
1627}
1628
1629/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +00001630/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +00001631///
Richard Smithd9f663b2013-04-22 15:31:51 +00001632/// \return true if the body is OK (maybe only as an extension), false if we
1633/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +00001634static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +00001635 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1636 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001637 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1638 // contain only
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001639 for (const auto *DclIt : DS->decls()) {
1640 switch (DclIt->getKind()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001641 case Decl::StaticAssert:
1642 case Decl::Using:
1643 case Decl::UsingShadow:
1644 case Decl::UsingDirective:
1645 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +00001646 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001647 // - static_assert-declarations
1648 // - using-declarations,
1649 // - using-directives,
1650 continue;
1651
1652 case Decl::Typedef:
1653 case Decl::TypeAlias: {
1654 // - typedef declarations and alias-declarations that do not define
1655 // classes or enumerations,
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001656 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001657 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1658 // Don't allow variably-modified types in constexpr functions.
1659 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1660 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1661 << TL.getSourceRange() << TL.getType()
1662 << isa<CXXConstructorDecl>(Dcl);
1663 return false;
1664 }
1665 continue;
1666 }
1667
1668 case Decl::Enum:
1669 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +00001670 // C++1y allows types to be defined, not just declared.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001671 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smithd9f663b2013-04-22 15:31:51 +00001672 SemaRef.Diag(DS->getLocStart(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001673 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001674 ? diag::warn_cxx11_compat_constexpr_type_definition
1675 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +00001676 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001677 continue;
1678
Richard Smithd9f663b2013-04-22 15:31:51 +00001679 case Decl::EnumConstant:
1680 case Decl::IndirectField:
1681 case Decl::ParmVar:
1682 // These can only appear with other declarations which are banned in
1683 // C++11 and permitted in C++1y, so ignore them.
1684 continue;
1685
Richard Smithdca60b42016-08-12 00:39:32 +00001686 case Decl::Var:
1687 case Decl::Decomposition: {
Richard Smithd9f663b2013-04-22 15:31:51 +00001688 // C++1y [dcl.constexpr]p3 allows anything except:
1689 // a definition of a variable of non-literal type or of static or
1690 // thread storage duration or for which no initialization is performed.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001691 const auto *VD = cast<VarDecl>(DclIt);
Richard Smithd9f663b2013-04-22 15:31:51 +00001692 if (VD->isThisDeclarationADefinition()) {
1693 if (VD->isStaticLocal()) {
1694 SemaRef.Diag(VD->getLocation(),
1695 diag::err_constexpr_local_var_static)
1696 << isa<CXXConstructorDecl>(Dcl)
1697 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1698 return false;
1699 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001700 if (!VD->getType()->isDependentType() &&
1701 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +00001702 VD->getLocation(), VD->getType(),
1703 diag::err_constexpr_local_var_non_literal_type,
1704 isa<CXXConstructorDecl>(Dcl)))
1705 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +00001706 if (!VD->getType()->isDependentType() &&
1707 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001708 SemaRef.Diag(VD->getLocation(),
1709 diag::err_constexpr_local_var_no_init)
1710 << isa<CXXConstructorDecl>(Dcl);
1711 return false;
1712 }
1713 }
1714 SemaRef.Diag(VD->getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001715 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001716 ? diag::warn_cxx11_compat_constexpr_local_var
1717 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +00001718 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +00001719 continue;
1720 }
1721
1722 case Decl::NamespaceAlias:
1723 case Decl::Function:
1724 // These are disallowed in C++11 and permitted in C++1y. Allow them
1725 // everywhere as an extension.
1726 if (!Cxx1yLoc.isValid())
1727 Cxx1yLoc = DS->getLocStart();
1728 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001729
1730 default:
1731 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1732 << isa<CXXConstructorDecl>(Dcl);
1733 return false;
1734 }
1735 }
1736
1737 return true;
1738}
1739
1740/// Check that the given field is initialized within a constexpr constructor.
1741///
1742/// \param Dcl The constexpr constructor being checked.
1743/// \param Field The field being checked. This may be a member of an anonymous
1744/// struct or union nested within the class being checked.
1745/// \param Inits All declarations, including anonymous struct/union members and
1746/// indirect members, for which any initialization was provided.
1747/// \param Diagnosed Set to true if an error is produced.
1748static void CheckConstexprCtorInitializer(Sema &SemaRef,
1749 const FunctionDecl *Dcl,
1750 FieldDecl *Field,
1751 llvm::SmallSet<Decl*, 16> &Inits,
1752 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00001753 if (Field->isInvalidDecl())
1754 return;
1755
Douglas Gregor556e5862011-10-10 17:22:13 +00001756 if (Field->isUnnamedBitfield())
1757 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +00001758
Richard Smithab44d5b2013-12-10 08:25:00 +00001759 // Anonymous unions with no variant members and empty anonymous structs do not
1760 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1761 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +00001762 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +00001763 (Field->getType()->isUnionType()
1764 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1765 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +00001766 return;
1767
Richard Smitheb3c10c2011-10-01 02:31:28 +00001768 if (!Inits.count(Field)) {
1769 if (!Diagnosed) {
1770 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1771 Diagnosed = true;
1772 }
1773 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1774 } else if (Field->isAnonymousStructOrUnion()) {
1775 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001776 for (auto *I : RD->fields())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001777 // If an anonymous union contains an anonymous struct of which any member
1778 // is initialized, all members must be initialized.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001779 if (!RD->isUnion() || Inits.count(I))
1780 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001781 }
1782}
1783
Richard Smithd9f663b2013-04-22 15:31:51 +00001784/// Check the provided statement is allowed in a constexpr function
1785/// definition.
1786static bool
1787CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00001788 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001789 SourceLocation &Cxx1yLoc) {
1790 // - its function-body shall be [...] a compound-statement that contains only
1791 switch (S->getStmtClass()) {
1792 case Stmt::NullStmtClass:
1793 // - null statements,
1794 return true;
1795
1796 case Stmt::DeclStmtClass:
1797 // - static_assert-declarations
1798 // - using-declarations,
1799 // - using-directives,
1800 // - typedef declarations and alias-declarations that do not define
1801 // classes or enumerations,
1802 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1803 return false;
1804 return true;
1805
1806 case Stmt::ReturnStmtClass:
1807 // - and exactly one return statement;
1808 if (isa<CXXConstructorDecl>(Dcl)) {
1809 // C++1y allows return statements in constexpr constructors.
1810 if (!Cxx1yLoc.isValid())
1811 Cxx1yLoc = S->getLocStart();
1812 return true;
1813 }
1814
1815 ReturnStmts.push_back(S->getLocStart());
1816 return true;
1817
1818 case Stmt::CompoundStmtClass: {
1819 // C++1y allows compound-statements.
1820 if (!Cxx1yLoc.isValid())
1821 Cxx1yLoc = S->getLocStart();
1822
1823 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001824 for (auto *BodyIt : CompStmt->body()) {
1825 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001826 Cxx1yLoc))
1827 return false;
1828 }
1829 return true;
1830 }
1831
1832 case Stmt::AttributedStmtClass:
1833 if (!Cxx1yLoc.isValid())
1834 Cxx1yLoc = S->getLocStart();
1835 return true;
1836
1837 case Stmt::IfStmtClass: {
1838 // C++1y allows if-statements.
1839 if (!Cxx1yLoc.isValid())
1840 Cxx1yLoc = S->getLocStart();
1841
1842 IfStmt *If = cast<IfStmt>(S);
1843 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1844 Cxx1yLoc))
1845 return false;
1846 if (If->getElse() &&
1847 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1848 Cxx1yLoc))
1849 return false;
1850 return true;
1851 }
1852
1853 case Stmt::WhileStmtClass:
1854 case Stmt::DoStmtClass:
1855 case Stmt::ForStmtClass:
1856 case Stmt::CXXForRangeStmtClass:
1857 case Stmt::ContinueStmtClass:
1858 // C++1y allows all of these. We don't allow them as extensions in C++11,
1859 // because they don't make sense without variable mutation.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001860 if (!SemaRef.getLangOpts().CPlusPlus14)
Richard Smithd9f663b2013-04-22 15:31:51 +00001861 break;
1862 if (!Cxx1yLoc.isValid())
1863 Cxx1yLoc = S->getLocStart();
Benjamin Kramer642f1732015-07-02 21:03:14 +00001864 for (Stmt *SubStmt : S->children())
1865 if (SubStmt &&
1866 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001867 Cxx1yLoc))
1868 return false;
1869 return true;
1870
1871 case Stmt::SwitchStmtClass:
1872 case Stmt::CaseStmtClass:
1873 case Stmt::DefaultStmtClass:
1874 case Stmt::BreakStmtClass:
1875 // C++1y allows switch-statements, and since they don't need variable
1876 // mutation, we can reasonably allow them in C++11 as an extension.
1877 if (!Cxx1yLoc.isValid())
1878 Cxx1yLoc = S->getLocStart();
Benjamin Kramer642f1732015-07-02 21:03:14 +00001879 for (Stmt *SubStmt : S->children())
1880 if (SubStmt &&
1881 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001882 Cxx1yLoc))
1883 return false;
1884 return true;
1885
1886 default:
1887 if (!isa<Expr>(S))
1888 break;
1889
1890 // C++1y allows expression-statements.
1891 if (!Cxx1yLoc.isValid())
1892 Cxx1yLoc = S->getLocStart();
1893 return true;
1894 }
1895
1896 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1897 << isa<CXXConstructorDecl>(Dcl);
1898 return false;
1899}
1900
Richard Smitheb3c10c2011-10-01 02:31:28 +00001901/// Check the body for the given constexpr function declaration only contains
1902/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1903///
1904/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001905bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001906 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001907 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001908 // The definition of a constexpr function shall satisfy the following
1909 // constraints: [...]
1910 // - its function-body shall be = delete, = default, or a
1911 // compound-statement
1912 //
Richard Smith74388b42012-02-04 00:33:54 +00001913 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001914 // In the definition of a constexpr constructor, [...]
1915 // - its function-body shall not be a function-try-block;
1916 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1917 << isa<CXXConstructorDecl>(Dcl);
1918 return false;
1919 }
1920
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001921 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001922
1923 // - its function-body shall be [...] a compound-statement that contains only
1924 // [... list of cases ...]
1925 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1926 SourceLocation Cxx1yLoc;
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001927 for (auto *BodyIt : CompBody->body()) {
1928 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smithd9f663b2013-04-22 15:31:51 +00001929 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001930 }
1931
Richard Smithd9f663b2013-04-22 15:31:51 +00001932 if (Cxx1yLoc.isValid())
1933 Diag(Cxx1yLoc,
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001934 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001935 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1936 : diag::ext_constexpr_body_invalid_stmt)
1937 << isa<CXXConstructorDecl>(Dcl);
1938
Richard Smitheb3c10c2011-10-01 02:31:28 +00001939 if (const CXXConstructorDecl *Constructor
1940 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1941 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001942 // DR1359:
1943 // - every non-variant non-static data member and base class sub-object
1944 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001945 // DR1460:
1946 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001947 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001948 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001949 if (Constructor->getNumCtorInitializers() == 0 &&
1950 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001951 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1952 return false;
1953 }
Richard Smithf368fb42011-10-10 16:38:04 +00001954 } else if (!Constructor->isDependentContext() &&
1955 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001956 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1957
1958 // Skip detailed checking if we have enough initializers, and we would
1959 // allow at most one initializer per member.
1960 bool AnyAnonStructUnionMembers = false;
1961 unsigned Fields = 0;
1962 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1963 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001964 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001965 AnyAnonStructUnionMembers = true;
1966 break;
1967 }
1968 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001969 // DR1460:
1970 // - if the class is a union-like class, but is not a union, for each of
1971 // its anonymous union members having variant members, exactly one of
1972 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001973 if (AnyAnonStructUnionMembers ||
1974 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1975 // Check initialization of non-static data members. Base classes are
1976 // always initialized so do not need to be checked. Dependent bases
1977 // might not have initializers in the member initializer list.
1978 llvm::SmallSet<Decl*, 16> Inits;
Aaron Ballman0ad78302014-03-13 17:34:31 +00001979 for (const auto *I: Constructor->inits()) {
1980 if (FieldDecl *FD = I->getMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001981 Inits.insert(FD);
Aaron Ballman0ad78302014-03-13 17:34:31 +00001982 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001983 Inits.insert(ID->chain_begin(), ID->chain_end());
1984 }
1985
1986 bool Diagnosed = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001987 for (auto *I : RD->fields())
1988 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001989 if (Diagnosed)
1990 return false;
1991 }
1992 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001993 } else {
1994 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001995 // C++1y doesn't require constexpr functions to contain a 'return'
Richard Smith06ffb452014-04-22 23:14:23 +00001996 // statement. We still do, unless the return type might be void, because
Richard Smithd9f663b2013-04-22 15:31:51 +00001997 // otherwise if there's no return statement, the function cannot
1998 // be used in a core constant expression.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001999 bool OK = getLangOpts().CPlusPlus14 &&
Richard Smith06ffb452014-04-22 23:14:23 +00002000 (Dcl->getReturnType()->isVoidType() ||
2001 Dcl->getReturnType()->isDependentType());
Richard Smithd9f663b2013-04-22 15:31:51 +00002002 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00002003 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2004 : diag::err_constexpr_body_no_return);
Richard Smithd35cb052015-08-28 22:33:53 +00002005 if (!OK)
2006 return false;
2007 } else if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00002008 Diag(ReturnStmts.back(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002009 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00002010 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2011 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00002012 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2013 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00002014 }
2015 }
2016
Richard Smith74388b42012-02-04 00:33:54 +00002017 // C++11 [dcl.constexpr]p5:
2018 // if no function argument values exist such that the function invocation
2019 // substitution would produce a constant expression, the program is
2020 // ill-formed; no diagnostic required.
2021 // C++11 [dcl.constexpr]p3:
2022 // - every constructor call and implicit conversion used in initializing the
2023 // return value shall be one of those allowed in a constant expression.
2024 // C++11 [dcl.constexpr]p4:
2025 // - every constructor involved in initializing non-static data members and
2026 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002027 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00002028 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00002029 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00002030 << isa<CXXConstructorDecl>(Dcl);
2031 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2032 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00002033 // Don't return false here: we allow this for compatibility in
2034 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00002035 }
2036
Richard Smitheb3c10c2011-10-01 02:31:28 +00002037 return true;
2038}
2039
Douglas Gregor61956c42008-10-31 09:07:45 +00002040/// isCurrentClassName - Determine whether the identifier II is the
2041/// name of the class type currently being defined. In the case of
2042/// nested classes, this will only return true if II is the name of
2043/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00002044bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
2045 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002046 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002047
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00002048 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00002049 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00002050 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00002051 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2052 } else
2053 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2054
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00002055 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00002056 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002057 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00002058}
2059
Richard Smithfb8b7b92013-10-15 00:00:26 +00002060/// \brief Determine whether the identifier II is a typo for the name of
2061/// the class type currently being defined. If so, update it to the identifier
2062/// that should have been used.
2063bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2064 assert(getLangOpts().CPlusPlus && "No class names in C!");
2065
2066 if (!getLangOpts().SpellChecking)
2067 return false;
2068
2069 CXXRecordDecl *CurDecl;
2070 if (SS && SS->isSet() && !SS->isInvalid()) {
2071 DeclContext *DC = computeDeclContext(*SS, true);
2072 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2073 } else
2074 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2075
2076 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2077 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2078 < II->getLength()) {
2079 II = CurDecl->getIdentifier();
2080 return true;
2081 }
2082
2083 return false;
2084}
2085
Douglas Gregordc974572012-11-10 07:24:09 +00002086/// \brief Determine whether the given class is a base class of the given
2087/// class, including looking at dependent bases.
2088static bool findCircularInheritance(const CXXRecordDecl *Class,
2089 const CXXRecordDecl *Current) {
2090 SmallVector<const CXXRecordDecl*, 8> Queue;
2091
2092 Class = Class->getCanonicalDecl();
2093 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002094 for (const auto &I : Current->bases()) {
2095 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregordc974572012-11-10 07:24:09 +00002096 if (!Base)
2097 continue;
2098
2099 Base = Base->getDefinition();
2100 if (!Base)
2101 continue;
2102
2103 if (Base->getCanonicalDecl() == Class)
2104 return true;
2105
2106 Queue.push_back(Base);
2107 }
2108
2109 if (Queue.empty())
2110 return false;
2111
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002112 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00002113 }
2114
2115 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00002116}
2117
Mike Stump11289f42009-09-09 15:08:12 +00002118/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00002119///
2120/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2121/// and returns NULL otherwise.
2122CXXBaseSpecifier *
2123Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2124 SourceRange SpecifierRange,
2125 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00002126 TypeSourceInfo *TInfo,
2127 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00002128 QualType BaseType = TInfo->getType();
2129
Douglas Gregor463421d2009-03-03 04:44:36 +00002130 // C++ [class.union]p1:
2131 // A union shall not have base classes.
2132 if (Class->isUnion()) {
2133 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2134 << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00002135 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00002136 }
2137
Douglas Gregor752a5952011-01-03 22:36:02 +00002138 if (EllipsisLoc.isValid() &&
2139 !TInfo->getType()->containsUnexpandedParameterPack()) {
2140 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2141 << TInfo->getTypeLoc().getSourceRange();
2142 EllipsisLoc = SourceLocation();
2143 }
Douglas Gregor62004702012-11-10 01:18:17 +00002144
2145 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2146
2147 if (BaseType->isDependentType()) {
2148 // Make sure that we don't have circular inheritance among our dependent
2149 // bases. For non-dependent bases, the check for completeness below handles
2150 // this.
2151 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2152 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2153 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00002154 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00002155 Diag(BaseLoc, diag::err_circular_inheritance)
2156 << BaseType << Context.getTypeDeclType(Class);
2157
2158 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2159 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2160 << BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002161
2162 return nullptr;
Douglas Gregor62004702012-11-10 01:18:17 +00002163 }
2164 }
2165
Mike Stump11289f42009-09-09 15:08:12 +00002166 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00002167 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00002168 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00002169 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002170
2171 // Base specifiers must be record types.
2172 if (!BaseType->isRecordType()) {
2173 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00002174 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00002175 }
2176
2177 // C++ [class.union]p1:
2178 // A union shall not be used as a base class.
2179 if (BaseType->isUnionType()) {
2180 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00002181 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00002182 }
2183
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00002184 // For the MS ABI, propagate DLL attributes to base class templates.
2185 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2186 if (Attr *ClassAttr = getDLLAttr(Class)) {
2187 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2188 BaseType->getAsCXXRecordDecl())) {
Hans Wennborgfce87ca2015-06-09 00:39:09 +00002189 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2190 BaseLoc);
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00002191 }
2192 }
2193 }
2194
Douglas Gregor463421d2009-03-03 04:44:36 +00002195 // C++ [class.derived]p2:
2196 // The class-name in a base-specifier shall not be an incompletely
2197 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00002198 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002199 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00002200 Class->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00002201 return nullptr;
John McCall3696dcb2010-08-17 07:23:57 +00002202 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002203
Eli Friedmanc96d4962009-08-15 21:55:26 +00002204 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002205 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00002206 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002207 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00002208 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00002209 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00002210 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00002211
David Majnemer9b1754d2013-11-02 12:00:36 +00002212 // A class which contains a flexible array member is not suitable for use as a
2213 // base class:
2214 // - If the layout determines that a base comes before another base,
2215 // the flexible array member would index into the subsequent base.
2216 // - If the layout determines that base comes before the derived class,
2217 // the flexible array member would index into the derived class.
2218 if (CXXBaseDecl->hasFlexibleArrayMember()) {
2219 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2220 << CXXBaseDecl->getDeclName();
Craig Topperc3ec1492014-05-26 06:22:03 +00002221 return nullptr;
David Majnemer9b1754d2013-11-02 12:00:36 +00002222 }
2223
Anders Carlsson65c76d32011-03-25 14:55:14 +00002224 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00002225 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00002226 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00002227 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00002228 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00002229 << CXXBaseDecl->getDeclName()
2230 << FA->isSpelledAsSealed();
Alp Toker2afa8782014-05-28 12:20:14 +00002231 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2232 << CXXBaseDecl->getDeclName() << FA->getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00002233 return nullptr;
Anders Carlssonfc1eef42011-01-22 17:51:53 +00002234 }
2235
John McCall3696dcb2010-08-17 07:23:57 +00002236 if (BaseDecl->isInvalidDecl())
2237 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00002238
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00002239 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00002240 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00002241 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00002242 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00002243}
2244
Douglas Gregor556877c2008-04-13 21:30:24 +00002245/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2246/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00002247/// example:
2248/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00002249/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00002250BaseResult
John McCall48871652010-08-21 09:40:31 +00002251Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00002252 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00002253 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00002254 ParsedType basetype, SourceLocation BaseLoc,
2255 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002256 if (!classdecl)
2257 return true;
2258
Douglas Gregorc40290e2009-03-09 23:48:35 +00002259 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00002260 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00002261 if (!Class)
2262 return true;
2263
David Majnemer5ef4fe72014-06-13 06:43:46 +00002264 // We haven't yet attached the base specifiers.
2265 Class->setIsParsingBaseSpecifiers();
2266
Richard Smith4c96e992013-02-19 23:47:15 +00002267 // We do not support any C++11 attributes on base-specifiers yet.
2268 // Diagnose any attributes we see.
2269 if (!Attributes.empty()) {
2270 for (AttributeList *Attr = Attributes.getList(); Attr;
2271 Attr = Attr->getNext()) {
2272 if (Attr->isInvalid() ||
2273 Attr->getKind() == AttributeList::IgnoredAttribute)
2274 continue;
2275 Diag(Attr->getLoc(),
2276 Attr->getKind() == AttributeList::UnknownAttribute
2277 ? diag::warn_unknown_attribute_ignored
2278 : diag::err_base_specifier_attribute)
2279 << Attr->getName();
2280 }
2281 }
2282
Craig Topperc3ec1492014-05-26 06:22:03 +00002283 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00002284 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00002285
Douglas Gregor752a5952011-01-03 22:36:02 +00002286 if (EllipsisLoc.isInvalid() &&
2287 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00002288 UPPC_BaseType))
2289 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00002290
Douglas Gregor463421d2009-03-03 04:44:36 +00002291 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00002292 Virtual, Access, TInfo,
2293 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00002294 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002295 else
2296 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002297
Douglas Gregor463421d2009-03-03 04:44:36 +00002298 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00002299}
Douglas Gregor556877c2008-04-13 21:30:24 +00002300
Nathan Sidwell44b21742015-01-19 01:44:02 +00002301/// Use small set to collect indirect bases. As this is only used
2302/// locally, there's no need to abstract the small size parameter.
2303typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2304
2305/// \brief Recursively add the bases of Type. Don't add Type itself.
2306static void
2307NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2308 const QualType &Type)
2309{
2310 // Even though the incoming type is a base, it might not be
2311 // a class -- it could be a template parm, for instance.
2312 if (auto Rec = Type->getAs<RecordType>()) {
2313 auto Decl = Rec->getAsCXXRecordDecl();
2314
2315 // Iterate over its bases.
2316 for (const auto &BaseSpec : Decl->bases()) {
2317 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2318 .getUnqualifiedType();
2319 if (Set.insert(Base).second)
2320 // If we've not already seen it, recurse.
2321 NoteIndirectBases(Context, Set, Base);
2322 }
2323 }
2324}
2325
Douglas Gregor463421d2009-03-03 04:44:36 +00002326/// \brief Performs the actual work of attaching the given base class
2327/// specifiers to a C++ class.
Craig Topperaa700cb2015-12-27 21:55:19 +00002328bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2329 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2330 if (Bases.empty())
Douglas Gregor463421d2009-03-03 04:44:36 +00002331 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00002332
2333 // Used to keep track of which base types we have already seen, so
2334 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00002335 // that the key is always the unqualified canonical type of the base
2336 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00002337 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2338
Nathan Sidwell44b21742015-01-19 01:44:02 +00002339 // Used to track indirect bases so we can see if a direct base is
2340 // ambiguous.
2341 IndirectBaseSet IndirectBaseTypes;
2342
Douglas Gregor29a92472008-10-22 17:49:05 +00002343 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00002344 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00002345 bool Invalid = false;
Craig Topperaa700cb2015-12-27 21:55:19 +00002346 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00002347 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00002348 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002349 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00002350
2351 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2352 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00002353 // C++ [class.mi]p3:
2354 // A class shall not be specified as a direct base class of a
2355 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002356 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002357 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00002358 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00002359 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00002360
2361 // Delete the duplicate base class specifier; we're going to
2362 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00002363 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00002364
2365 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00002366 } else {
2367 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00002368 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00002369 Bases[NumGoodBases++] = Bases[idx];
Nathan Sidwell44b21742015-01-19 01:44:02 +00002370
2371 // Note this base's direct & indirect bases, if there could be ambiguity.
Craig Topperaa700cb2015-12-27 21:55:19 +00002372 if (Bases.size() > 1)
Nathan Sidwell44b21742015-01-19 01:44:02 +00002373 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2374
John McCalldb632ac2012-09-25 07:32:39 +00002375 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2376 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2377 if (Class->isInterface() &&
2378 (!RD->isInterface() ||
2379 KnownBase->getAccessSpecifier() != AS_public)) {
2380 // The Microsoft extension __interface does not permit bases that
2381 // are not themselves public interfaces.
2382 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
2383 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
2384 << RD->getSourceRange();
2385 Invalid = true;
2386 }
2387 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00002388 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00002389 }
Douglas Gregor29a92472008-10-22 17:49:05 +00002390 }
2391 }
2392
2393 // Attach the remaining base class specifiers to the derived class.
Craig Topperaa700cb2015-12-27 21:55:19 +00002394 Class->setBases(Bases.data(), NumGoodBases);
Nathan Sidwell44b21742015-01-19 01:44:02 +00002395
2396 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2397 // Check whether this direct base is inaccessible due to ambiguity.
2398 QualType BaseType = Bases[idx]->getType();
2399 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2400 .getUnqualifiedType();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00002401
Nathan Sidwell44b21742015-01-19 01:44:02 +00002402 if (IndirectBaseTypes.count(CanonicalBase)) {
2403 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2404 /*DetectVirtual=*/true);
2405 bool found
2406 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2407 assert(found);
NAKAMURA Takumi6a1565c2015-01-19 09:49:59 +00002408 (void)found;
Nathan Sidwell44b21742015-01-19 01:44:02 +00002409
2410 if (Paths.isAmbiguous(CanonicalBase))
2411 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
2412 << BaseType << getAmbiguousPathsDisplayString(Paths)
2413 << Bases[idx]->getSourceRange();
2414 else
2415 assert(Bases[idx]->isVirtual());
2416 }
2417
2418 // Delete the base class specifier, since its data has been copied
2419 // into the CXXRecordDecl.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00002420 Context.Deallocate(Bases[idx]);
Nathan Sidwell44b21742015-01-19 01:44:02 +00002421 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002422
2423 return Invalid;
2424}
2425
2426/// ActOnBaseSpecifiers - Attach the given base specifiers to the
2427/// class, after checking whether there are any duplicate base
2428/// classes.
Craig Topperaa700cb2015-12-27 21:55:19 +00002429void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2430 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2431 if (!ClassDecl || Bases.empty())
Douglas Gregor463421d2009-03-03 04:44:36 +00002432 return;
2433
2434 AdjustDeclIfTemplate(ClassDecl);
Craig Topperaa700cb2015-12-27 21:55:19 +00002435 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
Douglas Gregor556877c2008-04-13 21:30:24 +00002436}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002437
Douglas Gregor36d1b142009-10-06 17:59:45 +00002438/// \brief Determine whether the type \p Derived is a C++ class that is
2439/// derived from the type \p Base.
Richard Smith0f59cb32015-12-18 21:45:41 +00002440bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002441 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002442 return false;
Richard Smith0f59cb32015-12-18 21:45:41 +00002443
Douglas Gregor45bb4832013-03-26 23:36:30 +00002444 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00002445 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002446 return false;
2447
Douglas Gregor45bb4832013-03-26 23:36:30 +00002448 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00002449 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002450 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00002451
2452 // If either the base or the derived type is invalid, don't try to
2453 // check whether one is derived from the other.
2454 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2455 return false;
2456
Richard Smithdb0ac552015-12-18 22:40:25 +00002457 // FIXME: In a modules build, do we need the entire path to be visible for us
2458 // to be able to use the inheritance relationship?
2459 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2460 return false;
2461
Richard Smith0f59cb32015-12-18 21:45:41 +00002462 return DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00002463}
2464
2465/// \brief Determine whether the type \p Derived is a C++ class that is
2466/// derived from the type \p Base.
Richard Smith0f59cb32015-12-18 21:45:41 +00002467bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2468 CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002469 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002470 return false;
2471
Douglas Gregor45bb4832013-03-26 23:36:30 +00002472 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00002473 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002474 return false;
2475
Douglas Gregor45bb4832013-03-26 23:36:30 +00002476 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00002477 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002478 return false;
2479
Richard Smithdb0ac552015-12-18 22:40:25 +00002480 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2481 return false;
2482
Douglas Gregor36d1b142009-10-06 17:59:45 +00002483 return DerivedRD->isDerivedFrom(BaseRD, Paths);
2484}
2485
Anders Carlssona70cff62010-04-24 19:06:50 +00002486void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00002487 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00002488 assert(BasePathArray.empty() && "Base path array must be empty!");
2489 assert(Paths.isRecordingPaths() && "Must record paths!");
2490
2491 const CXXBasePath &Path = Paths.front();
2492
2493 // We first go backward and check if we have a virtual base.
2494 // FIXME: It would be better if CXXBasePath had the base specifier for
2495 // the nearest virtual base.
2496 unsigned Start = 0;
2497 for (unsigned I = Path.size(); I != 0; --I) {
2498 if (Path[I - 1].Base->isVirtual()) {
2499 Start = I - 1;
2500 break;
2501 }
2502 }
2503
2504 // Now add all bases.
2505 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00002506 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00002507}
2508
Douglas Gregor36d1b142009-10-06 17:59:45 +00002509/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2510/// conversion (where Derived and Base are class types) is
2511/// well-formed, meaning that the conversion is unambiguous (and
2512/// that all of the base classes are accessible). Returns true
2513/// and emits a diagnostic if the code is ill-formed, returns false
2514/// otherwise. Loc is the location where this routine should point to
2515/// if there is an error, and Range is the source range to highlight
2516/// if there is an error.
George Burgess IV60bc9722016-01-13 23:36:34 +00002517///
2518/// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2519/// diagnostic for the respective type of error will be suppressed, but the
2520/// check for ill-formed code will still be performed.
Douglas Gregor36d1b142009-10-06 17:59:45 +00002521bool
2522Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00002523 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002524 unsigned AmbigiousBaseConvID,
2525 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00002526 DeclarationName Name,
George Burgess IV60bc9722016-01-13 23:36:34 +00002527 CXXCastPath *BasePath,
2528 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00002529 // First, determine whether the path from Derived to Base is
2530 // ambiguous. This is slightly more expensive than checking whether
2531 // the Derived to Base conversion exists, because here we need to
2532 // explore multiple paths to determine if there is an ambiguity.
2533 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2534 /*DetectVirtual=*/false);
Richard Smith0f59cb32015-12-18 21:45:41 +00002535 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
Douglas Gregor36d1b142009-10-06 17:59:45 +00002536 assert(DerivationOkay &&
2537 "Can only be used with a derived-to-base conversion");
2538 (void)DerivationOkay;
2539
2540 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
George Burgess IV60bc9722016-01-13 23:36:34 +00002541 if (!IgnoreAccess) {
Anders Carlssona70cff62010-04-24 19:06:50 +00002542 // Check that the base class can be accessed.
2543 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
2544 InaccessibleBaseID)) {
2545 case AR_inaccessible:
2546 return true;
2547 case AR_accessible:
2548 case AR_dependent:
2549 case AR_delayed:
2550 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00002551 }
John McCall5b0829a2010-02-10 09:31:12 +00002552 }
Anders Carlssona70cff62010-04-24 19:06:50 +00002553
2554 // Build a base path if necessary.
2555 if (BasePath)
2556 BuildBasePathArray(Paths, *BasePath);
2557 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00002558 }
2559
David Majnemer626032f2013-06-22 06:43:58 +00002560 if (AmbigiousBaseConvID) {
2561 // We know that the derived-to-base conversion is ambiguous, and
2562 // we're going to produce a diagnostic. Perform the derived-to-base
2563 // search just one more time to compute all of the possible paths so
2564 // that we can print them out. This is more expensive than any of
2565 // the previous derived-to-base checks we've done, but at this point
2566 // performance isn't as much of an issue.
2567 Paths.clear();
2568 Paths.setRecordingPaths(true);
Richard Smith0f59cb32015-12-18 21:45:41 +00002569 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
David Majnemer626032f2013-06-22 06:43:58 +00002570 assert(StillOkay && "Can only be used with a derived-to-base conversion");
2571 (void)StillOkay;
2572
2573 // Build up a textual representation of the ambiguous paths, e.g.,
2574 // D -> B -> A, that will be used to illustrate the ambiguous
2575 // conversions in the diagnostic. We only print one of the paths
2576 // to each base class subobject.
2577 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2578
2579 Diag(Loc, AmbigiousBaseConvID)
2580 << Derived << Base << PathDisplayStr << Range << Name;
2581 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00002582 return true;
2583}
2584
2585bool
2586Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00002587 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00002588 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002589 bool IgnoreAccess) {
George Burgess IV60bc9722016-01-13 23:36:34 +00002590 return CheckDerivedToBaseConversion(
2591 Derived, Base, diag::err_upcast_to_inaccessible_base,
2592 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2593 BasePath, IgnoreAccess);
Douglas Gregor36d1b142009-10-06 17:59:45 +00002594}
2595
2596
2597/// @brief Builds a string representing ambiguous paths from a
2598/// specific derived class to different subobjects of the same base
2599/// class.
2600///
2601/// This function builds a string that can be used in error messages
2602/// to show the different paths that one can take through the
2603/// inheritance hierarchy to go from the derived class to different
2604/// subobjects of a base class. The result looks something like this:
2605/// @code
2606/// struct D -> struct B -> struct A
2607/// struct D -> struct C -> struct A
2608/// @endcode
2609std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2610 std::string PathDisplayStr;
2611 std::set<unsigned> DisplayedPaths;
2612 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2613 Path != Paths.end(); ++Path) {
2614 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2615 // We haven't displayed a path to this particular base
2616 // class subobject yet.
2617 PathDisplayStr += "\n ";
2618 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2619 for (CXXBasePath::const_iterator Element = Path->begin();
2620 Element != Path->end(); ++Element)
2621 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2622 }
2623 }
2624
2625 return PathDisplayStr;
2626}
2627
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002628//===----------------------------------------------------------------------===//
2629// C++ class member Handling
2630//===----------------------------------------------------------------------===//
2631
Abramo Bagnarad7340582010-06-05 05:09:32 +00002632/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002633bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
2634 SourceLocation ASLoc,
2635 SourceLocation ColonLoc,
2636 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00002637 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00002638 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00002639 ASLoc, ColonLoc);
2640 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002641 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00002642}
2643
Richard Smith18f07db2012-08-06 03:25:17 +00002644/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002645void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00002646 if (D->isInvalidDecl())
2647 return;
2648
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002649 // We only care about "override" and "final" declarations.
2650 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2651 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00002652
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002653 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00002654
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002655 // We can't check dependent instance methods.
2656 if (MD && MD->isInstance() &&
2657 (MD->getParent()->hasAnyDependentBases() ||
2658 MD->getType()->isDependentType()))
2659 return;
2660
2661 if (MD && !MD->isVirtual()) {
2662 // If we have a non-virtual method, check if if hides a virtual method.
2663 // (In that case, it's most likely the method has the wrong type.)
2664 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2665 FindHiddenVirtualMethods(MD, OverloadedMethods);
2666
2667 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00002668 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2669 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002670 diag::override_keyword_hides_virtual_member_function)
2671 << "override" << (OverloadedMethods.size() > 1);
2672 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00002673 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002674 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00002675 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2676 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00002677 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002678 NoteHiddenVirtualMethods(MD, OverloadedMethods);
2679 MD->setInvalidDecl();
2680 return;
2681 }
2682 // Fall through into the general case diagnostic.
2683 // FIXME: We might want to attempt typo correction here.
2684 }
2685
2686 if (!MD || !MD->isVirtual()) {
2687 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2688 Diag(OA->getLocation(),
2689 diag::override_keyword_only_allowed_on_virtual_member_functions)
2690 << "override" << FixItHint::CreateRemoval(OA->getLocation());
2691 D->dropAttr<OverrideAttr>();
2692 }
2693 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2694 Diag(FA->getLocation(),
2695 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00002696 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2697 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002698 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00002699 }
Anders Carlssonfd835532011-01-20 05:57:14 +00002700 return;
2701 }
Richard Smith18f07db2012-08-06 03:25:17 +00002702
Richard Smith18f07db2012-08-06 03:25:17 +00002703 // C++11 [class.virtual]p5:
David Blaikie1cbb9712014-11-14 19:09:44 +00002704 // If a function is marked with the virt-specifier override and
Richard Smith18f07db2012-08-06 03:25:17 +00002705 // does not override a member function of a base class, the program is
2706 // ill-formed.
2707 bool HasOverriddenMethods =
2708 MD->begin_overridden_methods() != MD->end_overridden_methods();
2709 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2710 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2711 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00002712}
2713
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00002714void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2715 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2716 return;
2717 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2718 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
2719 isa<CXXDestructorDecl>(MD))
2720 return;
2721
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00002722 SourceLocation Loc = MD->getLocation();
2723 SourceLocation SpellingLoc = Loc;
2724 if (getSourceManager().isMacroArgExpansion(Loc))
2725 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
2726 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2727 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
Fariborz Jahanian6e213382014-10-31 19:56:27 +00002728 return;
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00002729
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00002730 if (MD->size_overridden_methods() > 0) {
2731 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
2732 << MD->getDeclName();
2733 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2734 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2735 }
2736}
2737
Richard Smith18f07db2012-08-06 03:25:17 +00002738/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00002739/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00002740/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00002741bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2742 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00002743 FinalAttr *FA = Old->getAttr<FinalAttr>();
2744 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00002745 return false;
2746
2747 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00002748 << New->getDeclName()
2749 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00002750 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2751 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00002752}
2753
Daniel Jasper0baec5492012-06-06 08:32:04 +00002754static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00002755 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2756 // FIXME: Destruction of ObjC lifetime types has side-effects.
2757 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2758 return !RD->isCompleteDefinition() ||
2759 !RD->hasTrivialDefaultConstructor() ||
2760 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00002761 return false;
2762}
2763
John McCall5e77d762013-04-16 07:28:30 +00002764static AttributeList *getMSPropertyAttr(AttributeList *list) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002765 for (AttributeList *it = list; it != nullptr; it = it->getNext())
John McCall5e77d762013-04-16 07:28:30 +00002766 if (it->isDeclspecPropertyAttribute())
2767 return it;
Craig Topperc3ec1492014-05-26 06:22:03 +00002768 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +00002769}
2770
Saleem Abdulrasoola6ae0602017-02-08 03:30:13 +00002771// Check if there is a field shadowing.
2772void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2773 DeclarationName FieldName,
2774 const CXXRecordDecl *RD) {
2775 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2776 return;
2777
2778 // To record a shadowed field in a base
2779 std::map<CXXRecordDecl*, NamedDecl*> Bases;
2780 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2781 CXXBasePath &Path) {
2782 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2783 // Record an ambiguous path directly
2784 if (Bases.find(Base) != Bases.end())
2785 return true;
2786 for (const auto Field : Base->lookup(FieldName)) {
2787 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2788 Field->getAccess() != AS_private) {
2789 assert(Field->getAccess() != AS_none);
2790 assert(Bases.find(Base) == Bases.end());
2791 Bases[Base] = Field;
2792 return true;
2793 }
2794 }
2795 return false;
2796 };
2797
2798 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2799 /*DetectVirtual=*/true);
2800 if (!RD->lookupInBases(FieldShadowed, Paths))
2801 return;
2802
2803 for (const auto &P : Paths) {
2804 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2805 auto It = Bases.find(Base);
2806 // Skip duplicated bases
2807 if (It == Bases.end())
2808 continue;
2809 auto BaseField = It->second;
2810 assert(BaseField->getAccess() != AS_private);
2811 if (AS_none !=
2812 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2813 Diag(Loc, diag::warn_shadow_field)
2814 << FieldName.getAsString() << RD->getName() << Base->getName();
2815 Diag(BaseField->getLocation(), diag::note_shadow_field);
2816 Bases.erase(It);
2817 }
2818 }
2819}
2820
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002821/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2822/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00002823/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00002824/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2825/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002826NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002827Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00002828 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00002829 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00002830 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002831 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002832 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2833 DeclarationName Name = NameInfo.getName();
2834 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00002835
2836 // For anonymous bitfields, the location should point to the type.
2837 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002838 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00002839
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002840 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002841
John McCallb1cd7da2010-06-04 08:34:12 +00002842 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00002843 assert(!DS.isFriendSpecified());
2844
Richard Smithcfcdf3a2011-06-25 02:28:38 +00002845 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00002846
John McCalldb632ac2012-09-25 07:32:39 +00002847 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2848 // The Microsoft extension __interface only permits public member functions
2849 // and prohibits constructors, destructors, operators, non-public member
2850 // functions, static methods and data members.
2851 unsigned InvalidDecl;
2852 bool ShowDeclName = true;
2853 if (!isFunc)
2854 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2855 else if (AS != AS_public)
2856 InvalidDecl = 2;
2857 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2858 InvalidDecl = 3;
2859 else switch (Name.getNameKind()) {
2860 case DeclarationName::CXXConstructorName:
2861 InvalidDecl = 4;
2862 ShowDeclName = false;
2863 break;
2864
2865 case DeclarationName::CXXDestructorName:
2866 InvalidDecl = 5;
2867 ShowDeclName = false;
2868 break;
2869
2870 case DeclarationName::CXXOperatorName:
2871 case DeclarationName::CXXConversionFunctionName:
2872 InvalidDecl = 6;
2873 break;
2874
2875 default:
2876 InvalidDecl = 0;
2877 break;
2878 }
2879
2880 if (InvalidDecl) {
2881 if (ShowDeclName)
2882 Diag(Loc, diag::err_invalid_member_in_interface)
2883 << (InvalidDecl-1) << Name;
2884 else
2885 Diag(Loc, diag::err_invalid_member_in_interface)
2886 << (InvalidDecl-1) << "";
Craig Topperc3ec1492014-05-26 06:22:03 +00002887 return nullptr;
John McCalldb632ac2012-09-25 07:32:39 +00002888 }
2889 }
2890
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002891 // C++ 9.2p6: A member shall not be declared to have automatic storage
2892 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002893 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2894 // data members and cannot be applied to names declared const or static,
2895 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002896 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00002897 case DeclSpec::SCS_unspecified:
2898 case DeclSpec::SCS_typedef:
2899 case DeclSpec::SCS_static:
2900 break;
2901 case DeclSpec::SCS_mutable:
2902 if (isFunc) {
2903 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00002904
Richard Smithb4a9e862013-04-12 22:46:28 +00002905 // FIXME: It would be nicer if the keyword was ignored only for this
2906 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002907 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00002908 }
2909 break;
2910 default:
2911 Diag(DS.getStorageClassSpecLoc(),
2912 diag::err_storageclass_invalid_for_member);
2913 D.getMutableDeclSpec().ClearStorageClassSpecs();
2914 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002915 }
2916
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002917 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2918 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00002919 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002920
David Blaikie35506f82013-01-30 01:22:18 +00002921 if (DS.isConstexprSpecified() && isInstField) {
2922 SemaDiagnosticBuilder B =
2923 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2924 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2925 if (InitStyle == ICIS_NoInit) {
Richard Smith82dce552014-04-14 21:00:40 +00002926 B << 0 << 0;
2927 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2928 B << FixItHint::CreateRemoval(ConstexprLoc);
2929 else {
2930 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2931 D.getMutableDeclSpec().ClearConstexprSpec();
2932 const char *PrevSpec;
2933 unsigned DiagID;
2934 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2935 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2936 (void)Failed;
2937 assert(!Failed && "Making a constexpr member const shouldn't fail");
2938 }
David Blaikie35506f82013-01-30 01:22:18 +00002939 } else {
2940 B << 1;
2941 const char *PrevSpec;
2942 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00002943 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002944 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2945 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00002946 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00002947 "This is the only DeclSpec that should fail to be applied");
2948 B << 1;
2949 } else {
2950 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2951 isInstField = false;
2952 }
2953 }
2954 }
2955
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002956 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00002957 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00002958 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002959
2960 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00002961 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002962 Diag(Loc, diag::err_bad_variable_name)
2963 << Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002964 return nullptr;
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002965 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002966
Benjamin Kramer365082d2012-05-19 16:34:46 +00002967 IdentifierInfo *II = Name.getAsIdentifierInfo();
2968
Douglas Gregor7c26c042011-09-21 14:40:46 +00002969 // Member field could not be with "template" keyword.
2970 // So TemplateParameterLists should be empty in this case.
2971 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002972 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002973 if (TemplateParams->size()) {
2974 // There is no such thing as a member field template.
2975 Diag(D.getIdentifierLoc(), diag::err_template_member)
2976 << II
2977 << SourceRange(TemplateParams->getTemplateLoc(),
2978 TemplateParams->getRAngleLoc());
2979 } else {
2980 // There is an extraneous 'template<>' for this member.
2981 Diag(TemplateParams->getTemplateLoc(),
2982 diag::err_template_member_noparams)
2983 << II
2984 << SourceRange(TemplateParams->getTemplateLoc(),
2985 TemplateParams->getRAngleLoc());
2986 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002987 return nullptr;
Douglas Gregor7c26c042011-09-21 14:40:46 +00002988 }
2989
Douglas Gregora007d362010-10-13 22:19:53 +00002990 if (SS.isSet() && !SS.isInvalid()) {
2991 // The user provided a superfluous scope specifier inside a class
2992 // definition:
2993 //
2994 // class X {
2995 // int X::member;
2996 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002997 if (DeclContext *DC = computeDeclContext(SS, false))
2998 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002999 else
3000 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3001 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00003002
Douglas Gregora007d362010-10-13 22:19:53 +00003003 SS.clear();
3004 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00003005
John McCall5e77d762013-04-16 07:28:30 +00003006 AttributeList *MSPropertyAttr =
3007 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00003008 if (MSPropertyAttr) {
3009 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3010 BitWidth, InitStyle, AS, MSPropertyAttr);
3011 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00003012 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00003013 isInstField = false;
3014 } else {
3015 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3016 BitWidth, InitStyle, AS);
Richard Smithbdb84f32016-07-22 23:36:59 +00003017 if (!Member)
3018 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00003019 }
Saleem Abdulrasoola6ae0602017-02-08 03:30:13 +00003020
3021 // Check for any possible shadowed member variables
3022 if (const auto *RD = cast<CXXRecordDecl>(CurContext))
3023 CheckShadowInheritedFields(Loc, Name, RD);
3024
Eli Friedmanc37dbf72013-06-28 20:48:34 +00003025 } else {
Eli Friedmanc37dbf72013-06-28 20:48:34 +00003026 Member = HandleDeclarator(S, D, TemplateParameterLists);
3027 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00003028 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00003029
3030 // Non-instance-fields can't have a bitfield.
3031 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00003032 if (Member->isInvalidDecl()) {
3033 // don't emit another diagnostic.
David Majnemer380443a2014-12-28 22:51:45 +00003034 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00003035 // C++ 9.6p3: A bit-field shall not be a static member.
3036 // "static member 'A' cannot be a bit-field"
3037 Diag(Loc, diag::err_static_not_bitfield)
3038 << Name << BitWidth->getSourceRange();
3039 } else if (isa<TypedefDecl>(Member)) {
3040 // "typedef member 'x' cannot be a bit-field"
3041 Diag(Loc, diag::err_typedef_not_bitfield)
3042 << Name << BitWidth->getSourceRange();
3043 } else {
3044 // A function typedef ("typedef int f(); f a;").
3045 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3046 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00003047 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00003048 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00003049 }
Mike Stump11289f42009-09-09 15:08:12 +00003050
Craig Topperc3ec1492014-05-26 06:22:03 +00003051 BitWidth = nullptr;
Chris Lattnerd26760a2009-03-05 23:01:03 +00003052 Member->setInvalidDecl();
3053 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00003054
3055 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00003056
Larisse Voufo39a1e502013-08-06 01:03:05 +00003057 // If we have declared a member function template or static data member
3058 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00003059 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3060 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003061 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3062 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00003063 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003064
Richard Smith18f07db2012-08-06 03:25:17 +00003065 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00003066 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00003067 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00003068 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3069 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00003070
Douglas Gregorf2f08062011-03-08 17:10:18 +00003071 if (VS.getLastLocation().isValid()) {
3072 // Update the end location of a method that has a virt-specifiers.
3073 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3074 MD->setRangeEnd(VS.getLastLocation());
3075 }
Richard Smith18f07db2012-08-06 03:25:17 +00003076
Anders Carlssonc87f8612011-01-20 06:29:02 +00003077 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00003078
Douglas Gregor92751d42008-11-17 22:58:34 +00003079 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003080
Daniel Jasper0baec5492012-06-06 08:32:04 +00003081 if (isInstField) {
3082 FieldDecl *FD = cast<FieldDecl>(Member);
3083 FieldCollector->Add(FD);
3084
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00003085 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
Daniel Jasper0baec5492012-06-06 08:32:04 +00003086 // Remember all explicit private FieldDecls that have a name, no side
3087 // effects and are not part of a dependent type declaration.
3088 if (!FD->isImplicit() && FD->getDeclName() &&
3089 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00003090 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00003091 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00003092 !InitializationHasSideEffects(*FD))
3093 UnusedPrivateFields.insert(FD);
3094 }
3095 }
3096
John McCall48871652010-08-21 09:40:31 +00003097 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003098}
3099
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003100namespace {
3101 class UninitializedFieldVisitor
3102 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3103 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00003104 // List of Decls to generate a warning on. Also remove Decls that become
3105 // initialized.
Craig Topper4dd9b432014-08-17 23:49:53 +00003106 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
Richard Trieu3630c392014-11-21 03:10:30 +00003107 // List of base classes of the record. Classes are removed after their
3108 // initializers.
3109 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
Richard Trieu8d08a272014-08-28 03:23:47 +00003110 // Vector of decls to be removed from the Decl set prior to visiting the
3111 // nodes. These Decls may have been initialized in the prior initializer.
3112 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
Richard Trieu406e65c2013-09-20 03:03:06 +00003113 // If non-null, add a note to the warning pointing back to the constructor.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00003114 const CXXConstructorDecl *Constructor;
Nick Lewycky314a4492014-10-17 22:45:44 +00003115 // Variables to hold state when processing an initializer list. When
Richard Trieufa1d0a72014-10-17 20:56:10 +00003116 // InitList is true, special case initialization of FieldDecls matching
3117 // InitListFieldDecl.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00003118 bool InitList;
3119 FieldDecl *InitListFieldDecl;
Richard Trieufa1d0a72014-10-17 20:56:10 +00003120 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3121
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003122 public:
3123 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00003124 UninitializedFieldVisitor(Sema &S,
Richard Trieu3630c392014-11-21 03:10:30 +00003125 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3126 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3127 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3128 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003129
Richard Trieufa1d0a72014-10-17 20:56:10 +00003130 // Returns true if the use of ME is not an uninitialized use.
3131 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3132 bool CheckReferenceOnly) {
3133 llvm::SmallVector<FieldDecl*, 4> Fields;
3134 bool ReferenceField = false;
3135 while (ME) {
3136 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3137 if (!FD)
3138 return false;
3139 Fields.push_back(FD);
3140 if (FD->getType()->isReferenceType())
3141 ReferenceField = true;
3142 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3143 }
3144
3145 // Binding a reference to an unintialized field is not an
3146 // uninitialized use.
3147 if (CheckReferenceOnly && !ReferenceField)
3148 return true;
3149
3150 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3151 // Discard the first field since it is the field decl that is being
3152 // initialized.
3153 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3154 UsedFieldIndex.push_back((*I)->getFieldIndex());
3155 }
3156
3157 for (auto UsedIter = UsedFieldIndex.begin(),
3158 UsedEnd = UsedFieldIndex.end(),
3159 OrigIter = InitFieldIndex.begin(),
3160 OrigEnd = InitFieldIndex.end();
3161 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3162 if (*UsedIter < *OrigIter)
3163 return true;
3164 if (*UsedIter > *OrigIter)
3165 break;
3166 }
3167
3168 return false;
3169 }
3170
Richard Trieu2d779b92014-10-01 03:44:58 +00003171 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3172 bool AddressOf) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00003173 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3174 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003175
Richard Trieu1bc22c12013-09-13 03:20:53 +00003176 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3177 // or union.
3178 MemberExpr *FieldME = ME;
3179
Richard Trieu2d779b92014-10-01 03:44:58 +00003180 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3181
Richard Trieu1bc22c12013-09-13 03:20:53 +00003182 Expr *Base = ME;
Richard Trieu3630c392014-11-21 03:10:30 +00003183 while (MemberExpr *SubME =
3184 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00003185
Richard Trieufa1d0a72014-10-17 20:56:10 +00003186 if (isa<VarDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00003187 return;
3188
Richard Trieufa1d0a72014-10-17 20:56:10 +00003189 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00003190 if (!FD->isAnonymousStructOrUnion())
Richard Trieufa1d0a72014-10-17 20:56:10 +00003191 FieldME = SubME;
Richard Trieu1bc22c12013-09-13 03:20:53 +00003192
Richard Trieu2d779b92014-10-01 03:44:58 +00003193 if (!FieldME->getType().isPODType(S.Context))
3194 AllPODFields = false;
3195
Richard Trieu3630c392014-11-21 03:10:30 +00003196 Base = SubME->getBase();
Richard Trieu1bc22c12013-09-13 03:20:53 +00003197 }
3198
Richard Trieu3630c392014-11-21 03:10:30 +00003199 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
Richard Trieufd687772013-09-16 20:46:50 +00003200 return;
3201
Richard Trieu2d779b92014-10-01 03:44:58 +00003202 if (AddressOf && AllPODFields)
3203 return;
3204
Richard Trieu406e65c2013-09-20 03:03:06 +00003205 ValueDecl* FoundVD = FieldME->getMemberDecl();
3206
Richard Trieu3630c392014-11-21 03:10:30 +00003207 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3208 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3209 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3210 }
3211
3212 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3213 QualType T = BaseCast->getType();
3214 if (T->isPointerType() &&
3215 BaseClasses.count(T->getPointeeType())) {
3216 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3217 << T->getPointeeType() << FoundVD;
3218 }
3219 }
3220 }
3221
Richard Trieuef64e942013-10-25 00:56:00 +00003222 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00003223 return;
3224
Richard Trieuef64e942013-10-25 00:56:00 +00003225 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00003226
Richard Trieufa1d0a72014-10-17 20:56:10 +00003227 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3228 // Special checking for initializer lists.
3229 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3230 return;
3231 }
3232 } else {
3233 // Prevent double warnings on use of unbounded references.
3234 if (CheckReferenceOnly && !IsReference)
3235 return;
3236 }
Richard Trieuef64e942013-10-25 00:56:00 +00003237
3238 unsigned diag = IsReference
3239 ? diag::warn_reference_field_is_uninit
3240 : diag::warn_field_is_uninit;
3241 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3242 if (Constructor)
3243 S.Diag(Constructor->getLocation(),
3244 diag::note_uninit_in_this_constructor)
3245 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3246
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003247 }
3248
Richard Trieu2d779b92014-10-01 03:44:58 +00003249 void HandleValue(Expr *E, bool AddressOf) {
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003250 E = E->IgnoreParens();
3251
3252 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003253 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3254 AddressOf /*AddressOf*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00003255 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003256 }
3257
3258 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003259 Visit(CO->getCond());
3260 HandleValue(CO->getTrueExpr(), AddressOf);
3261 HandleValue(CO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003262 return;
3263 }
3264
3265 if (BinaryConditionalOperator *BCO =
3266 dyn_cast<BinaryConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003267 Visit(BCO->getCond());
3268 HandleValue(BCO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003269 return;
3270 }
3271
Richard Trieuabf6ec42014-08-27 22:15:10 +00003272 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003273 HandleValue(OVE->getSourceExpr(), AddressOf);
Richard Trieuabf6ec42014-08-27 22:15:10 +00003274 return;
3275 }
3276
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003277 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3278 switch (BO->getOpcode()) {
3279 default:
Richard Trieu2d779b92014-10-01 03:44:58 +00003280 break;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003281 case(BO_PtrMemD):
3282 case(BO_PtrMemI):
Richard Trieu2d779b92014-10-01 03:44:58 +00003283 HandleValue(BO->getLHS(), AddressOf);
3284 Visit(BO->getRHS());
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003285 return;
3286 case(BO_Comma):
Richard Trieu2d779b92014-10-01 03:44:58 +00003287 Visit(BO->getLHS());
3288 HandleValue(BO->getRHS(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003289 return;
3290 }
3291 }
Richard Trieu2d779b92014-10-01 03:44:58 +00003292
3293 Visit(E);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003294 }
3295
Richard Trieufa1d0a72014-10-17 20:56:10 +00003296 void CheckInitListExpr(InitListExpr *ILE) {
3297 InitFieldIndex.push_back(0);
3298 for (auto Child : ILE->children()) {
3299 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3300 CheckInitListExpr(SubList);
3301 } else {
3302 Visit(Child);
3303 }
3304 ++InitFieldIndex.back();
3305 }
3306 InitFieldIndex.pop_back();
3307 }
3308
Richard Trieu8d08a272014-08-28 03:23:47 +00003309 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
Richard Trieu3630c392014-11-21 03:10:30 +00003310 FieldDecl *Field, const Type *BaseClass) {
Richard Trieu8d08a272014-08-28 03:23:47 +00003311 // Remove Decls that may have been initialized in the previous
3312 // initializer.
3313 for (ValueDecl* VD : DeclsToRemove)
3314 Decls.erase(VD);
Richard Trieu8d08a272014-08-28 03:23:47 +00003315 DeclsToRemove.clear();
Richard Trieufa1d0a72014-10-17 20:56:10 +00003316
Richard Trieu8d08a272014-08-28 03:23:47 +00003317 Constructor = FieldConstructor;
Richard Trieufa1d0a72014-10-17 20:56:10 +00003318 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3319
3320 if (ILE && Field) {
3321 InitList = true;
3322 InitListFieldDecl = Field;
3323 InitFieldIndex.clear();
3324 CheckInitListExpr(ILE);
3325 } else {
3326 InitList = false;
3327 Visit(E);
3328 }
3329
Richard Trieu8d08a272014-08-28 03:23:47 +00003330 if (Field)
3331 Decls.erase(Field);
Richard Trieu3630c392014-11-21 03:10:30 +00003332 if (BaseClass)
3333 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
Richard Trieu8d08a272014-08-28 03:23:47 +00003334 }
3335
Richard Trieu1bc22c12013-09-13 03:20:53 +00003336 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00003337 // All uses of unbounded reference fields will warn.
Richard Trieu2d779b92014-10-01 03:44:58 +00003338 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00003339 }
3340
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003341 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003342 if (E->getCastKind() == CK_LValueToRValue) {
3343 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3344 return;
3345 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003346
3347 Inherited::VisitImplicitCastExpr(E);
3348 }
3349
Richard Trieu1bc22c12013-09-13 03:20:53 +00003350 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu4834ad22014-08-12 21:05:04 +00003351 if (E->getConstructor()->isCopyConstructor()) {
3352 Expr *ArgExpr = E->getArg(0);
Richard Trieu2d779b92014-10-01 03:44:58 +00003353 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3354 if (ILE->getNumInits() == 1)
3355 ArgExpr = ILE->getInit(0);
3356 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3357 if (ICE->getCastKind() == CK_NoOp)
Richard Trieu4834ad22014-08-12 21:05:04 +00003358 ArgExpr = ICE->getSubExpr();
Richard Trieu2d779b92014-10-01 03:44:58 +00003359 HandleValue(ArgExpr, false /*AddressOf*/);
3360 return;
Richard Trieu4834ad22014-08-12 21:05:04 +00003361 }
Richard Trieu1bc22c12013-09-13 03:20:53 +00003362 Inherited::VisitCXXConstructExpr(E);
3363 }
3364
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003365 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3366 Expr *Callee = E->getCallee();
Richard Trieu2d779b92014-10-01 03:44:58 +00003367 if (isa<MemberExpr>(Callee)) {
3368 HandleValue(Callee, false /*AddressOf*/);
Richard Trieu46847422014-11-01 00:46:54 +00003369 for (auto Arg : E->arguments())
3370 Visit(Arg);
Richard Trieu2d779b92014-10-01 03:44:58 +00003371 return;
3372 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003373
3374 Inherited::VisitCXXMemberCallExpr(E);
3375 }
Richard Trieu406e65c2013-09-20 03:03:06 +00003376
Richard Trieu11fd0792014-08-26 04:30:55 +00003377 void VisitCallExpr(CallExpr *E) {
3378 // Treat std::move as a use.
3379 if (E->getNumArgs() == 1) {
3380 if (FunctionDecl *FD = E->getDirectCallee()) {
Richard Trieuc321b932014-11-27 01:29:32 +00003381 if (FD->isInStdNamespace() && FD->getIdentifier() &&
3382 FD->getIdentifier()->isStr("move")) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003383 HandleValue(E->getArg(0), false /*AddressOf*/);
3384 return;
Richard Trieu11fd0792014-08-26 04:30:55 +00003385 }
3386 }
3387 }
3388
3389 Inherited::VisitCallExpr(E);
3390 }
3391
Richard Trieud4a01362014-10-31 21:10:22 +00003392 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3393 Expr *Callee = E->getCallee();
3394
3395 if (isa<UnresolvedLookupExpr>(Callee))
3396 return Inherited::VisitCXXOperatorCallExpr(E);
3397
3398 Visit(Callee);
3399 for (auto Arg : E->arguments())
3400 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3401 }
3402
Richard Trieu406e65c2013-09-20 03:03:06 +00003403 void VisitBinaryOperator(BinaryOperator *E) {
3404 // If a field assignment is detected, remove the field from the
3405 // uninitiailized field set.
3406 if (E->getOpcode() == BO_Assign)
3407 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3408 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00003409 if (!FD->getType()->isReferenceType())
Richard Trieu8d08a272014-08-28 03:23:47 +00003410 DeclsToRemove.push_back(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00003411
Richard Trieu52b8b602014-09-25 01:15:40 +00003412 if (E->isCompoundAssignmentOp()) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003413 HandleValue(E->getLHS(), false /*AddressOf*/);
3414 Visit(E->getRHS());
3415 return;
Richard Trieu52b8b602014-09-25 01:15:40 +00003416 }
3417
Richard Trieu406e65c2013-09-20 03:03:06 +00003418 Inherited::VisitBinaryOperator(E);
3419 }
Richard Trieu52b8b602014-09-25 01:15:40 +00003420
3421 void VisitUnaryOperator(UnaryOperator *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003422 if (E->isIncrementDecrementOp()) {
3423 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3424 return;
3425 }
3426 if (E->getOpcode() == UO_AddrOf) {
3427 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3428 HandleValue(ME->getBase(), true /*AddressOf*/);
3429 return;
3430 }
3431 }
Richard Trieu52b8b602014-09-25 01:15:40 +00003432
3433 Inherited::VisitUnaryOperator(E);
3434 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003435 };
Richard Trieuef64e942013-10-25 00:56:00 +00003436
3437 // Diagnose value-uses of fields to initialize themselves, e.g.
3438 // foo(foo)
3439 // where foo is not also a parameter to the constructor.
3440 // Also diagnose across field uninitialized use such as
3441 // x(y), y(x)
3442 // TODO: implement -Wuninitialized and fold this into that framework.
3443 static void DiagnoseUninitializedFields(
3444 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3445
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00003446 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3447 Constructor->getLocation())) {
Richard Trieuef64e942013-10-25 00:56:00 +00003448 return;
3449 }
3450
3451 if (Constructor->isInvalidDecl())
3452 return;
3453
3454 const CXXRecordDecl *RD = Constructor->getParent();
3455
Richard Trieu353a4b42014-10-22 05:21:59 +00003456 if (RD->getDescribedClassTemplate())
Richard Trieu277ace02014-10-22 02:52:00 +00003457 return;
3458
Richard Trieuef64e942013-10-25 00:56:00 +00003459 // Holds fields that are uninitialized.
3460 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3461
3462 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00003463 for (auto *I : RD->decls()) {
3464 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00003465 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00003466 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00003467 UninitializedFields.insert(IFD->getAnonField());
3468 }
3469 }
3470
Richard Trieu3630c392014-11-21 03:10:30 +00003471 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3472 for (auto I : RD->bases())
3473 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3474
3475 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00003476 return;
3477
3478 UninitializedFieldVisitor UninitializedChecker(SemaRef,
Richard Trieu3630c392014-11-21 03:10:30 +00003479 UninitializedFields,
3480 UninitializedBaseClasses);
Richard Trieu8d08a272014-08-28 03:23:47 +00003481
Aaron Ballman0ad78302014-03-13 17:34:31 +00003482 for (const auto *FieldInit : Constructor->inits()) {
Richard Trieu3630c392014-11-21 03:10:30 +00003483 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00003484 break;
3485
Aaron Ballman0ad78302014-03-13 17:34:31 +00003486 Expr *InitExpr = FieldInit->getInit();
Richard Trieu8d08a272014-08-28 03:23:47 +00003487 if (!InitExpr)
3488 continue;
Richard Trieuef64e942013-10-25 00:56:00 +00003489
Richard Trieu8d08a272014-08-28 03:23:47 +00003490 if (CXXDefaultInitExpr *Default =
3491 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3492 InitExpr = Default->getExpr();
3493 if (!InitExpr)
3494 continue;
3495 // In class initializers will point to the constructor.
3496 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
Richard Trieu3630c392014-11-21 03:10:30 +00003497 FieldInit->getAnyMember(),
3498 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00003499 } else {
3500 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
Richard Trieu3630c392014-11-21 03:10:30 +00003501 FieldInit->getAnyMember(),
3502 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00003503 }
Richard Trieuef64e942013-10-25 00:56:00 +00003504 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003505 }
3506} // namespace
3507
Richard Smith74108172014-01-17 03:11:34 +00003508/// \brief Enter a new C++ default initializer scope. After calling this, the
3509/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3510/// parsing or instantiating the initializer failed.
3511void Sema::ActOnStartCXXInClassMemberInitializer() {
3512 // Create a synthetic function scope to represent the call to the constructor
3513 // that notionally surrounds a use of this initializer.
3514 PushFunctionScope();
3515}
3516
3517/// \brief This is invoked after parsing an in-class initializer for a
3518/// non-static C++ class member, and after instantiating an in-class initializer
3519/// in a class template. Such actions are deferred until the class is complete.
3520void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3521 SourceLocation InitLoc,
3522 Expr *InitExpr) {
3523 // Pop the notional constructor scope we created earlier.
Craig Topperc3ec1492014-05-26 06:22:03 +00003524 PopFunctionScopeInfo(nullptr, D);
Richard Smith74108172014-01-17 03:11:34 +00003525
David Majnemer87ff66c2014-12-13 11:34:16 +00003526 FieldDecl *FD = dyn_cast<FieldDecl>(D);
3527 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
Richard Smith2b013182012-06-10 03:12:00 +00003528 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00003529
3530 if (!InitExpr) {
David Majnemer87ff66c2014-12-13 11:34:16 +00003531 D->setInvalidDecl();
3532 if (FD)
3533 FD->removeInClassInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00003534 return;
3535 }
3536
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00003537 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3538 FD->setInvalidDecl();
3539 FD->removeInClassInitializer();
3540 return;
3541 }
3542
Richard Smith938f40b2011-06-11 17:19:42 +00003543 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00003544 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00003545 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00003546 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00003547 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00003548 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003549 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3550 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00003551 if (Init.isInvalid()) {
3552 FD->setInvalidDecl();
3553 return;
3554 }
Richard Smith938f40b2011-06-11 17:19:42 +00003555 }
3556
Richard Smith945f8d32013-01-14 22:39:08 +00003557 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00003558 // The initialization of each base and member constitutes a
3559 // full-expression.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003560 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00003561 if (Init.isInvalid()) {
3562 FD->setInvalidDecl();
3563 return;
3564 }
3565
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003566 InitExpr = Init.get();
Richard Smith938f40b2011-06-11 17:19:42 +00003567
3568 FD->setInClassInitializer(InitExpr);
3569}
3570
Douglas Gregor15e77a22009-12-31 09:10:24 +00003571/// \brief Find the direct and/or virtual base specifiers that
3572/// correspond to the given base type, for use in base initialization
3573/// within a constructor.
3574static bool FindBaseInitializer(Sema &SemaRef,
3575 CXXRecordDecl *ClassDecl,
3576 QualType BaseType,
3577 const CXXBaseSpecifier *&DirectBaseSpec,
3578 const CXXBaseSpecifier *&VirtualBaseSpec) {
3579 // First, check for a direct base class.
Craig Topperc3ec1492014-05-26 06:22:03 +00003580 DirectBaseSpec = nullptr;
Aaron Ballman574705e2014-03-13 15:41:46 +00003581 for (const auto &Base : ClassDecl->bases()) {
3582 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00003583 // We found a direct base of this type. That's what we're
3584 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00003585 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00003586 break;
3587 }
3588 }
3589
3590 // Check for a virtual base class.
3591 // FIXME: We might be able to short-circuit this if we know in advance that
3592 // there are no virtual bases.
Craig Topperc3ec1492014-05-26 06:22:03 +00003593 VirtualBaseSpec = nullptr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00003594 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3595 // We haven't found a base yet; search the class hierarchy for a
3596 // virtual base class.
3597 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3598 /*DetectVirtual=*/false);
Richard Smith0f59cb32015-12-18 21:45:41 +00003599 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3600 SemaRef.Context.getTypeDeclType(ClassDecl),
Douglas Gregor15e77a22009-12-31 09:10:24 +00003601 BaseType, Paths)) {
3602 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3603 Path != Paths.end(); ++Path) {
3604 if (Path->back().Base->isVirtual()) {
3605 VirtualBaseSpec = Path->back().Base;
3606 break;
3607 }
3608 }
3609 }
3610 }
3611
3612 return DirectBaseSpec || VirtualBaseSpec;
3613}
3614
Sebastian Redla74948d2011-09-24 17:48:25 +00003615/// \brief Handle a C++ member initializer using braced-init-list syntax.
3616MemInitResult
3617Sema::ActOnMemInitializer(Decl *ConstructorD,
3618 Scope *S,
3619 CXXScopeSpec &SS,
3620 IdentifierInfo *MemberOrBase,
3621 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00003622 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00003623 SourceLocation IdLoc,
3624 Expr *InitList,
3625 SourceLocation EllipsisLoc) {
3626 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00003627 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00003628 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003629}
3630
3631/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00003632MemInitResult
John McCall48871652010-08-21 09:40:31 +00003633Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00003634 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003635 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00003636 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00003637 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00003638 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00003639 SourceLocation IdLoc,
3640 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00003641 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00003642 SourceLocation RParenLoc,
3643 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003644 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00003645 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003646 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00003647 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003648}
3649
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003650namespace {
3651
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00003652// Callback to only accept typo corrections that can be a valid C++ member
3653// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003654class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003655public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003656 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3657 : ClassDecl(ClassDecl) {}
3658
Craig Toppera798a9d2014-03-02 09:32:10 +00003659 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003660 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3661 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3662 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003663 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003664 }
3665 return false;
3666 }
3667
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003668private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003669 CXXRecordDecl *ClassDecl;
3670};
3671
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003672}
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003673
Sebastian Redla74948d2011-09-24 17:48:25 +00003674/// \brief Handle a C++ member initializer.
3675MemInitResult
3676Sema::BuildMemInitializer(Decl *ConstructorD,
3677 Scope *S,
3678 CXXScopeSpec &SS,
3679 IdentifierInfo *MemberOrBase,
3680 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00003681 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00003682 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00003683 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00003684 SourceLocation EllipsisLoc) {
Kaelyn Takataa15a6dc2014-12-08 22:41:42 +00003685 ExprResult Res = CorrectDelayedTyposInExpr(Init);
3686 if (!Res.isUsable())
3687 return true;
3688 Init = Res.get();
3689
Douglas Gregor71a57182009-06-22 23:20:33 +00003690 if (!ConstructorD)
3691 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003692
Douglas Gregorc8c277a2009-08-24 11:57:43 +00003693 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00003694
3695 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003696 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00003697 if (!Constructor) {
3698 // The user wrote a constructor initializer on a function that is
3699 // not a C++ constructor. Ignore the error for now, because we may
3700 // have more member initializers coming; we'll diagnose it just
3701 // once in ActOnMemInitializers.
3702 return true;
3703 }
3704
3705 CXXRecordDecl *ClassDecl = Constructor->getParent();
3706
3707 // C++ [class.base.init]p2:
3708 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00003709 // constructor's class and, if not found in that scope, are looked
3710 // up in the scope containing the constructor's definition.
3711 // [Note: if the constructor's class contains a member with the
3712 // same name as a direct or virtual base class of the class, a
3713 // mem-initializer-id naming the member or base class and composed
3714 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00003715 // mem-initializer-id for the hidden base class may be specified
3716 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003717 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00003718 // Look for a member, first.
Nico Weberaa0117c2014-11-12 03:44:43 +00003719 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00003720 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00003721 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00003722 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3723 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00003724 if (EllipsisLoc.isValid())
3725 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00003726 << MemberOrBase
3727 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00003728
Sebastian Redla9351792012-02-11 23:51:47 +00003729 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00003730 }
Francois Pichetd583da02010-12-04 09:14:42 +00003731 }
Douglas Gregore8381c02008-11-05 04:29:56 +00003732 }
Douglas Gregore8381c02008-11-05 04:29:56 +00003733 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00003734 QualType BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00003735 TypeSourceInfo *TInfo = nullptr;
John McCallb5a0d312009-12-21 10:41:20 +00003736
3737 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00003738 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00003739 } else if (DS.getTypeSpecType() == TST_decltype) {
3740 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
Richard Smithef2cd8f2017-02-08 20:39:08 +00003741 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3742 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3743 return true;
John McCallb5a0d312009-12-21 10:41:20 +00003744 } else {
3745 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3746 LookupParsedName(R, S, &SS);
3747
3748 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3749 if (!TyD) {
3750 if (R.isAmbiguous()) return true;
3751
John McCallda6841b2010-04-09 19:01:14 +00003752 // We don't want access-control diagnostics here.
3753 R.suppressDiagnostics();
3754
Douglas Gregora3b624a2010-01-19 06:46:48 +00003755 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3756 bool NotUnknownSpecialization = false;
3757 DeclContext *DC = computeDeclContext(SS, false);
3758 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3759 NotUnknownSpecialization = !Record->hasAnyDependentBases();
3760
3761 if (!NotUnknownSpecialization) {
3762 // When the scope specifier can refer to a member of an unknown
3763 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00003764 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3765 SS.getWithLocInContext(Context),
3766 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00003767 if (BaseType.isNull())
3768 return true;
3769
Douglas Gregora3b624a2010-01-19 06:46:48 +00003770 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00003771 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00003772 }
3773 }
3774
Douglas Gregor15e77a22009-12-31 09:10:24 +00003775 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003776 TypoCorrection Corr;
Douglas Gregora3b624a2010-01-19 06:46:48 +00003777 if (R.empty() && BaseType.isNull() &&
Kaelyn Takata89c881b2014-10-27 18:07:29 +00003778 (Corr = CorrectTypo(
3779 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3780 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3781 CTK_ErrorRecovery, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003782 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003783 // We have found a non-static data member with a similar
3784 // name to what was typed; complain and initialize that
3785 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00003786 diagnoseTypo(Corr,
3787 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3788 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00003789 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003790 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00003791 const CXXBaseSpecifier *DirectBaseSpec;
3792 const CXXBaseSpecifier *VirtualBaseSpec;
3793 if (FindBaseInitializer(*this, ClassDecl,
3794 Context.getTypeDeclType(Type),
3795 DirectBaseSpec, VirtualBaseSpec)) {
3796 // We have found a direct or virtual base class with a
3797 // similar name to what was typed; complain and initialize
3798 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00003799 diagnoseTypo(Corr,
3800 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3801 << MemberOrBase << false,
3802 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00003803
Richard Smithf9b15102013-08-17 00:46:16 +00003804 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3805 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003806 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00003807 diag::note_base_class_specified_here)
3808 << BaseSpec->getType()
3809 << BaseSpec->getSourceRange();
3810
Douglas Gregor15e77a22009-12-31 09:10:24 +00003811 TyD = Type;
3812 }
3813 }
3814 }
3815
Douglas Gregora3b624a2010-01-19 06:46:48 +00003816 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00003817 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00003818 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00003819 return true;
3820 }
John McCallb5a0d312009-12-21 10:41:20 +00003821 }
3822
Douglas Gregora3b624a2010-01-19 06:46:48 +00003823 if (BaseType.isNull()) {
3824 BaseType = Context.getTypeDeclType(TyD);
Nico Weber28309182014-11-12 03:52:25 +00003825 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
Richard Smith97047d82015-12-12 02:17:54 +00003826 if (SS.isSet()) {
Aaron Ballman4a979672014-01-03 13:56:08 +00003827 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3828 BaseType);
Richard Smith97047d82015-12-12 02:17:54 +00003829 TInfo = Context.CreateTypeSourceInfo(BaseType);
3830 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3831 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3832 TL.setElaboratedKeywordLoc(SourceLocation());
3833 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3834 }
John McCallb5a0d312009-12-21 10:41:20 +00003835 }
3836 }
Mike Stump11289f42009-09-09 15:08:12 +00003837
John McCallbcd03502009-12-07 02:54:59 +00003838 if (!TInfo)
3839 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003840
Sebastian Redla9351792012-02-11 23:51:47 +00003841 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00003842}
3843
Chandler Carruth599deef2011-09-03 01:14:15 +00003844/// Checks a member initializer expression for cases where reference (or
3845/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00003846static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3847 Expr *Init,
3848 SourceLocation IdLoc) {
3849 QualType MemberTy = Member->getType();
3850
3851 // We only handle pointers and references currently.
3852 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3853 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3854 return;
3855
3856 const bool IsPointer = MemberTy->isPointerType();
3857 if (IsPointer) {
3858 if (const UnaryOperator *Op
3859 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3860 // The only case we're worried about with pointers requires taking the
3861 // address.
3862 if (Op->getOpcode() != UO_AddrOf)
3863 return;
3864
3865 Init = Op->getSubExpr();
3866 } else {
3867 // We only handle address-of expression initializers for pointers.
3868 return;
3869 }
3870 }
3871
Richard Smithe3b28bc2013-06-12 21:51:50 +00003872 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003873 // We only warn when referring to a non-reference parameter declaration.
3874 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3875 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00003876 return;
3877
3878 S.Diag(Init->getExprLoc(),
3879 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3880 : diag::warn_bind_ref_member_to_parameter)
3881 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003882 } else {
3883 // Other initializers are fine.
3884 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00003885 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003886
3887 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3888 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00003889}
3890
John McCallfaf5fb42010-08-26 23:41:50 +00003891MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003892Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00003893 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00003894 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3895 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3896 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00003897 "Member must be a FieldDecl or IndirectFieldDecl");
3898
Sebastian Redla9351792012-02-11 23:51:47 +00003899 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00003900 return true;
3901
Douglas Gregor266bb5f2010-11-05 22:21:31 +00003902 if (Member->isInvalidDecl())
3903 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00003904
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003905 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00003906 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003907 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00003908 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003909 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00003910 } else {
3911 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003912 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003913 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00003914
Sebastian Redla9351792012-02-11 23:51:47 +00003915 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00003916
Sebastian Redla9351792012-02-11 23:51:47 +00003917 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003918 // Can't check initialization for a member of dependent type or when
3919 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00003920 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00003921 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00003922 bool InitList = false;
3923 if (isa<InitListExpr>(Init)) {
3924 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003925 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003926 }
3927
Chandler Carruthd44c3102010-12-06 09:23:57 +00003928 // Initialize the member.
3929 InitializedEntity MemberEntity =
Craig Topperc3ec1492014-05-26 06:22:03 +00003930 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3931 : InitializedEntity::InitializeMember(IndirectMember,
3932 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003933 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003934 InitList ? InitializationKind::CreateDirectList(IdLoc)
3935 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3936 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00003937
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003938 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003939 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3940 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003941 if (MemberInit.isInvalid())
3942 return true;
3943
Richard Smith736a9472013-06-12 20:42:33 +00003944 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3945
Richard Smith945f8d32013-01-14 22:39:08 +00003946 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00003947 // The initialization of each base and member constitutes a
3948 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003949 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003950 if (MemberInit.isInvalid())
3951 return true;
3952
Richard Smithd59b8322012-12-19 01:39:02 +00003953 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003954 }
3955
Chandler Carruthd44c3102010-12-06 09:23:57 +00003956 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00003957 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3958 InitRange.getBegin(), Init,
3959 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003960 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00003961 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3962 InitRange.getBegin(), Init,
3963 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003964 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00003965}
3966
John McCallfaf5fb42010-08-26 23:41:50 +00003967MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003968Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00003969 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003970 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003971 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003972 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003973 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003974 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00003975
Sebastian Redl0501c632012-02-12 16:37:36 +00003976 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003977 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003978 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3979 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003980 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00003981 }
3982
Sebastian Redla9351792012-02-11 23:51:47 +00003983 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00003984 // Initialize the object.
3985 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3986 QualType(ClassDecl->getTypeForDecl(), 0));
3987 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003988 InitList ? InitializationKind::CreateDirectList(NameLoc)
3989 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3990 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003991 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00003992 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Craig Topperc3ec1492014-05-26 06:22:03 +00003993 Args, nullptr);
Alexis Huntc5575cc2011-02-26 19:13:13 +00003994 if (DelegationInit.isInvalid())
3995 return true;
3996
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00003997 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3998 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00003999
Richard Smith945f8d32013-01-14 22:39:08 +00004000 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00004001 // The initialization of each base and member constitutes a
4002 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00004003 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
4004 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00004005 if (DelegationInit.isInvalid())
4006 return true;
4007
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00004008 // If we are in a dependent context, template instantiation will
4009 // perform this type-checking again. Just save the arguments that we
4010 // received in a ParenListExpr.
4011 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4012 // of the information that we have about the base
4013 // initializer. However, deconstructing the ASTs is a dicey process,
4014 // and this approach is far more likely to get the corner cases right.
4015 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004016 DelegationInit = Init;
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00004017
Sebastian Redla9351792012-02-11 23:51:47 +00004018 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004019 DelegationInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00004020 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00004021}
4022
4023MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00004024Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00004025 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00004026 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00004027 SourceLocation BaseLoc
4028 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00004029
Douglas Gregor1c69bf02010-06-16 16:03:14 +00004030 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4031 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4032 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4033
4034 // C++ [class.base.init]p2:
4035 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00004036 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00004037 // of that class, the mem-initializer is ill-formed. A
4038 // mem-initializer-list can initialize a base class using any
4039 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00004040 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00004041
Sebastian Redla9351792012-02-11 23:51:47 +00004042 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00004043 if (EllipsisLoc.isValid()) {
4044 // This is a pack expansion.
4045 if (!BaseType->containsUnexpandedParameterPack()) {
4046 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00004047 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00004048
Douglas Gregor44e7df62011-01-04 00:32:56 +00004049 EllipsisLoc = SourceLocation();
4050 }
4051 } else {
4052 // Check for any unexpanded parameter packs.
4053 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4054 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00004055
Sebastian Redla9351792012-02-11 23:51:47 +00004056 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00004057 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00004058 }
Sebastian Redla74948d2011-09-24 17:48:25 +00004059
Douglas Gregor1c69bf02010-06-16 16:03:14 +00004060 // Check for direct and virtual base classes.
Craig Topperc3ec1492014-05-26 06:22:03 +00004061 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4062 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
Douglas Gregor1c69bf02010-06-16 16:03:14 +00004063 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00004064 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4065 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00004066 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00004067
Douglas Gregor1c69bf02010-06-16 16:03:14 +00004068 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4069 VirtualBaseSpec);
4070
4071 // C++ [base.class.init]p2:
4072 // Unless the mem-initializer-id names a nonstatic data member of the
4073 // constructor's class or a direct or virtual base of that class, the
4074 // mem-initializer is ill-formed.
4075 if (!DirectBaseSpec && !VirtualBaseSpec) {
4076 // If the class has any dependent bases, then it's possible that
4077 // one of those types will resolve to the same type as
4078 // BaseType. Therefore, just treat this as a dependent base
4079 // class initialization. FIXME: Should we try to check the
4080 // initialization anyway? It seems odd.
4081 if (ClassDecl->hasAnyDependentBases())
4082 Dependent = true;
4083 else
4084 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4085 << BaseType << Context.getTypeDeclType(ClassDecl)
4086 << BaseTInfo->getTypeLoc().getLocalSourceRange();
4087 }
4088 }
4089
4090 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00004091 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00004092
Sebastian Redla74948d2011-09-24 17:48:25 +00004093 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4094 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00004095 InitRange.getBegin(), Init,
4096 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00004097 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004098
4099 // C++ [base.class.init]p2:
4100 // If a mem-initializer-id is ambiguous because it designates both
4101 // a direct non-virtual base class and an inherited virtual base
4102 // class, the mem-initializer is ill-formed.
4103 if (DirectBaseSpec && VirtualBaseSpec)
4104 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00004105 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004106
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004107 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004108 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004109 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004110
4111 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00004112 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004113 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00004114 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00004115 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004116 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00004117 }
Sebastian Redl0501c632012-02-12 16:37:36 +00004118
4119 InitializedEntity BaseEntity =
4120 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4121 InitializationKind Kind =
4122 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4123 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4124 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004125 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00004126 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004127 if (BaseInit.isInvalid())
4128 return true;
John McCallacf0ee52010-10-08 02:01:28 +00004129
Richard Smith945f8d32013-01-14 22:39:08 +00004130 // C++11 [class.base.init]p7:
4131 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004132 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00004133 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004134 if (BaseInit.isInvalid())
4135 return true;
4136
4137 // If we are in a dependent context, template instantiation will
4138 // perform this type-checking again. Just save the arguments that we
4139 // received in a ParenListExpr.
4140 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4141 // of the information that we have about the base
4142 // initializer. However, deconstructing the ASTs is a dicey process,
4143 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00004144 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004145 BaseInit = Init;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004146
Alexis Hunt1d792652011-01-08 20:30:50 +00004147 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00004148 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00004149 InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004150 BaseInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00004151 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00004152}
4153
Sebastian Redl22653ba2011-08-30 19:58:05 +00004154// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00004155static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4156 if (T.isNull()) T = E->getType();
4157 QualType TargetType = SemaRef.BuildReferenceType(
4158 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004159 SourceLocation ExprLoc = E->getLocStart();
4160 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4161 TargetType, ExprLoc);
4162
4163 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4164 SourceRange(ExprLoc, ExprLoc),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004165 E->getSourceRange()).get();
Sebastian Redl22653ba2011-08-30 19:58:05 +00004166}
4167
Anders Carlsson1b00e242010-04-23 03:10:23 +00004168/// ImplicitInitializerKind - How an implicit base or member initializer should
4169/// initialize its base or member.
4170enum ImplicitInitializerKind {
4171 IIK_Default,
4172 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00004173 IIK_Move,
4174 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00004175};
4176
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004177static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00004178BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00004179 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00004180 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004181 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00004182 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004183 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00004184 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4185 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004186
John McCalldadc5752010-08-24 06:29:42 +00004187 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00004188
4189 switch (ImplicitInitKind) {
Richard Smith5179eb72016-06-28 19:03:57 +00004190 case IIK_Inherit:
Anders Carlsson1b00e242010-04-23 03:10:23 +00004191 case IIK_Default: {
4192 InitializationKind InitKind
4193 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00004194 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4195 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00004196 break;
4197 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004198
Sebastian Redl22653ba2011-08-30 19:58:05 +00004199 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00004200 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004201 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00004202 ParmVarDecl *Param = Constructor->getParamDecl(0);
4203 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00004204
Anders Carlsson1b00e242010-04-23 03:10:23 +00004205 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00004206 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00004207 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00004208 Constructor->getLocation(), ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00004209 VK_LValue, nullptr);
Sebastian Redl22653ba2011-08-30 19:58:05 +00004210
Eli Friedmanfa0df832012-02-02 03:46:19 +00004211 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4212
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00004213 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00004214 QualType ArgTy =
4215 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4216 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00004217
Sebastian Redl22653ba2011-08-30 19:58:05 +00004218 if (Moving) {
4219 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4220 }
4221
John McCallcf142162010-08-07 06:22:56 +00004222 CXXCastPath BasePath;
4223 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00004224 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4225 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00004226 Moving ? VK_XValue : VK_LValue,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004227 &BasePath).get();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00004228
Anders Carlsson1b00e242010-04-23 03:10:23 +00004229 InitializationKind InitKind
4230 = InitializationKind::CreateDirect(Constructor->getLocation(),
4231 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004232 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4233 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00004234 break;
4235 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00004236 }
John McCallb268a282010-08-23 23:25:46 +00004237
Douglas Gregora40433a2010-12-07 00:41:46 +00004238 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004239 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004240 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004241
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004242 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00004243 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004244 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4245 SourceLocation()),
4246 BaseSpec->isVirtual(),
4247 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004248 BaseInit.getAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004249 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004250 SourceLocation());
4251
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004252 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004253}
4254
Sebastian Redl22653ba2011-08-30 19:58:05 +00004255static bool RefersToRValueRef(Expr *MemRef) {
4256 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4257 return Referenced->getType()->isRValueReferenceType();
4258}
4259
Anders Carlsson3c1db572010-04-23 02:15:47 +00004260static bool
4261BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00004262 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00004263 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00004264 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004265 if (Field->isInvalidDecl())
4266 return true;
4267
Chandler Carruth9c9286b2010-06-29 23:50:44 +00004268 SourceLocation Loc = Constructor->getLocation();
4269
Sebastian Redl22653ba2011-08-30 19:58:05 +00004270 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4271 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00004272 ParmVarDecl *Param = Constructor->getParamDecl(0);
4273 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00004274
4275 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00004276 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
4277 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004278
Anders Carlsson423f5d82010-04-23 16:04:08 +00004279 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00004280 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00004281 SourceLocation(), Param, false,
Craig Topperc3ec1492014-05-26 06:22:03 +00004282 Loc, ParamType, VK_LValue, nullptr);
Douglas Gregor94f9a482010-05-05 05:51:00 +00004283
Eli Friedmanfa0df832012-02-02 03:46:19 +00004284 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4285
Sebastian Redl22653ba2011-08-30 19:58:05 +00004286 if (Moving) {
4287 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4288 }
4289
Douglas Gregor94f9a482010-05-05 05:51:00 +00004290 // Build a reference to this field within the parameter.
4291 CXXScopeSpec SS;
4292 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4293 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00004294 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4295 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00004296 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00004297 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00004298 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00004299 ParamType, Loc,
4300 /*IsArrow=*/false,
4301 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004302 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00004303 /*FirstQualifierInScope=*/nullptr,
Douglas Gregor94f9a482010-05-05 05:51:00 +00004304 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00004305 /*TemplateArgs=*/nullptr,
4306 /*S*/nullptr);
Sebastian Redle9c4e842011-09-04 18:14:28 +00004307 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00004308 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004309
4310 // C++11 [class.copy]p15:
4311 // - if a member m has rvalue reference type T&&, it is direct-initialized
4312 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00004313 if (RefersToRValueRef(CtorArg.get())) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004314 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004315 }
4316
Richard Smith30e304e2016-12-14 00:03:17 +00004317 InitializedEntity Entity =
4318 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4319 /*Implicit*/ true)
4320 : InitializedEntity::InitializeMember(Field, nullptr,
4321 /*Implicit*/ true);
Sebastian Redle9c4e842011-09-04 18:14:28 +00004322
Douglas Gregor94f9a482010-05-05 05:51:00 +00004323 // Direct-initialize to use the copy constructor.
4324 InitializationKind InitKind =
4325 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4326
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004327 Expr *CtorArgE = CtorArg.getAs<Expr>();
Richard Smith30e304e2016-12-14 00:03:17 +00004328 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4329 ExprResult MemberInit =
4330 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00004331 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00004332 if (MemberInit.isInvalid())
4333 return true;
4334
Richard Smith30e304e2016-12-14 00:03:17 +00004335 if (Indirect)
4336 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4337 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4338 else
4339 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4340 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
Anders Carlsson1b00e242010-04-23 03:10:23 +00004341 return false;
4342 }
4343
Richard Smithc2bc61b2013-03-18 21:12:30 +00004344 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4345 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00004346
Anders Carlsson3c1db572010-04-23 02:15:47 +00004347 QualType FieldBaseElementType =
4348 SemaRef.Context.getBaseElementType(Field->getType());
4349
Anders Carlsson3c1db572010-04-23 02:15:47 +00004350 if (FieldBaseElementType->isRecordType()) {
Richard Smith30e304e2016-12-14 00:03:17 +00004351 InitializedEntity InitEntity =
4352 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4353 /*Implicit*/ true)
4354 : InitializedEntity::InitializeMember(Field, nullptr,
4355 /*Implicit*/ true);
Anders Carlsson423f5d82010-04-23 16:04:08 +00004356 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00004357 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00004358
4359 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4360 ExprResult MemberInit =
4361 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00004362
Douglas Gregora40433a2010-12-07 00:41:46 +00004363 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00004364 if (MemberInit.isInvalid())
4365 return true;
4366
Douglas Gregor493627b2011-08-10 15:22:55 +00004367 if (Indirect)
4368 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4369 Indirect, Loc,
4370 Loc,
4371 MemberInit.get(),
4372 Loc);
4373 else
4374 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4375 Field, Loc, Loc,
4376 MemberInit.get(),
4377 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00004378 return false;
4379 }
Anders Carlssondca6be02010-04-23 03:07:47 +00004380
Alexis Hunt8b455182011-05-17 00:19:05 +00004381 if (!Field->getParent()->isUnion()) {
4382 if (FieldBaseElementType->isReferenceType()) {
4383 SemaRef.Diag(Constructor->getLocation(),
4384 diag::err_uninitialized_member_in_ctor)
4385 << (int)Constructor->isImplicit()
4386 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4387 << 0 << Field->getDeclName();
4388 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4389 return true;
4390 }
Anders Carlssondca6be02010-04-23 03:07:47 +00004391
Alexis Hunt8b455182011-05-17 00:19:05 +00004392 if (FieldBaseElementType.isConstQualified()) {
4393 SemaRef.Diag(Constructor->getLocation(),
4394 diag::err_uninitialized_member_in_ctor)
4395 << (int)Constructor->isImplicit()
4396 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4397 << 1 << Field->getDeclName();
4398 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4399 return true;
4400 }
Anders Carlssondca6be02010-04-23 03:07:47 +00004401 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00004402
David Blaikiebbafb8a2012-03-11 07:00:24 +00004403 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00004404 FieldBaseElementType->isObjCRetainableType() &&
4405 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
4406 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00004407 // ARC:
John McCall31168b02011-06-15 23:02:42 +00004408 // Default-initialize Objective-C pointers to NULL.
4409 CXXMemberInit
4410 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4411 Loc, Loc,
4412 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4413 Loc);
4414 return false;
4415 }
4416
Anders Carlsson3c1db572010-04-23 02:15:47 +00004417 // Nothing to initialize.
Craig Topperc3ec1492014-05-26 06:22:03 +00004418 CXXMemberInit = nullptr;
Anders Carlsson3c1db572010-04-23 02:15:47 +00004419 return false;
4420}
John McCallbc83b3f2010-05-20 23:23:51 +00004421
4422namespace {
4423struct BaseAndFieldInfo {
4424 Sema &S;
4425 CXXConstructorDecl *Ctor;
4426 bool AnyErrorsInInits;
4427 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00004428 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004429 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00004430 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00004431
4432 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4433 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004434 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
Richard Smith5179eb72016-06-28 19:03:57 +00004435 if (Ctor->getInheritedConstructor())
4436 IIK = IIK_Inherit;
4437 else if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00004438 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004439 else if (Generated && Ctor->isMoveConstructor())
4440 IIK = IIK_Move;
John McCallbc83b3f2010-05-20 23:23:51 +00004441 else
4442 IIK = IIK_Default;
4443 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00004444
4445 bool isImplicitCopyOrMove() const {
4446 switch (IIK) {
4447 case IIK_Copy:
4448 case IIK_Move:
4449 return true;
4450
4451 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00004452 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00004453 return false;
4454 }
David Blaikiee4d798f2012-01-20 21:50:17 +00004455
4456 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00004457 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00004458
4459 bool addFieldInitializer(CXXCtorInitializer *Init) {
4460 AllToInit.push_back(Init);
4461
4462 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00004463 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00004464 S.UnusedPrivateFields.remove(Init->getAnyMember());
4465
4466 return false;
4467 }
John McCallbc83b3f2010-05-20 23:23:51 +00004468
Richard Smithab44d5b2013-12-10 08:25:00 +00004469 bool isInactiveUnionMember(FieldDecl *Field) {
4470 RecordDecl *Record = Field->getParent();
4471 if (!Record->isUnion())
4472 return false;
4473
Richard Smith8d183852013-12-10 20:56:03 +00004474 if (FieldDecl *Active =
4475 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00004476 return Active != Field->getCanonicalDecl();
4477
4478 // In an implicit copy or move constructor, ignore any in-class initializer.
4479 if (isImplicitCopyOrMove())
4480 return true;
4481
4482 // If there's no explicit initialization, the field is active only if it
4483 // has an in-class initializer...
4484 if (Field->hasInClassInitializer())
4485 return false;
4486 // ... or it's an anonymous struct or union whose class has an in-class
4487 // initializer.
4488 if (!Field->isAnonymousStructOrUnion())
4489 return true;
4490 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4491 return !FieldRD->hasInClassInitializer();
4492 }
4493
4494 /// \brief Determine whether the given field is, or is within, a union member
4495 /// that is inactive (because there was an initializer given for a different
4496 /// member of the union, or because the union was not initialized at all).
4497 bool isWithinInactiveUnionMember(FieldDecl *Field,
4498 IndirectFieldDecl *Indirect) {
4499 if (!Indirect)
4500 return isInactiveUnionMember(Field);
4501
Aaron Ballman29c94602014-03-07 18:36:15 +00004502 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004503 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00004504 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00004505 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00004506 }
4507 return false;
4508 }
4509};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004510}
Richard Smithc94ec842011-09-19 13:34:43 +00004511
Douglas Gregor10f939c2011-11-02 23:04:16 +00004512/// \brief Determine whether the given type is an incomplete or zero-lenfgth
4513/// array type.
4514static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4515 if (T->isIncompleteArrayType())
4516 return true;
4517
4518 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4519 if (!ArrayT->getSize())
4520 return true;
4521
4522 T = ArrayT->getElementType();
4523 }
4524
4525 return false;
4526}
4527
Richard Smith938f40b2011-06-11 17:19:42 +00004528static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00004529 FieldDecl *Field,
Craig Topperc3ec1492014-05-26 06:22:03 +00004530 IndirectFieldDecl *Indirect = nullptr) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00004531 if (Field->isInvalidDecl())
4532 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00004533
Chandler Carruth139e9622010-06-30 02:59:29 +00004534 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smithcd45dbc2014-04-19 03:48:30 +00004535 if (CXXCtorInitializer *Init =
4536 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
Richard Smith0a8cfc72012-08-07 21:30:42 +00004537 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00004538
Richard Smithab44d5b2013-12-10 08:25:00 +00004539 // C++11 [class.base.init]p8:
4540 // if the entity is a non-static data member that has a
4541 // brace-or-equal-initializer and either
4542 // -- the constructor's class is a union and no other variant member of that
4543 // union is designated by a mem-initializer-id or
4544 // -- the constructor's class is not a union, and, if the entity is a member
4545 // of an anonymous union, no other member of that union is designated by
4546 // a mem-initializer-id,
4547 // the entity is initialized as specified in [dcl.init].
4548 //
4549 // We also apply the same rules to handle anonymous structs within anonymous
4550 // unions.
4551 if (Info.isWithinInactiveUnionMember(Field, Indirect))
4552 return false;
4553
Douglas Gregor7db3e952011-11-28 20:03:15 +00004554 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Reid Klecknerd60b82f2014-11-17 23:36:45 +00004555 ExprResult DIE =
4556 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4557 if (DIE.isInvalid())
4558 return true;
Douglas Gregor493627b2011-08-10 15:22:55 +00004559 CXXCtorInitializer *Init;
4560 if (Indirect)
Reid Klecknerd60b82f2014-11-17 23:36:45 +00004561 Init = new (SemaRef.Context)
4562 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4563 SourceLocation(), DIE.get(), SourceLocation());
Douglas Gregor493627b2011-08-10 15:22:55 +00004564 else
Reid Klecknerd60b82f2014-11-17 23:36:45 +00004565 Init = new (SemaRef.Context)
4566 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4567 SourceLocation(), DIE.get(), SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00004568 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00004569 }
4570
Douglas Gregor10f939c2011-11-02 23:04:16 +00004571 // Don't initialize incomplete or zero-length arrays.
4572 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4573 return false;
4574
John McCallbc83b3f2010-05-20 23:23:51 +00004575 // Don't try to build an implicit initializer if there were semantic
4576 // errors in any of the initializers (and therefore we might be
4577 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00004578 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00004579 return false;
4580
Craig Topperc3ec1492014-05-26 06:22:03 +00004581 CXXCtorInitializer *Init = nullptr;
Douglas Gregor493627b2011-08-10 15:22:55 +00004582 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4583 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00004584 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00004585
Richard Smith0a8cfc72012-08-07 21:30:42 +00004586 if (!Init)
4587 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00004588
Richard Smith0a8cfc72012-08-07 21:30:42 +00004589 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00004590}
Alexis Hunt61bc1732011-05-01 07:04:31 +00004591
4592bool
4593Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4594 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00004595 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00004596 Constructor->setNumCtorInitializers(1);
4597 CXXCtorInitializer **initializer =
4598 new (Context) CXXCtorInitializer*[1];
4599 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4600 Constructor->setCtorInitializers(initializer);
4601
Alexis Hunt9d47faf2011-05-03 23:05:34 +00004602 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00004603 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00004604 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4605 }
4606
Alexis Hunte2622992011-05-05 00:05:47 +00004607 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00004608
Richard Trieu8a0c9e62014-09-12 22:47:58 +00004609 DiagnoseUninitializedFields(*this, Constructor);
4610
Alexis Hunt61bc1732011-05-01 07:04:31 +00004611 return false;
4612}
Douglas Gregor493627b2011-08-10 15:22:55 +00004613
David Blaikie3fc2f912013-01-17 05:26:25 +00004614bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4615 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00004616 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004617 // Just store the initializers as written, they will be checked during
4618 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00004619 if (!Initializers.empty()) {
4620 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00004621 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00004622 new (Context) CXXCtorInitializer*[Initializers.size()];
4623 memcpy(baseOrMemberInitializers, Initializers.data(),
4624 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00004625 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00004626 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00004627
4628 // Let template instantiation know whether we had errors.
4629 if (AnyErrors)
4630 Constructor->setInvalidDecl();
4631
Anders Carlssondb0a9652010-04-02 06:26:44 +00004632 return false;
4633 }
4634
John McCallbc83b3f2010-05-20 23:23:51 +00004635 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00004636
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004637 // We need to build the initializer AST according to order of construction
4638 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004639 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00004640 if (!ClassDecl)
4641 return true;
4642
Eli Friedman9cf6b592009-11-09 19:20:36 +00004643 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00004644
David Blaikie3fc2f912013-01-17 05:26:25 +00004645 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004646 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00004647
Anders Carlssondb0a9652010-04-02 06:26:44 +00004648 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00004649 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00004650 else {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004651 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00004652
4653 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00004654 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004655 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00004656 if (FD && FD->getParent()->isUnion())
4657 Info.ActiveUnionMember.insert(std::make_pair(
4658 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4659 }
4660 } else if (FieldDecl *FD = Member->getMember()) {
4661 if (FD->getParent()->isUnion())
4662 Info.ActiveUnionMember.insert(std::make_pair(
4663 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4664 }
4665 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00004666 }
4667
Anders Carlsson43c64af2010-04-21 19:52:01 +00004668 // Keep track of the direct virtual bases.
4669 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00004670 for (auto &I : ClassDecl->bases()) {
4671 if (I.isVirtual())
4672 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00004673 }
4674
Anders Carlssondb0a9652010-04-02 06:26:44 +00004675 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00004676 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004677 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00004678 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00004679 // [class.base.init]p7, per DR257:
4680 // A mem-initializer where the mem-initializer-id names a virtual base
4681 // class is ignored during execution of a constructor of any class that
4682 // is not the most derived class.
4683 if (ClassDecl->isAbstract()) {
4684 // FIXME: Provide a fixit to remove the base specifier. This requires
4685 // tracking the location of the associated comma for a base specifier.
4686 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00004687 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00004688 DiagnoseAbstractType(ClassDecl);
4689 }
4690
John McCallbc83b3f2010-05-20 23:23:51 +00004691 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00004692 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4693 // [class.base.init]p8, per DR257:
4694 // If a given [...] base class is not named by a mem-initializer-id
4695 // [...] and the entity is not a virtual base class of an abstract
4696 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00004697 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00004698 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00004699 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00004700 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00004701 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004702 HadError = true;
4703 continue;
4704 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004705
John McCallbc83b3f2010-05-20 23:23:51 +00004706 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004707 }
4708 }
Mike Stump11289f42009-09-09 15:08:12 +00004709
John McCallbc83b3f2010-05-20 23:23:51 +00004710 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004711 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004712 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00004713 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00004714 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004715
Alexis Hunt1d792652011-01-08 20:30:50 +00004716 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00004717 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00004718 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00004719 } else if (!AnyErrors) {
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 Ballman574705e2014-03-13 15:41:46 +00004722 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004723 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004724 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004725 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00004726 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +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 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00004733 for (auto *Mem : ClassDecl->decls()) {
4734 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004735 // C++ [class.bit]p2:
4736 // A declaration for a bit-field that omits the identifier declares an
4737 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
4738 // initialized.
4739 if (F->isUnnamedBitfield())
4740 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004741
Sebastian Redl22653ba2011-08-30 19:58:05 +00004742 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00004743 // handle anonymous struct/union fields based on their individual
4744 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00004745 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00004746 continue;
4747
4748 if (CollectFieldInitializer(*this, Info, F))
4749 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004750 continue;
4751 }
Douglas Gregor493627b2011-08-10 15:22:55 +00004752
4753 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00004754 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00004755 continue;
4756
Aaron Ballman629afae2014-03-07 19:56:05 +00004757 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00004758 if (F->getType()->isIncompleteArrayType()) {
4759 assert(ClassDecl->hasFlexibleArrayMember() &&
4760 "Incomplete array type is not valid");
4761 continue;
4762 }
4763
Douglas Gregor493627b2011-08-10 15:22:55 +00004764 // Initialize each field of an anonymous struct individually.
4765 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4766 HadError = true;
4767
4768 continue;
4769 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004770 }
Mike Stump11289f42009-09-09 15:08:12 +00004771
David Blaikie3fc2f912013-01-17 05:26:25 +00004772 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004773 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004774 Constructor->setNumCtorInitializers(NumInitializers);
4775 CXXCtorInitializer **baseOrMemberInitializers =
4776 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00004777 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00004778 NumInitializers * sizeof(CXXCtorInitializer*));
4779 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00004780
John McCalla6309952010-03-16 21:39:52 +00004781 // Constructors implicitly reference the base and member
4782 // destructors.
4783 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4784 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004785 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00004786
4787 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004788}
4789
David Blaikieb61b8152013-01-17 08:49:22 +00004790static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004791 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00004792 const RecordDecl *RD = RT->getDecl();
4793 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004794 for (auto *Field : RD->fields())
4795 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00004796 return;
4797 }
Eli Friedman952c15d2009-07-21 19:28:10 +00004798 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00004799 IdealInits.push_back(Field->getCanonicalDecl());
Eli Friedman952c15d2009-07-21 19:28:10 +00004800}
4801
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004802static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4803 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00004804}
4805
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004806static const void *GetKeyForMember(ASTContext &Context,
4807 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00004808 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004809 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00004810
Richard Smithcd45dbc2014-04-19 03:48:30 +00004811 return Member->getAnyMember()->getCanonicalDecl();
Eli Friedman952c15d2009-07-21 19:28:10 +00004812}
4813
David Blaikie3fc2f912013-01-17 05:26:25 +00004814static void DiagnoseBaseOrMemInitializerOrder(
4815 Sema &SemaRef, const CXXConstructorDecl *Constructor,
4816 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00004817 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00004818 return;
Mike Stump11289f42009-09-09 15:08:12 +00004819
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004820 // Don't check initializers order unless the warning is enabled at the
4821 // location of at least one initializer.
4822 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004823 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004824 CXXCtorInitializer *Init = Inits[InitIndex];
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004825 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4826 Init->getSourceLocation())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004827 ShouldCheckOrder = true;
4828 break;
4829 }
4830 }
4831 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00004832 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004833
John McCallbb7b6582010-04-10 07:37:23 +00004834 // Build the list of bases and members in the order that they'll
4835 // actually be initialized. The explicit initializers should be in
4836 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004837 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00004838
Anders Carlsson96b8fc62010-04-02 03:38:04 +00004839 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4840
John McCallbb7b6582010-04-10 07:37:23 +00004841 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004842 for (const auto &VBase : ClassDecl->vbases())
4843 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00004844
John McCallbb7b6582010-04-10 07:37:23 +00004845 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004846 for (const auto &Base : ClassDecl->bases()) {
4847 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00004848 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00004849 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00004850 }
Mike Stump11289f42009-09-09 15:08:12 +00004851
John McCallbb7b6582010-04-10 07:37:23 +00004852 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004853 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004854 if (Field->isUnnamedBitfield())
4855 continue;
4856
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004857 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00004858 }
4859
John McCallbb7b6582010-04-10 07:37:23 +00004860 unsigned NumIdealInits = IdealInitKeys.size();
4861 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00004862
Craig Topperc3ec1492014-05-26 06:22:03 +00004863 CXXCtorInitializer *PrevInit = nullptr;
David Blaikie3fc2f912013-01-17 05:26:25 +00004864 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004865 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004866 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00004867
4868 // Scan forward to try to find this initializer in the idealized
4869 // initializers list.
4870 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4871 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004872 break;
John McCallbb7b6582010-04-10 07:37:23 +00004873
4874 // If we didn't find this initializer, it must be because we
4875 // scanned past it on a previous iteration. That can only
4876 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00004877 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00004878 Sema::SemaDiagnosticBuilder D =
4879 SemaRef.Diag(PrevInit->getSourceLocation(),
4880 diag::warn_initializer_out_of_order);
4881
Francois Pichetd583da02010-12-04 09:14:42 +00004882 if (PrevInit->isAnyMemberInitializer())
4883 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004884 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004885 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004886
Francois Pichetd583da02010-12-04 09:14:42 +00004887 if (Init->isAnyMemberInitializer())
4888 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004889 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004890 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004891
4892 // Move back to the initializer's location in the ideal list.
4893 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4894 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004895 break;
John McCallbb7b6582010-04-10 07:37:23 +00004896
Aaron Ballmanddd2ece2015-07-20 13:36:07 +00004897 assert(IdealIndex < NumIdealInits &&
John McCallbb7b6582010-04-10 07:37:23 +00004898 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004899 }
John McCallbb7b6582010-04-10 07:37:23 +00004900
4901 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004902 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00004903}
4904
John McCall23eebd92010-04-10 09:28:51 +00004905namespace {
4906bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004907 CXXCtorInitializer *Init,
4908 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00004909 if (!PrevInit) {
4910 PrevInit = Init;
4911 return false;
4912 }
4913
Douglas Gregorea306a12013-03-25 23:28:23 +00004914 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00004915 S.Diag(Init->getSourceLocation(),
4916 diag::err_multiple_mem_initialization)
4917 << Field->getDeclName()
4918 << Init->getSourceRange();
4919 else {
John McCall424cec92011-01-19 06:33:43 +00004920 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00004921 assert(BaseClass && "neither field nor base");
4922 S.Diag(Init->getSourceLocation(),
4923 diag::err_multiple_base_initialization)
4924 << QualType(BaseClass, 0)
4925 << Init->getSourceRange();
4926 }
4927 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4928 << 0 << PrevInit->getSourceRange();
4929
4930 return true;
4931}
4932
Alexis Hunt1d792652011-01-08 20:30:50 +00004933typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00004934typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4935
4936bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004937 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00004938 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00004939 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00004940 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00004941 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00004942
4943 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00004944 if (Parent->isUnion()) {
4945 UnionEntry &En = Unions[Parent];
4946 if (En.first && En.first != Child) {
4947 S.Diag(Init->getSourceLocation(),
4948 diag::err_multiple_mem_union_initialization)
4949 << Field->getDeclName()
4950 << Init->getSourceRange();
4951 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4952 << 0 << En.second->getSourceRange();
4953 return true;
David Blaikie256ee192011-11-12 20:54:14 +00004954 }
4955 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00004956 En.first = Child;
4957 En.second = Init;
4958 }
David Blaikie0f65d592011-11-17 06:01:57 +00004959 if (!Parent->isAnonymousStructOrUnion())
4960 return false;
John McCall23eebd92010-04-10 09:28:51 +00004961 }
4962
4963 Child = Parent;
4964 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00004965 }
John McCall23eebd92010-04-10 09:28:51 +00004966
4967 return false;
4968}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004969}
John McCall23eebd92010-04-10 09:28:51 +00004970
Anders Carlssone857b292010-04-02 03:37:03 +00004971/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00004972void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00004973 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00004974 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00004975 bool AnyErrors) {
4976 if (!ConstructorDecl)
4977 return;
4978
4979 AdjustDeclIfTemplate(ConstructorDecl);
4980
4981 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00004982 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00004983
4984 if (!Constructor) {
4985 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4986 return;
4987 }
4988
John McCall23eebd92010-04-10 09:28:51 +00004989 // Mapping for the duplicate initializers check.
4990 // For member initializers, this is keyed with a FieldDecl*.
4991 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004992 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00004993
4994 // Mapping for the inconsistent anonymous-union initializers check.
4995 RedundantUnionMap MemberUnions;
4996
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004997 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004998 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004999 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00005000
Abramo Bagnara341d7832010-05-26 18:09:23 +00005001 // Set the source order index.
5002 Init->setSourceOrder(i);
5003
Francois Pichetd583da02010-12-04 09:14:42 +00005004 if (Init->isAnyMemberInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00005005 const void *Key = GetKeyForMember(Context, Init);
5006 if (CheckRedundantInit(*this, Init, Members[Key]) ||
John McCall23eebd92010-04-10 09:28:51 +00005007 CheckRedundantUnionInit(*this, Init, MemberUnions))
5008 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00005009 } else if (Init->isBaseInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00005010 const void *Key = GetKeyForMember(Context, Init);
John McCall23eebd92010-04-10 09:28:51 +00005011 if (CheckRedundantInit(*this, Init, Members[Key]))
5012 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00005013 } else {
5014 assert(Init->isDelegatingInitializer());
5015 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00005016 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00005017 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00005018 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00005019 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00005020 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00005021 }
Alexis Hunt6118d662011-05-04 05:57:24 +00005022 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00005023 // Return immediately as the initializer is set.
5024 return;
Anders Carlssone857b292010-04-02 03:37:03 +00005025 }
Anders Carlssone857b292010-04-02 03:37:03 +00005026 }
5027
Anders Carlsson7b3f2782010-04-02 05:42:15 +00005028 if (HadError)
5029 return;
5030
David Blaikie3fc2f912013-01-17 05:26:25 +00005031 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00005032
David Blaikie3fc2f912013-01-17 05:26:25 +00005033 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00005034
Richard Trieuef64e942013-10-25 00:56:00 +00005035 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00005036}
5037
Fariborz Jahanian37d06562009-09-03 23:18:17 +00005038void
John McCalla6309952010-03-16 21:39:52 +00005039Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5040 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00005041 // Ignore dependent contexts. Also ignore unions, since their members never
5042 // have destructors implicitly called.
5043 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00005044 return;
John McCall1064d7e2010-03-16 05:22:47 +00005045
5046 // FIXME: all the access-control diagnostics are positioned on the
5047 // field/base declaration. That's probably good; that said, the
5048 // user might reasonably want to know why the destructor is being
5049 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00005050
Anders Carlssondee9a302009-11-17 04:44:12 +00005051 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005052 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00005053 if (Field->isInvalidDecl())
5054 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00005055
5056 // Don't destroy incomplete or zero-length arrays.
5057 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5058 continue;
5059
Anders Carlssondee9a302009-11-17 04:44:12 +00005060 QualType FieldType = Context.getBaseElementType(Field->getType());
5061
5062 const RecordType* RT = FieldType->getAs<RecordType>();
5063 if (!RT)
5064 continue;
5065
5066 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005067 if (FieldClassDecl->isInvalidDecl())
5068 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00005069 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00005070 continue;
Richard Smith921bd202012-02-26 09:11:52 +00005071 // The destructor for an implicit anonymous union member is never invoked.
5072 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5073 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00005074
Douglas Gregore71edda2010-07-01 22:47:18 +00005075 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005076 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00005077 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00005078 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00005079 << Field->getDeclName()
5080 << FieldType);
5081
Benjamin Kramer8bf44352013-07-24 15:28:33 +00005082 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00005083 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00005084 }
5085
John McCall1064d7e2010-03-16 05:22:47 +00005086 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5087
Anders Carlssondee9a302009-11-17 04:44:12 +00005088 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00005089 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00005090 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00005091 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00005092
5093 // Remember direct virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00005094 if (Base.isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00005095 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00005096
John McCall1064d7e2010-03-16 05:22:47 +00005097 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005098 // If our base class is invalid, we probably can't get its dtor anyway.
5099 if (BaseClassDecl->isInvalidDecl())
5100 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00005101 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00005102 continue;
John McCall1064d7e2010-03-16 05:22:47 +00005103
Douglas Gregore71edda2010-07-01 22:47:18 +00005104 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005105 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00005106
5107 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00005108 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00005109 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00005110 << Base.getType()
5111 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00005112 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00005113
Benjamin Kramer8bf44352013-07-24 15:28:33 +00005114 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00005115 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00005116 }
5117
5118 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00005119 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00005120 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00005121 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00005122
5123 // Ignore direct virtual bases.
5124 if (DirectVirtualBases.count(RT))
5125 continue;
5126
John McCall1064d7e2010-03-16 05:22:47 +00005127 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005128 // If our base class is invalid, we probably can't get its dtor anyway.
5129 if (BaseClassDecl->isInvalidDecl())
5130 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00005131 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00005132 continue;
John McCall1064d7e2010-03-16 05:22:47 +00005133
Douglas Gregore71edda2010-07-01 22:47:18 +00005134 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005135 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00005136 if (CheckDestructorAccess(
5137 ClassDecl->getLocation(), Dtor,
5138 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00005139 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00005140 Context.getTypeDeclType(ClassDecl)) ==
5141 AR_accessible) {
5142 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00005143 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00005144 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005145 SourceRange(), DeclarationName(), nullptr);
David Majnemer626032f2013-06-22 06:43:58 +00005146 }
John McCall1064d7e2010-03-16 05:22:47 +00005147
Benjamin Kramer8bf44352013-07-24 15:28:33 +00005148 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00005149 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00005150 }
5151}
5152
John McCall48871652010-08-21 09:40:31 +00005153void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00005154 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00005155 return;
Mike Stump11289f42009-09-09 15:08:12 +00005156
Mike Stump11289f42009-09-09 15:08:12 +00005157 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00005158 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00005159 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00005160 DiagnoseUninitializedFields(*this, Constructor);
5161 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00005162}
5163
Richard Smithdb0ac552015-12-18 22:40:25 +00005164bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005165 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005166 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005167
Richard Smithdb0ac552015-12-18 22:40:25 +00005168 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5169 if (!RD)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005170 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005171
Richard Smithdb0ac552015-12-18 22:40:25 +00005172 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5173 // class template specialization here, but doing so breaks a lot of code.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005174
John McCall02db245d2010-08-18 09:41:07 +00005175 // We can't answer whether something is abstract until it has a
Richard Smithdb0ac552015-12-18 22:40:25 +00005176 // definition. If it's currently being defined, we'll walk back
John McCall02db245d2010-08-18 09:41:07 +00005177 // over all the declarations when we have a full definition.
5178 const CXXRecordDecl *Def = RD->getDefinition();
5179 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00005180 return false;
5181
Richard Smithdb0ac552015-12-18 22:40:25 +00005182 return RD->isAbstract();
5183}
5184
5185bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5186 TypeDiagnoser &Diagnoser) {
5187 if (!isAbstractType(Loc, T))
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005188 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005189
Richard Smithdb0ac552015-12-18 22:40:25 +00005190 T = Context.getBaseElementType(T);
Douglas Gregorae298422012-05-04 17:09:59 +00005191 Diagnoser.diagnose(*this, Loc, T);
Richard Smithdb0ac552015-12-18 22:40:25 +00005192 DiagnoseAbstractType(T->getAsCXXRecordDecl());
John McCall02db245d2010-08-18 09:41:07 +00005193 return true;
5194}
5195
5196void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5197 // Check if we've already emitted the list of pure virtual functions
5198 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005199 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00005200 return;
Mike Stump11289f42009-09-09 15:08:12 +00005201
Richard Smithbc46e432013-07-22 02:56:56 +00005202 // If the diagnostic is suppressed, don't emit the notes. We're only
5203 // going to emit them once, so try to attach them to a diagnostic we're
5204 // actually going to show.
5205 if (Diags.isLastDiagnosticIgnored())
5206 return;
5207
Douglas Gregor4165bd62010-03-23 23:47:56 +00005208 CXXFinalOverriderMap FinalOverriders;
5209 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00005210
Anders Carlssona2f74f32010-06-03 01:00:02 +00005211 // Keep a set of seen pure methods so we won't diagnose the same method
5212 // more than once.
5213 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5214
Douglas Gregor4165bd62010-03-23 23:47:56 +00005215 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5216 MEnd = FinalOverriders.end();
5217 M != MEnd;
5218 ++M) {
5219 for (OverridingMethods::iterator SO = M->second.begin(),
5220 SOEnd = M->second.end();
5221 SO != SOEnd; ++SO) {
5222 // C++ [class.abstract]p4:
5223 // A class is abstract if it contains or inherits at least one
5224 // pure virtual function for which the final overrider is pure
5225 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00005226
Douglas Gregor4165bd62010-03-23 23:47:56 +00005227 //
5228 if (SO->second.size() != 1)
5229 continue;
5230
5231 if (!SO->second.front().Method->isPure())
5232 continue;
5233
David Blaikie82e95a32014-11-19 07:49:47 +00005234 if (!SeenPureMethods.insert(SO->second.front().Method).second)
Anders Carlssona2f74f32010-06-03 01:00:02 +00005235 continue;
5236
Douglas Gregor4165bd62010-03-23 23:47:56 +00005237 Diag(SO->second.front().Method->getLocation(),
5238 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00005239 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00005240 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005241 }
5242
5243 if (!PureVirtualClassDiagSet)
5244 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5245 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005246}
5247
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005248namespace {
John McCall02db245d2010-08-18 09:41:07 +00005249struct AbstractUsageInfo {
5250 Sema &S;
5251 CXXRecordDecl *Record;
5252 CanQualType AbstractType;
5253 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00005254
John McCall02db245d2010-08-18 09:41:07 +00005255 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5256 : S(S), Record(Record),
5257 AbstractType(S.Context.getCanonicalType(
5258 S.Context.getTypeDeclType(Record))),
5259 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005260
John McCall02db245d2010-08-18 09:41:07 +00005261 void DiagnoseAbstractType() {
5262 if (Invalid) return;
5263 S.DiagnoseAbstractType(Record);
5264 Invalid = true;
5265 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00005266
John McCall02db245d2010-08-18 09:41:07 +00005267 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5268};
5269
5270struct CheckAbstractUsage {
5271 AbstractUsageInfo &Info;
5272 const NamedDecl *Ctx;
5273
5274 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5275 : Info(Info), Ctx(Ctx) {}
5276
5277 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5278 switch (TL.getTypeLocClass()) {
5279#define ABSTRACT_TYPELOC(CLASS, PARENT)
5280#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00005281 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00005282#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005283 }
John McCall02db245d2010-08-18 09:41:07 +00005284 }
Mike Stump11289f42009-09-09 15:08:12 +00005285
John McCall02db245d2010-08-18 09:41:07 +00005286 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00005287 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005288 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5289 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00005290 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005291
5292 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00005293 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00005294 }
John McCall02db245d2010-08-18 09:41:07 +00005295 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005296
John McCall02db245d2010-08-18 09:41:07 +00005297 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5298 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5299 }
Mike Stump11289f42009-09-09 15:08:12 +00005300
John McCall02db245d2010-08-18 09:41:07 +00005301 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5302 // Visit the type parameters from a permissive context.
5303 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5304 TemplateArgumentLoc TAL = TL.getArgLoc(I);
5305 if (TAL.getArgument().getKind() == TemplateArgument::Type)
5306 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5307 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5308 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005309 }
John McCall02db245d2010-08-18 09:41:07 +00005310 }
Mike Stump11289f42009-09-09 15:08:12 +00005311
John McCall02db245d2010-08-18 09:41:07 +00005312 // Visit pointee types from a permissive context.
5313#define CheckPolymorphic(Type) \
5314 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5315 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5316 }
5317 CheckPolymorphic(PointerTypeLoc)
5318 CheckPolymorphic(ReferenceTypeLoc)
5319 CheckPolymorphic(MemberPointerTypeLoc)
5320 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00005321 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00005322
John McCall02db245d2010-08-18 09:41:07 +00005323 /// Handle all the types we haven't given a more specific
5324 /// implementation for above.
5325 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5326 // Every other kind of type that we haven't called out already
5327 // that has an inner type is either (1) sugar or (2) contains that
5328 // inner type in some way as a subobject.
5329 if (TypeLoc Next = TL.getNextTypeLoc())
5330 return Visit(Next, Sel);
5331
5332 // If there's no inner type and we're in a permissive context,
5333 // don't diagnose.
5334 if (Sel == Sema::AbstractNone) return;
5335
5336 // Check whether the type matches the abstract type.
5337 QualType T = TL.getType();
5338 if (T->isArrayType()) {
5339 Sel = Sema::AbstractArrayType;
5340 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00005341 }
John McCall02db245d2010-08-18 09:41:07 +00005342 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5343 if (CT != Info.AbstractType) return;
5344
5345 // It matched; do some magic.
5346 if (Sel == Sema::AbstractArrayType) {
5347 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5348 << T << TL.getSourceRange();
5349 } else {
5350 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5351 << Sel << T << TL.getSourceRange();
5352 }
5353 Info.DiagnoseAbstractType();
5354 }
5355};
5356
5357void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5358 Sema::AbstractDiagSelID Sel) {
5359 CheckAbstractUsage(*this, D).Visit(TL, Sel);
5360}
5361
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005362}
John McCall02db245d2010-08-18 09:41:07 +00005363
5364/// Check for invalid uses of an abstract type in a method declaration.
5365static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5366 CXXMethodDecl *MD) {
5367 // No need to do the check on definitions, which require that
5368 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00005369 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00005370 return;
5371
5372 // For safety's sake, just ignore it if we don't have type source
5373 // information. This should never happen for non-implicit methods,
5374 // but...
5375 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5376 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5377}
5378
5379/// Check for invalid uses of an abstract type within a class definition.
5380static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5381 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00005382 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00005383 if (D->isImplicit()) continue;
5384
5385 // Methods and method templates.
5386 if (isa<CXXMethodDecl>(D)) {
5387 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5388 } else if (isa<FunctionTemplateDecl>(D)) {
5389 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5390 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5391
5392 // Fields and static variables.
5393 } else if (isa<FieldDecl>(D)) {
5394 FieldDecl *FD = cast<FieldDecl>(D);
5395 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5396 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5397 } else if (isa<VarDecl>(D)) {
5398 VarDecl *VD = cast<VarDecl>(D);
5399 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5400 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5401
5402 // Nested classes and class templates.
5403 } else if (isa<CXXRecordDecl>(D)) {
5404 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5405 } else if (isa<ClassTemplateDecl>(D)) {
5406 CheckAbstractClassUsage(Info,
5407 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5408 }
5409 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005410}
5411
Hans Wennborg99000c22015-08-15 01:18:16 +00005412static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) {
5413 Attr *ClassAttr = getDLLAttr(Class);
5414 if (!ClassAttr)
5415 return;
5416
5417 assert(ClassAttr->getKind() == attr::DLLExport);
5418
5419 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5420
5421 if (TSK == TSK_ExplicitInstantiationDeclaration)
5422 // Don't go any further if this is just an explicit instantiation
5423 // declaration.
5424 return;
5425
5426 for (Decl *Member : Class->decls()) {
5427 auto *MD = dyn_cast<CXXMethodDecl>(Member);
5428 if (!MD)
5429 continue;
5430
5431 if (Member->getAttr<DLLExportAttr>()) {
5432 if (MD->isUserProvided()) {
5433 // Instantiate non-default class member functions ...
5434
5435 // .. except for certain kinds of template specializations.
5436 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5437 continue;
5438
5439 S.MarkFunctionReferenced(Class->getLocation(), MD);
5440
5441 // The function will be passed to the consumer when its definition is
5442 // encountered.
5443 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5444 MD->isCopyAssignmentOperator() ||
5445 MD->isMoveAssignmentOperator()) {
5446 // Synthesize and instantiate non-trivial implicit methods, explicitly
5447 // defaulted methods, and the copy and move assignment operators. The
5448 // latter are exported even if they are trivial, because the address of
5449 // an operator can be taken and should compare equal accross libraries.
5450 DiagnosticErrorTrap Trap(S.Diags);
5451 S.MarkFunctionReferenced(Class->getLocation(), MD);
5452 if (Trap.hasErrorOccurred()) {
5453 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5454 << Class->getName() << !S.getLangOpts().CPlusPlus11;
5455 break;
5456 }
5457
5458 // There is no later point when we will see the definition of this
5459 // function, so pass it to the consumer now.
5460 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5461 }
5462 }
5463 }
5464}
5465
Reid Kleckner82713bf2017-01-09 17:27:17 +00005466static void checkForMultipleExportedDefaultConstructors(Sema &S,
5467 CXXRecordDecl *Class) {
5468 // Only the MS ABI has default constructor closures, so we don't need to do
5469 // this semantic checking anywhere else.
5470 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5471 return;
5472
Reid Kleckner61195e12017-01-05 01:08:22 +00005473 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5474 for (Decl *Member : Class->decls()) {
5475 // Look for exported default constructors.
5476 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
Reid Kleckner82713bf2017-01-09 17:27:17 +00005477 if (!CD || !CD->isDefaultConstructor())
Reid Kleckner61195e12017-01-05 01:08:22 +00005478 continue;
Reid Kleckner82713bf2017-01-09 17:27:17 +00005479 auto *Attr = CD->getAttr<DLLExportAttr>();
5480 if (!Attr)
5481 continue;
5482
5483 // If the class is non-dependent, mark the default arguments as ODR-used so
5484 // that we can properly codegen the constructor closure.
5485 if (!Class->isDependentContext()) {
5486 for (ParmVarDecl *PD : CD->parameters()) {
5487 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5488 S.DiscardCleanupsInEvaluationContext();
5489 }
5490 }
Reid Kleckner61195e12017-01-05 01:08:22 +00005491
5492 if (LastExportedDefaultCtor) {
5493 S.Diag(LastExportedDefaultCtor->getLocation(),
5494 diag::err_attribute_dll_ambiguous_default_ctor)
5495 << Class;
5496 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5497 << CD->getDeclName();
5498 return;
5499 }
5500 LastExportedDefaultCtor = CD;
5501 }
5502}
5503
Hans Wennborg853ae942014-05-30 16:59:42 +00005504/// \brief Check class-level dllimport/dllexport attribute.
Hans Wennborg17f9b442015-05-27 00:06:45 +00005505void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
Hans Wennborg853ae942014-05-30 16:59:42 +00005506 Attr *ClassAttr = getDLLAttr(Class);
Hans Wennborg205c39b2014-08-23 22:34:43 +00005507
5508 // MSVC inherits DLL attributes to partial class template specializations.
Hans Wennborg17f9b442015-05-27 00:06:45 +00005509 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
Hans Wennborg205c39b2014-08-23 22:34:43 +00005510 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5511 if (Attr *TemplateAttr =
5512 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
Hans Wennborg17f9b442015-05-27 00:06:45 +00005513 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
Hans Wennborg205c39b2014-08-23 22:34:43 +00005514 A->setInherited(true);
5515 ClassAttr = A;
5516 }
5517 }
5518 }
5519
Hans Wennborg853ae942014-05-30 16:59:42 +00005520 if (!ClassAttr)
5521 return;
5522
Hans Wennborg8313c762014-11-03 16:09:16 +00005523 if (!Class->isExternallyVisible()) {
Hans Wennborg17f9b442015-05-27 00:06:45 +00005524 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
Hans Wennborg8313c762014-11-03 16:09:16 +00005525 << Class << ClassAttr;
5526 return;
5527 }
5528
Hans Wennborg17f9b442015-05-27 00:06:45 +00005529 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00005530 !ClassAttr->isInherited()) {
5531 // Diagnose dll attributes on members of class with dll attribute.
5532 for (Decl *Member : Class->decls()) {
5533 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5534 continue;
5535 InheritableAttr *MemberAttr = getDLLAttr(Member);
5536 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5537 continue;
5538
Hans Wennborg17f9b442015-05-27 00:06:45 +00005539 Diag(MemberAttr->getLocation(),
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00005540 diag::err_attribute_dll_member_of_dll_class)
5541 << MemberAttr << ClassAttr;
Hans Wennborg17f9b442015-05-27 00:06:45 +00005542 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00005543 Member->setInvalidDecl();
5544 }
5545 }
5546
5547 if (Class->getDescribedClassTemplate())
5548 // Don't inherit dll attribute until the template is instantiated.
5549 return;
5550
Hans Wennborg606bd6d2014-11-03 14:24:45 +00005551 // The class is either imported or exported.
5552 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
Hans Wennborg853ae942014-05-30 16:59:42 +00005553
Hans Wennborgfd76d912015-01-15 21:18:30 +00005554 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5555
Hans Wennborgbb1983c2015-06-09 00:39:03 +00005556 // Ignore explicit dllexport on explicit class template instantiation declarations.
5557 if (ClassExported && !ClassAttr->isInherited() &&
5558 TSK == TSK_ExplicitInstantiationDeclaration) {
Hans Wennborgfd76d912015-01-15 21:18:30 +00005559 Class->dropAttr<DLLExportAttr>();
5560 return;
5561 }
5562
Hans Wennborg853ae942014-05-30 16:59:42 +00005563 // Force declaration of implicit members so they can inherit the attribute.
Hans Wennborg17f9b442015-05-27 00:06:45 +00005564 ForceDeclarationOfImplicitMembers(Class);
Hans Wennborg853ae942014-05-30 16:59:42 +00005565
5566 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5567 // seem to be true in practice?
5568
Hans Wennborg853ae942014-05-30 16:59:42 +00005569 for (Decl *Member : Class->decls()) {
Hans Wennborge8ad3832014-06-11 22:44:39 +00005570 VarDecl *VD = dyn_cast<VarDecl>(Member);
5571 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5572
5573 // Only methods and static fields inherit the attributes.
5574 if (!VD && !MD)
Hans Wennborg853ae942014-05-30 16:59:42 +00005575 continue;
Hans Wennborge8ad3832014-06-11 22:44:39 +00005576
Hans Wennborg606bd6d2014-11-03 14:24:45 +00005577 if (MD) {
5578 // Don't process deleted methods.
5579 if (MD->isDeleted())
5580 continue;
Hans Wennborg853ae942014-05-30 16:59:42 +00005581
David Majnemer30f058a2015-05-11 03:00:22 +00005582 if (MD->isInlined()) {
Hans Wennborg97cbed42015-02-19 22:39:24 +00005583 // MinGW does not import or export inline methods.
Saleem Abdulrasool8bbc3152016-10-14 22:25:46 +00005584 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5585 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
David Majnemer30f058a2015-05-11 03:00:22 +00005586 continue;
5587
Dmitry Polukhin41581522016-05-13 09:03:56 +00005588 // MSVC versions before 2015 don't export the move assignment operators
5589 // and move constructor, so don't attempt to import/export them if
5590 // we have a definition.
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005591 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
Dmitry Polukhin41581522016-05-13 09:03:56 +00005592 if ((MD->isMoveAssignmentOperator() ||
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005593 (Ctor && Ctor->isMoveConstructor())) &&
Hans Wennborg17f9b442015-05-27 00:06:45 +00005594 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
David Majnemer30f058a2015-05-11 03:00:22 +00005595 continue;
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005596
5597 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5598 // operator is exported anyway.
5599 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5600 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5601 continue;
Hans Wennborg606bd6d2014-11-03 14:24:45 +00005602 }
Hans Wennborge8ad3832014-06-11 22:44:39 +00005603 }
5604
Hans Wennborg287231c2015-04-22 04:05:17 +00005605 if (!cast<NamedDecl>(Member)->isExternallyVisible())
5606 continue;
5607
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00005608 if (!getDLLAttr(Member)) {
Hans Wennborg496524b2014-05-31 02:08:49 +00005609 auto *NewAttr =
Hans Wennborg17f9b442015-05-27 00:06:45 +00005610 cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
Hans Wennborg496524b2014-05-31 02:08:49 +00005611 NewAttr->setInherited(true);
5612 Member->addAttr(NewAttr);
5613 }
Hans Wennborg853ae942014-05-30 16:59:42 +00005614 }
Hans Wennborg99000c22015-08-15 01:18:16 +00005615
5616 if (ClassExported)
5617 DelayedDllExportClasses.push_back(Class);
Hans Wennborg853ae942014-05-30 16:59:42 +00005618}
5619
Hans Wennborgfce87ca2015-06-09 00:39:09 +00005620/// \brief Perform propagation of DLL attributes from a derived class to a
5621/// templated base class for MS compatibility.
5622void Sema::propagateDLLAttrToBaseClassTemplate(
5623 CXXRecordDecl *Class, Attr *ClassAttr,
5624 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5625 if (getDLLAttr(
5626 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5627 // If the base class template has a DLL attribute, don't try to change it.
5628 return;
5629 }
5630
5631 auto TSK = BaseTemplateSpec->getSpecializationKind();
5632 if (!getDLLAttr(BaseTemplateSpec) &&
5633 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5634 TSK == TSK_ImplicitInstantiation)) {
5635 // The template hasn't been instantiated yet (or it has, but only as an
5636 // explicit instantiation declaration or implicit instantiation, which means
5637 // we haven't codegenned any members yet), so propagate the attribute.
5638 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5639 NewAttr->setInherited(true);
5640 BaseTemplateSpec->addAttr(NewAttr);
5641
5642 // If the template is already instantiated, checkDLLAttributeRedeclaration()
5643 // needs to be run again to work see the new attribute. Otherwise this will
5644 // get run whenever the template is instantiated.
5645 if (TSK != TSK_Undeclared)
5646 checkClassLevelDLLAttribute(BaseTemplateSpec);
5647
5648 return;
5649 }
5650
5651 if (getDLLAttr(BaseTemplateSpec)) {
5652 // The template has already been specialized or instantiated with an
5653 // attribute, explicitly or through propagation. We should not try to change
5654 // it.
5655 return;
5656 }
5657
5658 // The template was previously instantiated or explicitly specialized without
5659 // a dll attribute, It's too late for us to add an attribute, so warn that
5660 // this is unsupported.
5661 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5662 << BaseTemplateSpec->isExplicitSpecialization();
5663 Diag(ClassAttr->getLocation(), diag::note_attribute);
5664 if (BaseTemplateSpec->isExplicitSpecialization()) {
5665 Diag(BaseTemplateSpec->getLocation(),
5666 diag::note_template_class_explicit_specialization_was_here)
5667 << BaseTemplateSpec;
5668 } else {
5669 Diag(BaseTemplateSpec->getPointOfInstantiation(),
5670 diag::note_template_class_instantiation_was_here)
5671 << BaseTemplateSpec;
5672 }
5673}
5674
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005675static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5676 SourceLocation DefaultLoc) {
5677 switch (S.getSpecialMember(MD)) {
5678 case Sema::CXXDefaultConstructor:
5679 S.DefineImplicitDefaultConstructor(DefaultLoc,
5680 cast<CXXConstructorDecl>(MD));
5681 break;
5682 case Sema::CXXCopyConstructor:
5683 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5684 break;
5685 case Sema::CXXCopyAssignment:
5686 S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5687 break;
5688 case Sema::CXXDestructor:
5689 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5690 break;
5691 case Sema::CXXMoveConstructor:
5692 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5693 break;
5694 case Sema::CXXMoveAssignment:
5695 S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5696 break;
5697 case Sema::CXXInvalid:
5698 llvm_unreachable("Invalid special member.");
5699 }
5700}
5701
Douglas Gregorc99f1552009-12-03 18:33:45 +00005702/// \brief Perform semantic checks on a class definition that has been
5703/// completing, introducing implicitly-declared members, checking for
5704/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00005705void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00005706 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00005707 return;
5708
John McCall02db245d2010-08-18 09:41:07 +00005709 if (Record->isAbstract() && !Record->isInvalidDecl()) {
5710 AbstractUsageInfo Info(*this, Record);
5711 CheckAbstractClassUsage(Info, Record);
5712 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00005713
5714 // If this is not an aggregate type and has no user-declared constructor,
5715 // complain about any non-static data members of reference or const scalar
5716 // type, since they will never get initializers.
5717 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00005718 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
5719 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00005720 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005721 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00005722 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00005723 continue;
5724
Douglas Gregor454a5b62010-04-15 00:00:53 +00005725 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00005726 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00005727 if (!Complained) {
5728 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
5729 << Record->getTagKind() << Record;
5730 Complained = true;
5731 }
5732
5733 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
5734 << F->getType()->isReferenceType()
5735 << F->getDeclName();
5736 }
5737 }
5738 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00005739
Douglas Gregor36c22a22010-10-15 13:21:21 +00005740 if (Record->getIdentifier()) {
5741 // C++ [class.mem]p13:
5742 // If T is the name of a class, then each of the following shall have a
5743 // name different from T:
5744 // - every member of every anonymous union that is a member of class T.
5745 //
5746 // C++ [class.mem]p14:
5747 // In addition, if class T has a user-declared constructor (12.1), every
5748 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00005749 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
5750 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
5751 ++I) {
5752 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00005753 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
5754 isa<IndirectFieldDecl>(D)) {
5755 Diag(D->getLocation(), diag::err_member_name_of_class)
5756 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00005757 break;
5758 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00005759 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00005760 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00005761
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00005762 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00005763 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00005764 CXXDestructorDecl *dtor = Record->getDestructor();
David Blaikie04e2e662014-05-09 22:02:28 +00005765 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
5766 !Record->hasAttr<FinalAttr>())
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00005767 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
5768 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
5769 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005770
David Majnemera5433082013-10-18 00:33:31 +00005771 if (Record->isAbstract()) {
5772 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
5773 Diag(Record->getLocation(), diag::warn_abstract_final_class)
5774 << FA->isSpelledAsSealed();
5775 DiagnoseAbstractType(Record);
5776 }
David Blaikie348df502012-09-21 03:21:07 +00005777 }
5778
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00005779 bool HasMethodWithOverrideControl = false,
5780 HasOverridingMethodWithoutOverrideControl = false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005781 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005782 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00005783 // See if a method overloads virtual methods in a base
5784 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005785 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00005786 DiagnoseHiddenVirtualMethods(M);
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00005787 if (M->hasAttr<OverrideAttr>())
5788 HasMethodWithOverrideControl = true;
5789 else if (M->size_overridden_methods() > 0)
5790 HasOverridingMethodWithoutOverrideControl = true;
Richard Smithbd305122012-12-11 01:14:52 +00005791 // Check whether the explicitly-defaulted special members are valid.
5792 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00005793 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00005794
5795 // For an explicitly defaulted or deleted special member, we defer
5796 // determining triviality until the class is complete. That time is now!
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005797 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00005798 if (!M->isImplicit() && !M->isUserProvided()) {
Richard Smithbd305122012-12-11 01:14:52 +00005799 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005800 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00005801
5802 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005803 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00005804 }
5805 }
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005806
5807 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
5808 M->hasAttr<DLLExportAttr>()) {
5809 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5810 M->isTrivial() &&
5811 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
5812 CSM == CXXDestructor))
5813 M->dropAttr<DLLExportAttr>();
5814
5815 if (M->hasAttr<DLLExportAttr>()) {
5816 DefineImplicitSpecialMember(*this, M, M->getLocation());
5817 ActOnFinishInlineFunctionDef(M);
5818 }
5819 }
Richard Smithbd305122012-12-11 01:14:52 +00005820 }
5821 }
5822
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00005823 if (HasMethodWithOverrideControl &&
5824 HasOverridingMethodWithoutOverrideControl) {
5825 // At least one method has the 'override' control declared.
5826 // Diagnose all other overridden methods which do not have 'override' specified on them.
5827 for (auto *M : Record->methods())
5828 DiagnoseAbsenceOfOverrideControl(M);
5829 }
Sebastian Redl08905022011-02-05 19:23:19 +00005830
John McCall95833f32014-02-27 20:30:49 +00005831 // ms_struct is a request to use the same ABI rules as MSVC. Check
5832 // whether this class uses any C++ features that are implemented
5833 // completely differently in MSVC, and if so, emit a diagnostic.
5834 // That diagnostic defaults to an error, but we allow projects to
5835 // map it down to a warning (or ignore it). It's a fairly common
5836 // practice among users of the ms_struct pragma to mass-annotate
5837 // headers, sweeping up a bunch of types that the project doesn't
5838 // really rely on MSVC-compatible layout for. We must therefore
5839 // support "ms_struct except for C++ stuff" as a secondary ABI.
5840 if (Record->isMsStruct(Context) &&
5841 (Record->isPolymorphic() || Record->getNumBases())) {
5842 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00005843 }
5844
Hans Wennborg17f9b442015-05-27 00:06:45 +00005845 checkClassLevelDLLAttribute(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005846}
5847
Richard Smith41c35d62013-11-27 03:39:20 +00005848/// Look up the special member function that would be called by a special
5849/// member function for a subobject of class type.
5850///
5851/// \param Class The class type of the subobject.
5852/// \param CSM The kind of special member function.
5853/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5854/// \param ConstRHS True if this is a copy operation with a const object
5855/// on its RHS, that is, if the argument to the outer special member
5856/// function is 'const' and this is not a field marked 'mutable'.
5857static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
5858 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5859 unsigned FieldQuals, bool ConstRHS) {
5860 unsigned LHSQuals = 0;
5861 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5862 LHSQuals = FieldQuals;
5863
5864 unsigned RHSQuals = FieldQuals;
5865 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5866 RHSQuals = 0;
5867 else if (ConstRHS)
5868 RHSQuals |= Qualifiers::Const;
5869
5870 return S.LookupSpecialMember(Class, CSM,
5871 RHSQuals & Qualifiers::Const,
5872 RHSQuals & Qualifiers::Volatile,
5873 false,
5874 LHSQuals & Qualifiers::Const,
5875 LHSQuals & Qualifiers::Volatile);
5876}
5877
Richard Smith80a47022016-06-29 01:10:27 +00005878class Sema::InheritedConstructorInfo {
Richard Smith5179eb72016-06-28 19:03:57 +00005879 Sema &S;
5880 SourceLocation UseLoc;
Richard Smith5179eb72016-06-28 19:03:57 +00005881
5882 /// A mapping from the base classes through which the constructor was
5883 /// inherited to the using shadow declaration in that base class (or a null
5884 /// pointer if the constructor was declared in that base class).
5885 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
5886 InheritedFromBases;
5887
Richard Smith80a47022016-06-29 01:10:27 +00005888public:
Richard Smith5179eb72016-06-28 19:03:57 +00005889 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
5890 ConstructorUsingShadowDecl *Shadow)
Richard Smith80a47022016-06-29 01:10:27 +00005891 : S(S), UseLoc(UseLoc) {
Richard Smith5179eb72016-06-28 19:03:57 +00005892 bool DiagnosedMultipleConstructedBases = false;
5893 CXXRecordDecl *ConstructedBase = nullptr;
5894 UsingDecl *ConstructedBaseUsing = nullptr;
5895
5896 // Find the set of such base class subobjects and check that there's a
5897 // unique constructed subobject.
5898 for (auto *D : Shadow->redecls()) {
5899 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
5900 auto *DNominatedBase = DShadow->getNominatedBaseClass();
5901 auto *DConstructedBase = DShadow->getConstructedBaseClass();
5902
5903 InheritedFromBases.insert(
5904 std::make_pair(DNominatedBase->getCanonicalDecl(),
5905 DShadow->getNominatedBaseClassShadowDecl()));
5906 if (DShadow->constructsVirtualBase())
5907 InheritedFromBases.insert(
5908 std::make_pair(DConstructedBase->getCanonicalDecl(),
5909 DShadow->getConstructedBaseClassShadowDecl()));
5910 else
5911 assert(DNominatedBase == DConstructedBase);
5912
5913 // [class.inhctor.init]p2:
5914 // If the constructor was inherited from multiple base class subobjects
5915 // of type B, the program is ill-formed.
5916 if (!ConstructedBase) {
5917 ConstructedBase = DConstructedBase;
5918 ConstructedBaseUsing = D->getUsingDecl();
5919 } else if (ConstructedBase != DConstructedBase &&
5920 !Shadow->isInvalidDecl()) {
5921 if (!DiagnosedMultipleConstructedBases) {
5922 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
5923 << Shadow->getTargetDecl();
5924 S.Diag(ConstructedBaseUsing->getLocation(),
5925 diag::note_ambiguous_inherited_constructor_using)
5926 << ConstructedBase;
5927 DiagnosedMultipleConstructedBases = true;
5928 }
5929 S.Diag(D->getUsingDecl()->getLocation(),
5930 diag::note_ambiguous_inherited_constructor_using)
5931 << DConstructedBase;
5932 }
5933 }
5934
5935 if (DiagnosedMultipleConstructedBases)
5936 Shadow->setInvalidDecl();
5937 }
5938
5939 /// Find the constructor to use for inherited construction of a base class,
5940 /// and whether that base class constructor inherits the constructor from a
5941 /// virtual base class (in which case it won't actually invoke it).
5942 std::pair<CXXConstructorDecl *, bool>
5943 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
5944 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
5945 if (It == InheritedFromBases.end())
5946 return std::make_pair(nullptr, false);
5947
5948 // This is an intermediary class.
5949 if (It->second)
5950 return std::make_pair(
5951 S.findInheritingConstructor(UseLoc, Ctor, It->second),
5952 It->second->constructsVirtualBase());
5953
5954 // This is the base class from which the constructor was inherited.
5955 return std::make_pair(Ctor, false);
5956 }
5957};
Richard Smith5179eb72016-06-28 19:03:57 +00005958
Richard Smithb5800092012-06-10 05:43:50 +00005959/// Is the special member function which would be selected to perform the
5960/// specified operation on the specified class type a constexpr constructor?
Richard Smith5179eb72016-06-28 19:03:57 +00005961static bool
5962specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5963 Sema::CXXSpecialMember CSM, unsigned Quals,
5964 bool ConstRHS,
5965 CXXConstructorDecl *InheritedCtor = nullptr,
Richard Smith80a47022016-06-29 01:10:27 +00005966 Sema::InheritedConstructorInfo *Inherited = nullptr) {
Richard Smith5179eb72016-06-28 19:03:57 +00005967 // If we're inheriting a constructor, see if we need to call it for this base
5968 // class.
5969 if (InheritedCtor) {
5970 assert(CSM == Sema::CXXDefaultConstructor);
5971 auto BaseCtor =
5972 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
5973 if (BaseCtor)
5974 return BaseCtor->isConstexpr();
5975 }
5976
5977 if (CSM == Sema::CXXDefaultConstructor)
5978 return ClassDecl->hasConstexprDefaultConstructor();
5979
Richard Smithb5800092012-06-10 05:43:50 +00005980 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005981 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00005982 if (!SMOR || !SMOR->getMethod())
5983 // A constructor we wouldn't select can't be "involved in initializing"
5984 // anything.
5985 return true;
5986 return SMOR->getMethod()->isConstexpr();
5987}
5988
5989/// Determine whether the specified special member function would be constexpr
5990/// if it were implicitly defined.
Richard Smith5179eb72016-06-28 19:03:57 +00005991static bool defaultedSpecialMemberIsConstexpr(
5992 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
5993 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
Richard Smith80a47022016-06-29 01:10:27 +00005994 Sema::InheritedConstructorInfo *Inherited = nullptr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005995 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00005996 return false;
5997
5998 // C++11 [dcl.constexpr]p4:
5999 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00006000 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00006001 switch (CSM) {
6002 case Sema::CXXDefaultConstructor:
Richard Smith5179eb72016-06-28 19:03:57 +00006003 if (Inherited)
6004 break;
Richard Smith4086a132012-06-10 07:07:24 +00006005 // Since default constructor lookup is essentially trivial (and cannot
6006 // involve, for instance, template instantiation), we compute whether a
6007 // defaulted default constructor is constexpr directly within CXXRecordDecl.
6008 //
6009 // This is important for performance; we need to know whether the default
6010 // constructor is constexpr to determine whether the type is a literal type.
6011 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6012
Richard Smithb5800092012-06-10 05:43:50 +00006013 case Sema::CXXCopyConstructor:
6014 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00006015 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00006016 break;
6017
6018 case Sema::CXXCopyAssignment:
6019 case Sema::CXXMoveAssignment:
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006020 if (!S.getLangOpts().CPlusPlus14)
Richard Smith99005e62013-05-07 03:19:20 +00006021 return false;
6022 // In C++1y, we need to perform overload resolution.
6023 Ctor = false;
6024 break;
6025
Richard Smithb5800092012-06-10 05:43:50 +00006026 case Sema::CXXDestructor:
6027 case Sema::CXXInvalid:
6028 return false;
6029 }
6030
6031 // -- if the class is a non-empty union, or for each non-empty anonymous
6032 // union member of a non-union class, exactly one non-static data member
6033 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00006034 //
6035 // If we squint, this is guaranteed, since exactly one non-static data member
6036 // will be initialized (if the constructor isn't deleted), we just don't know
6037 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00006038 if (Ctor && ClassDecl->isUnion())
Richard Smith5179eb72016-06-28 19:03:57 +00006039 return CSM == Sema::CXXDefaultConstructor
6040 ? ClassDecl->hasInClassInitializer() ||
6041 !ClassDecl->hasVariantMembers()
6042 : true;
Richard Smithb5800092012-06-10 05:43:50 +00006043
6044 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00006045 if (Ctor && ClassDecl->getNumVBases())
6046 return false;
6047
6048 // C++1y [class.copy]p26:
6049 // -- [the class] is a literal type, and
6050 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00006051 return false;
6052
6053 // -- every constructor involved in initializing [...] base class
6054 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00006055 // -- the assignment operator selected to copy/move each direct base
6056 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00006057 for (const auto &B : ClassDecl->bases()) {
6058 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00006059 if (!BaseType) continue;
6060
6061 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith5179eb72016-06-28 19:03:57 +00006062 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6063 InheritedCtor, Inherited))
Richard Smithb5800092012-06-10 05:43:50 +00006064 return false;
6065 }
6066
6067 // -- every constructor involved in initializing non-static data members
6068 // [...] shall be a constexpr constructor;
6069 // -- every non-static data member and base class sub-object shall be
6070 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00006071 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00006072 // thereof), the assignment operator selected to copy/move that member is
6073 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006074 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00006075 if (F->isInvalidDecl())
6076 continue;
Richard Smith5179eb72016-06-28 19:03:57 +00006077 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6078 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00006079 QualType BaseType = S.Context.getBaseElementType(F->getType());
6080 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00006081 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00006082 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6083 BaseType.getCVRQualifiers(),
6084 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00006085 return false;
Richard Smith5179eb72016-06-28 19:03:57 +00006086 } else if (CSM == Sema::CXXDefaultConstructor) {
6087 return false;
Richard Smithb5800092012-06-10 05:43:50 +00006088 }
6089 }
6090
6091 // All OK, it's constexpr!
6092 return true;
6093}
6094
Richard Smithd3b5c9082012-07-27 04:22:15 +00006095static Sema::ImplicitExceptionSpecification
6096computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6097 switch (S.getSpecialMember(MD)) {
6098 case Sema::CXXDefaultConstructor:
6099 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
6100 case Sema::CXXCopyConstructor:
6101 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
6102 case Sema::CXXCopyAssignment:
6103 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
6104 case Sema::CXXMoveConstructor:
6105 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
6106 case Sema::CXXMoveAssignment:
6107 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
6108 case Sema::CXXDestructor:
6109 return S.ComputeDefaultedDtorExceptionSpec(MD);
6110 case Sema::CXXInvalid:
6111 break;
6112 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00006113 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
6114 "only special members have implicit exception specs");
Richard Smith5179eb72016-06-28 19:03:57 +00006115 return S.ComputeInheritingCtorExceptionSpec(Loc,
6116 cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00006117}
6118
Reid Kleckner78af0702013-08-27 23:08:25 +00006119static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6120 CXXMethodDecl *MD) {
6121 FunctionProtoType::ExtProtoInfo EPI;
6122
6123 // Build an exception specification pointing back at this member.
Richard Smith8acb4282014-07-31 21:57:55 +00006124 EPI.ExceptionSpec.Type = EST_Unevaluated;
6125 EPI.ExceptionSpec.SourceDecl = MD;
Reid Kleckner78af0702013-08-27 23:08:25 +00006126
6127 // Set the calling convention to the default for C++ instance methods.
6128 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6129 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6130 /*IsCXXMethod=*/true));
6131 return EPI;
6132}
6133
Richard Smithd3b5c9082012-07-27 04:22:15 +00006134void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6135 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6136 if (FPT->getExceptionSpecType() != EST_Unevaluated)
6137 return;
6138
Richard Smith7f782272012-07-30 23:48:14 +00006139 // Evaluate the exception specification.
Vitaly Bukaac10dcc2016-12-05 18:30:22 +00006140 auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6141 auto ESI = IES.getExceptionSpec();
Richard Smith564417a2014-03-20 21:47:22 +00006142
Richard Smith7f782272012-07-30 23:48:14 +00006143 // Update the type of the special member to use it.
Richard Smith8acb4282014-07-31 21:57:55 +00006144 UpdateExceptionSpec(MD, ESI);
Richard Smith7f782272012-07-30 23:48:14 +00006145
6146 // A user-provided destructor can be defined outside the class. When that
6147 // happens, be sure to update the exception specification on both
6148 // declarations.
6149 const FunctionProtoType *CanonicalFPT =
6150 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6151 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smith8acb4282014-07-31 21:57:55 +00006152 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00006153}
6154
Richard Smithb9e90b12012-05-15 04:39:51 +00006155void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6156 CXXRecordDecl *RD = MD->getParent();
6157 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00006158
Richard Smithb9e90b12012-05-15 04:39:51 +00006159 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6160 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00006161
6162 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00006163 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00006164 bool First = MD == MD->getCanonicalDecl();
6165
6166 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00006167
6168 // C++11 [dcl.fct.def.default]p1:
6169 // A function that is explicitly defaulted shall
6170 // -- be a special member function (checked elsewhere),
6171 // -- have the same type (except for ref-qualifiers, and except that a
6172 // copy operation can take a non-const reference) as an implicit
6173 // declaration, and
6174 // -- not have default arguments.
6175 unsigned ExpectedParams = 1;
6176 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6177 ExpectedParams = 0;
6178 if (MD->getNumParams() != ExpectedParams) {
6179 // This also checks for default arguments: a copy or move constructor with a
6180 // default argument is classified as a default constructor, and assignment
6181 // operations and destructors can't have default arguments.
6182 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6183 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00006184 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00006185 } else if (MD->isVariadic()) {
6186 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6187 << CSM << MD->getSourceRange();
6188 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00006189 }
6190
Richard Smithb9e90b12012-05-15 04:39:51 +00006191 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00006192
Richard Smithb5800092012-06-10 05:43:50 +00006193 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00006194 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00006195 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00006196 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00006197 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00006198
Richard Smithb9e90b12012-05-15 04:39:51 +00006199 QualType ReturnType = Context.VoidTy;
6200 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6201 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00006202 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00006203 QualType ExpectedReturnType =
6204 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
6205 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6206 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6207 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6208 HadError = true;
6209 }
6210
6211 // A defaulted special member cannot have cv-qualifiers.
6212 if (Type->getTypeQuals()) {
6213 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006214 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
Richard Smithb9e90b12012-05-15 04:39:51 +00006215 HadError = true;
6216 }
6217 }
6218
6219 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00006220 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00006221 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00006222 if (ExpectedParams && ArgType->isReferenceType()) {
6223 // Argument must be reference to possibly-const T.
6224 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00006225 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00006226
6227 if (ReferentType.isVolatileQualified()) {
6228 Diag(MD->getLocation(),
6229 diag::err_defaulted_special_member_volatile_param) << CSM;
6230 HadError = true;
6231 }
6232
Richard Smithb5800092012-06-10 05:43:50 +00006233 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00006234 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6235 Diag(MD->getLocation(),
6236 diag::err_defaulted_special_member_copy_const_param)
6237 << (CSM == CXXCopyAssignment);
6238 // FIXME: Explain why this special member can't be const.
6239 } else {
6240 Diag(MD->getLocation(),
6241 diag::err_defaulted_special_member_move_const_param)
6242 << (CSM == CXXMoveAssignment);
6243 }
6244 HadError = true;
6245 }
Richard Smithb9e90b12012-05-15 04:39:51 +00006246 } else if (ExpectedParams) {
6247 // A copy assignment operator can take its argument by value, but a
6248 // defaulted one cannot.
6249 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00006250 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00006251 HadError = true;
6252 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00006253
Richard Smithcc36f692011-12-22 02:22:31 +00006254 // C++11 [dcl.fct.def.default]p2:
6255 // An explicitly-defaulted function may be declared constexpr only if it
6256 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00006257 // Do not apply this rule to members of class templates, since core issue 1358
6258 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00006259 // functions which cannot be constexpr (for non-constructors in C++11 and for
6260 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00006261 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6262 HasConstParam);
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006263 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
Richard Smith99005e62013-05-07 03:19:20 +00006264 : isa<CXXConstructorDecl>(MD)) &&
6265 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00006266 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6267 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00006268 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00006269 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00006270 }
Richard Smithbd305122012-12-11 01:14:52 +00006271
Richard Smithcc36f692011-12-22 02:22:31 +00006272 // and may have an explicit exception-specification only if it is compatible
6273 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00006274 if (Type->hasExceptionSpec()) {
6275 // Delay the check if this is the first declaration of the special member,
6276 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00006277 if (First) {
6278 // If the exception specification needs to be instantiated, do so now,
6279 // before we clobber it with an EST_Unevaluated specification below.
6280 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6281 InstantiateExceptionSpec(MD->getLocStart(), MD);
6282 Type = MD->getType()->getAs<FunctionProtoType>();
6283 }
Richard Smithbd305122012-12-11 01:14:52 +00006284 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00006285 } else
Richard Smithbd305122012-12-11 01:14:52 +00006286 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6287 }
Richard Smithcc36f692011-12-22 02:22:31 +00006288
6289 // If a function is explicitly defaulted on its first declaration,
6290 if (First) {
6291 // -- it is implicitly considered to be constexpr if the implicit
6292 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00006293 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00006294
Richard Smithb9e90b12012-05-15 04:39:51 +00006295 // -- it is implicitly considered to have the same exception-specification
6296 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00006297 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00006298 EPI.ExceptionSpec.Type = EST_Unevaluated;
6299 EPI.ExceptionSpec.SourceDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00006300 MD->setType(Context.getFunctionType(ReturnType,
Craig Topper5fc8fc22014-08-27 06:28:36 +00006301 llvm::makeArrayRef(&ArgType,
Jordan Rose5c382722013-03-08 21:51:21 +00006302 ExpectedParams),
6303 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00006304 }
6305
Richard Smithb9e90b12012-05-15 04:39:51 +00006306 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00006307 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00006308 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00006309 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00006310 // C++11 [dcl.fct.def.default]p4:
6311 // [For a] user-provided explicitly-defaulted function [...] if such a
6312 // function is implicitly defined as deleted, the program is ill-formed.
6313 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith80a47022016-06-29 01:10:27 +00006314 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00006315 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00006316 }
6317 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00006318
Richard Smithb9e90b12012-05-15 04:39:51 +00006319 if (HadError)
6320 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00006321}
6322
Richard Smithbd305122012-12-11 01:14:52 +00006323/// Check whether the exception specification provided for an
6324/// explicitly-defaulted special member matches the exception specification
6325/// that would have been generated for an implicit special member, per
6326/// C++11 [dcl.fct.def.default]p2.
6327void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6328 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
Richard Smith0b3a4622014-11-13 20:01:57 +00006329 // If the exception specification was explicitly specified but hadn't been
6330 // parsed when the method was defaulted, grab it now.
6331 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6332 SpecifiedType =
6333 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6334
Richard Smithbd305122012-12-11 01:14:52 +00006335 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00006336 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6337 /*IsCXXMethod=*/true);
6338 FunctionProtoType::ExtProtoInfo EPI(CC);
Vitaly Buka846b8f72016-12-05 19:25:00 +00006339 auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
6340 EPI.ExceptionSpec = IES.getExceptionSpec();
Richard Smithbd305122012-12-11 01:14:52 +00006341 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006342 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00006343
6344 // Ensure that it matches.
6345 CheckEquivalentExceptionSpec(
6346 PDiag(diag::err_incorrect_defaulted_exception_spec)
6347 << getSpecialMember(MD), PDiag(),
6348 ImplicitType, SourceLocation(),
6349 SpecifiedType, MD->getLocation());
6350}
6351
Alp Tokerae3a9442013-10-18 05:54:19 +00006352void Sema::CheckDelayedMemberExceptionSpecs() {
Richard Smith88f45492014-11-22 03:09:05 +00006353 decltype(DelayedExceptionSpecChecks) Checks;
6354 decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
Richard Smithbd305122012-12-11 01:14:52 +00006355
Richard Smith88f45492014-11-22 03:09:05 +00006356 std::swap(Checks, DelayedExceptionSpecChecks);
Alp Tokerae3a9442013-10-18 05:54:19 +00006357 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
6358
6359 // Perform any deferred checking of exception specifications for virtual
6360 // destructors.
Richard Smith88f45492014-11-22 03:09:05 +00006361 for (auto &Check : Checks)
6362 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
Alp Tokerae3a9442013-10-18 05:54:19 +00006363
6364 // Check that any explicitly-defaulted methods have exception specifications
6365 // compatible with their implicit exception specifications.
Richard Smith88f45492014-11-22 03:09:05 +00006366 for (auto &Spec : Specs)
6367 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
Richard Smithbd305122012-12-11 01:14:52 +00006368}
6369
Richard Smithd951a1d2012-02-18 02:02:13 +00006370namespace {
6371struct SpecialMemberDeletionInfo {
6372 Sema &S;
6373 CXXMethodDecl *MD;
6374 Sema::CXXSpecialMember CSM;
Richard Smith80a47022016-06-29 01:10:27 +00006375 Sema::InheritedConstructorInfo *ICI;
Richard Smith852265f2012-03-30 20:53:28 +00006376 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00006377
6378 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00006379 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00006380 SourceLocation Loc;
6381
6382 bool AllFieldsAreConst;
6383
6384 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith80a47022016-06-29 01:10:27 +00006385 Sema::CXXSpecialMember CSM,
6386 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6387 : S(S), MD(MD), CSM(CSM), ICI(ICI), Diagnose(Diagnose),
6388 IsConstructor(false), IsAssignment(false), IsMove(false),
6389 ConstArg(false), Loc(MD->getLocation()), AllFieldsAreConst(true) {
Richard Smithd951a1d2012-02-18 02:02:13 +00006390 switch (CSM) {
6391 case Sema::CXXDefaultConstructor:
6392 case Sema::CXXCopyConstructor:
6393 IsConstructor = true;
6394 break;
6395 case Sema::CXXMoveConstructor:
6396 IsConstructor = true;
6397 IsMove = true;
6398 break;
6399 case Sema::CXXCopyAssignment:
6400 IsAssignment = true;
6401 break;
6402 case Sema::CXXMoveAssignment:
6403 IsAssignment = true;
6404 IsMove = true;
6405 break;
6406 case Sema::CXXDestructor:
6407 break;
6408 case Sema::CXXInvalid:
6409 llvm_unreachable("invalid special member kind");
6410 }
6411
6412 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00006413 if (const ReferenceType *RT =
6414 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6415 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00006416 }
6417 }
6418
6419 bool inUnion() const { return MD->getParent()->isUnion(); }
6420
Richard Smith80a47022016-06-29 01:10:27 +00006421 Sema::CXXSpecialMember getEffectiveCSM() {
6422 return ICI ? Sema::CXXInvalid : CSM;
6423 }
6424
Richard Smithd951a1d2012-02-18 02:02:13 +00006425 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00006426 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00006427 unsigned Quals, bool IsMutable) {
6428 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6429 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00006430 }
6431
Richard Smith852265f2012-03-30 20:53:28 +00006432 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00006433
Richard Smith852265f2012-03-30 20:53:28 +00006434 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00006435 bool shouldDeleteForField(FieldDecl *FD);
6436 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00006437
Richard Smithaf136f82012-07-18 03:51:16 +00006438 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6439 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00006440 bool shouldDeleteForSubobjectCall(Subobject Subobj,
6441 Sema::SpecialMemberOverloadResult *SMOR,
6442 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00006443
6444 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00006445};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006446}
Richard Smithd951a1d2012-02-18 02:02:13 +00006447
John McCalld4274212012-04-09 20:53:23 +00006448/// Is the given special member inaccessible when used on the given
6449/// sub-object.
6450bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6451 CXXMethodDecl *target) {
6452 /// If we're operating on a base class, the object type is the
6453 /// type of this special member.
6454 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00006455 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00006456 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6457 objectTy = S.Context.getTypeDeclType(MD->getParent());
6458 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6459
6460 // If we're operating on a field, the object type is the type of the field.
6461 } else {
6462 objectTy = S.Context.getTypeDeclType(target->getParent());
6463 }
6464
6465 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6466}
6467
Richard Smith852265f2012-03-30 20:53:28 +00006468/// Check whether we should delete a special member due to the implicit
6469/// definition containing a call to a special member of a subobject.
6470bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6471 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
6472 bool IsDtorCallInCtor) {
6473 CXXMethodDecl *Decl = SMOR->getMethod();
6474 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6475
6476 int DiagKind = -1;
6477
6478 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6479 DiagKind = !Decl ? 0 : 1;
6480 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6481 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00006482 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00006483 DiagKind = 3;
6484 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6485 !Decl->isTrivial()) {
6486 // A member of a union must have a trivial corresponding special member.
6487 // As a weird special case, a destructor call from a union's constructor
6488 // must be accessible and non-deleted, but need not be trivial. Such a
6489 // destructor is never actually called, but is semantically checked as
6490 // if it were.
6491 DiagKind = 4;
6492 }
6493
6494 if (DiagKind == -1)
6495 return false;
6496
6497 if (Diagnose) {
6498 if (Field) {
6499 S.Diag(Field->getLocation(),
6500 diag::note_deleted_special_member_class_subobject)
Richard Smith80a47022016-06-29 01:10:27 +00006501 << getEffectiveCSM() << MD->getParent() << /*IsField*/true
Richard Smith852265f2012-03-30 20:53:28 +00006502 << Field << DiagKind << IsDtorCallInCtor;
6503 } else {
6504 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6505 S.Diag(Base->getLocStart(),
6506 diag::note_deleted_special_member_class_subobject)
Richard Smith80a47022016-06-29 01:10:27 +00006507 << getEffectiveCSM() << MD->getParent() << /*IsField*/false
Richard Smith852265f2012-03-30 20:53:28 +00006508 << Base->getType() << DiagKind << IsDtorCallInCtor;
6509 }
6510
6511 if (DiagKind == 1)
6512 S.NoteDeletedFunction(Decl);
6513 // FIXME: Explain inaccessibility if DiagKind == 3.
6514 }
6515
6516 return true;
6517}
6518
Richard Smith921bd202012-02-26 09:11:52 +00006519/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00006520/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00006521bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00006522 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00006523 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00006524 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00006525
6526 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00006527 // -- any direct or virtual base class, or non-static data member with no
6528 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00006529 // either M has no default constructor or overload resolution as applied
6530 // to M's default constructor results in an ambiguity or in a function
6531 // that is deleted or inaccessible
6532 // C++11 [class.copy]p11, C++11 [class.copy]p23:
6533 // -- a direct or virtual base class B that cannot be copied/moved because
6534 // overload resolution, as applied to B's corresponding special member,
6535 // results in an ambiguity or a function that is deleted or inaccessible
6536 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00006537 // C++11 [class.dtor]p5:
6538 // -- any direct or virtual base class [...] has a type with a destructor
6539 // that is deleted or inaccessible
6540 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006541 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00006542 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6543 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006544 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00006545
Richard Smith852265f2012-03-30 20:53:28 +00006546 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6547 // -- any direct or virtual base class or non-static data member has a
6548 // type with a destructor that is deleted or inaccessible
6549 if (IsConstructor) {
6550 Sema::SpecialMemberOverloadResult *SMOR =
6551 S.LookupSpecialMember(Class, Sema::CXXDestructor,
6552 false, false, false, false, false);
6553 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
6554 return true;
6555 }
6556
Richard Smith921bd202012-02-26 09:11:52 +00006557 return false;
6558}
6559
6560/// Check whether we should delete a special member function due to the class
6561/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00006562bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006563 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Serge Pavlov5c49e1a2015-12-28 19:40:14 +00006564 // If program is correct, BaseClass cannot be null, but if it is, the error
6565 // must be reported elsewhere.
Richard Smith80a47022016-06-29 01:10:27 +00006566 if (!BaseClass)
6567 return false;
6568 // If we have an inheriting constructor, check whether we're calling an
6569 // inherited constructor instead of a default constructor.
6570 if (ICI) {
6571 assert(CSM == Sema::CXXDefaultConstructor);
6572 auto *BaseCtor =
6573 ICI->findConstructorForBase(BaseClass, cast<CXXConstructorDecl>(MD)
6574 ->getInheritedConstructor()
6575 .getConstructor())
6576 .first;
6577 if (BaseCtor) {
6578 if (BaseCtor->isDeleted() && Diagnose) {
6579 S.Diag(Base->getLocStart(),
6580 diag::note_deleted_special_member_class_subobject)
6581 << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6582 << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false;
6583 S.NoteDeletedFunction(BaseCtor);
6584 }
6585 return BaseCtor->isDeleted();
6586 }
6587 }
6588 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00006589}
6590
6591/// Check whether we should delete a special member function due to the class
6592/// having a particular non-static data member.
6593bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
6594 QualType FieldType = S.Context.getBaseElementType(FD->getType());
6595 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
6596
6597 if (CSM == Sema::CXXDefaultConstructor) {
6598 // For a default constructor, all references must be initialized in-class
6599 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00006600 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
6601 if (Diagnose)
6602 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smith80a47022016-06-29 01:10:27 +00006603 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00006604 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006605 }
Richard Smith619ecdc2012-02-27 06:07:25 +00006606 // C++11 [class.ctor]p5: any non-variant non-static data member of
6607 // const-qualified type (or array thereof) with no
6608 // brace-or-equal-initializer does not have a user-provided default
6609 // constructor.
6610 if (!inUnion() && FieldType.isConstQualified() &&
6611 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00006612 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
6613 if (Diagnose)
6614 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smith80a47022016-06-29 01:10:27 +00006615 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00006616 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006617 }
6618
6619 if (inUnion() && !FieldType.isConstQualified())
6620 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00006621 } else if (CSM == Sema::CXXCopyConstructor) {
6622 // For a copy constructor, data members must not be of rvalue reference
6623 // type.
Richard Smith852265f2012-03-30 20:53:28 +00006624 if (FieldType->isRValueReferenceType()) {
6625 if (Diagnose)
6626 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
6627 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00006628 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006629 }
Richard Smithd951a1d2012-02-18 02:02:13 +00006630 } else if (IsAssignment) {
6631 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00006632 if (FieldType->isReferenceType()) {
6633 if (Diagnose)
6634 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6635 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00006636 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006637 }
6638 if (!FieldRecord && FieldType.isConstQualified()) {
6639 // C++11 [class.copy]p23:
6640 // -- a non-static data member of const non-class type (or array thereof)
6641 if (Diagnose)
6642 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00006643 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00006644 return true;
6645 }
Richard Smithd951a1d2012-02-18 02:02:13 +00006646 }
6647
6648 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00006649 // Some additional restrictions exist on the variant members.
6650 if (!inUnion() && FieldRecord->isUnion() &&
6651 FieldRecord->isAnonymousStructOrUnion()) {
6652 bool AllVariantFieldsAreConst = true;
6653
Richard Smith5704fe82012-03-29 19:00:10 +00006654 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006655 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00006656 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00006657
6658 if (!UnionFieldType.isConstQualified())
6659 AllVariantFieldsAreConst = false;
6660
Richard Smith921bd202012-02-26 09:11:52 +00006661 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
6662 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006663 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00006664 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00006665 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00006666 }
6667
6668 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00006669 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006670 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00006671 if (Diagnose)
6672 S.Diag(FieldRecord->getLocation(),
6673 diag::note_deleted_default_ctor_all_const)
Richard Smith80a47022016-06-29 01:10:27 +00006674 << !!ICI << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00006675 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006676 }
Richard Smithd951a1d2012-02-18 02:02:13 +00006677
Richard Smith5704fe82012-03-29 19:00:10 +00006678 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00006679 // This is technically non-conformant, but sanity demands it.
6680 return false;
6681 }
6682
Richard Smithaf136f82012-07-18 03:51:16 +00006683 if (shouldDeleteForClassSubobject(FieldRecord, FD,
6684 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00006685 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00006686 }
6687
6688 return false;
6689}
6690
6691/// C++11 [class.ctor] p5:
6692/// A defaulted default constructor for a class X is defined as deleted if
6693/// X is a union and all of its variant members are of const-qualified type.
6694bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00006695 // This is a silly definition, because it gives an empty union a deleted
6696 // default constructor. Don't do that.
Richard Smith5e052982016-11-08 01:07:26 +00006697 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
6698 bool AnyFields = false;
6699 for (auto *F : MD->getParent()->fields())
6700 if ((AnyFields = !F->isUnnamedBitfield()))
6701 break;
6702 if (!AnyFields)
6703 return false;
Richard Smith852265f2012-03-30 20:53:28 +00006704 if (Diagnose)
6705 S.Diag(MD->getParent()->getLocation(),
6706 diag::note_deleted_default_ctor_all_const)
Richard Smith80a47022016-06-29 01:10:27 +00006707 << !!ICI << MD->getParent() << /*not anonymous union*/0;
Richard Smith852265f2012-03-30 20:53:28 +00006708 return true;
6709 }
6710 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00006711}
6712
6713/// Determine whether a defaulted special member function should be defined as
6714/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
6715/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00006716bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
Richard Smith80a47022016-06-29 01:10:27 +00006717 InheritedConstructorInfo *ICI,
Richard Smith852265f2012-03-30 20:53:28 +00006718 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00006719 if (MD->isInvalidDecl())
6720 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00006721 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00006722 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006723 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00006724 return false;
6725
Richard Smithd951a1d2012-02-18 02:02:13 +00006726 // C++11 [expr.lambda.prim]p19:
6727 // The closure type associated with a lambda-expression has a
6728 // deleted (8.4.3) default constructor and a deleted copy
6729 // assignment operator.
6730 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00006731 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
6732 if (Diagnose)
6733 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00006734 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006735 }
6736
Richard Smith6f1e2c62012-04-02 20:59:25 +00006737 // For an anonymous struct or union, the copy and assignment special members
6738 // will never be used, so skip the check. For an anonymous union declared at
6739 // namespace scope, the constructor and destructor are used.
6740 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
6741 RD->isAnonymousStructOrUnion())
6742 return false;
6743
Richard Smith852265f2012-03-30 20:53:28 +00006744 // C++11 [class.copy]p7, p18:
6745 // If the class definition declares a move constructor or move assignment
6746 // operator, an implicitly declared copy constructor or copy assignment
6747 // operator is defined as deleted.
6748 if (MD->isImplicit() &&
6749 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006750 CXXMethodDecl *UserDeclaredMove = nullptr;
Richard Smith852265f2012-03-30 20:53:28 +00006751
Peter Collingbourne66bfcb32016-11-19 00:30:56 +00006752 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
6753 // deletion of the corresponding copy operation, not both copy operations.
6754 // MSVC 2015 has adopted the standards conforming behavior.
6755 bool DeletesOnlyMatchingCopy =
6756 getLangOpts().MSVCCompat &&
6757 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
6758
Richard Smith852265f2012-03-30 20:53:28 +00006759 if (RD->hasUserDeclaredMoveConstructor() &&
Peter Collingbourne66bfcb32016-11-19 00:30:56 +00006760 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00006761 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00006762
6763 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006764 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00006765 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006766 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00006767 break;
6768 }
6769 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006770 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00006771 } else if (RD->hasUserDeclaredMoveAssignment() &&
Peter Collingbourne66bfcb32016-11-19 00:30:56 +00006772 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00006773 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00006774
6775 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00006776 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00006777 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00006778 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00006779 break;
6780 }
6781 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006782 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00006783 }
6784
6785 if (UserDeclaredMove) {
6786 Diag(UserDeclaredMove->getLocation(),
6787 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00006788 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00006789 << UserDeclaredMove->isMoveAssignmentOperator();
6790 return true;
6791 }
6792 }
Alexis Huntd6da8762011-10-10 06:18:57 +00006793
Richard Smith6f1e2c62012-04-02 20:59:25 +00006794 // Do access control from the special member function
6795 ContextRAII MethodContext(*this, MD);
6796
Richard Smith921bd202012-02-26 09:11:52 +00006797 // C++11 [class.dtor]p5:
6798 // -- for a virtual destructor, lookup of the non-array deallocation function
6799 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00006800 if (CSM == CXXDestructor && MD->isVirtual()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006801 FunctionDecl *OperatorDelete = nullptr;
Richard Smith921bd202012-02-26 09:11:52 +00006802 DeclarationName Name =
6803 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6804 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smithb2f0f052016-10-10 18:54:32 +00006805 OperatorDelete, /*Diagnose*/false)) {
Richard Smith852265f2012-03-30 20:53:28 +00006806 if (Diagnose)
6807 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00006808 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006809 }
Richard Smith921bd202012-02-26 09:11:52 +00006810 }
6811
Richard Smith80a47022016-06-29 01:10:27 +00006812 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00006813
Aaron Ballman574705e2014-03-13 15:41:46 +00006814 for (auto &BI : RD->bases())
Richard Smith0786d5b2016-08-31 20:37:39 +00006815 if ((SMI.IsAssignment || !BI.isVirtual()) &&
Aaron Ballman574705e2014-03-13 15:41:46 +00006816 SMI.shouldDeleteForBase(&BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00006817 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00006818
Richard Smithd1627032013-07-22 18:06:23 +00006819 // Per DR1611, do not consider virtual bases of constructors of abstract
Richard Smith0786d5b2016-08-31 20:37:39 +00006820 // classes, since we are not going to construct them. For assignment
6821 // operators, we only assign (and thus only consider) direct bases.
6822 if ((!RD->isAbstract() || !SMI.IsConstructor) && !SMI.IsAssignment) {
Aaron Ballman445a9392014-03-13 16:15:17 +00006823 for (auto &BI : RD->vbases())
6824 if (SMI.shouldDeleteForBase(&BI))
Richard Smithbc46e432013-07-22 02:56:56 +00006825 return true;
6826 }
Alexis Huntea6f0322011-05-11 22:34:38 +00006827
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006828 for (auto *FI : RD->fields())
Richard Smithd951a1d2012-02-18 02:02:13 +00006829 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006830 SMI.shouldDeleteForField(FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00006831 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00006832
Richard Smithd951a1d2012-02-18 02:02:13 +00006833 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00006834 return true;
6835
Eli Bendersky9a220fc2014-09-29 20:38:29 +00006836 if (getLangOpts().CUDA) {
6837 // We should delete the special member in CUDA mode if target inference
6838 // failed.
6839 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
6840 Diagnose);
6841 }
6842
Alexis Huntea6f0322011-05-11 22:34:38 +00006843 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006844}
6845
Richard Smith92f241f2012-12-08 02:53:02 +00006846/// Perform lookup for a special member of the specified kind, and determine
6847/// whether it is trivial. If the triviality can be determined without the
6848/// lookup, skip it. This is intended for use when determining whether a
6849/// special member of a containing object is trivial, and thus does not ever
6850/// perform overload resolution for default constructors.
6851///
6852/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
6853/// member that was most likely to be intended to be trivial, if any.
6854static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
6855 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00006856 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00006857 if (Selected)
Craig Topperc3ec1492014-05-26 06:22:03 +00006858 *Selected = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00006859
6860 switch (CSM) {
6861 case Sema::CXXInvalid:
6862 llvm_unreachable("not a special member");
6863
6864 case Sema::CXXDefaultConstructor:
6865 // C++11 [class.ctor]p5:
6866 // A default constructor is trivial if:
6867 // - all the [direct subobjects] have trivial default constructors
6868 //
6869 // Note, no overload resolution is performed in this case.
6870 if (RD->hasTrivialDefaultConstructor())
6871 return true;
6872
6873 if (Selected) {
6874 // If there's a default constructor which could have been trivial, dig it
6875 // out. Otherwise, if there's any user-provided default constructor, point
6876 // to that as an example of why there's not a trivial one.
Craig Topperc3ec1492014-05-26 06:22:03 +00006877 CXXConstructorDecl *DefCtor = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00006878 if (RD->needsImplicitDefaultConstructor())
6879 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006880 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00006881 if (!CI->isDefaultConstructor())
6882 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006883 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00006884 if (!DefCtor->isUserProvided())
6885 break;
6886 }
6887
6888 *Selected = DefCtor;
6889 }
6890
6891 return false;
6892
6893 case Sema::CXXDestructor:
6894 // C++11 [class.dtor]p5:
6895 // A destructor is trivial if:
6896 // - all the direct [subobjects] have trivial destructors
6897 if (RD->hasTrivialDestructor())
6898 return true;
6899
6900 if (Selected) {
6901 if (RD->needsImplicitDestructor())
6902 S.DeclareImplicitDestructor(RD);
6903 *Selected = RD->getDestructor();
6904 }
6905
6906 return false;
6907
6908 case Sema::CXXCopyConstructor:
6909 // C++11 [class.copy]p12:
6910 // A copy constructor is trivial if:
6911 // - the constructor selected to copy each direct [subobject] is trivial
6912 if (RD->hasTrivialCopyConstructor()) {
6913 if (Quals == Qualifiers::Const)
6914 // We must either select the trivial copy constructor or reach an
6915 // ambiguity; no need to actually perform overload resolution.
6916 return true;
6917 } else if (!Selected) {
6918 return false;
6919 }
6920 // In C++98, we are not supposed to perform overload resolution here, but we
6921 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
6922 // cases like B as having a non-trivial copy constructor:
6923 // struct A { template<typename T> A(T&); };
6924 // struct B { mutable A a; };
6925 goto NeedOverloadResolution;
6926
6927 case Sema::CXXCopyAssignment:
6928 // C++11 [class.copy]p25:
6929 // A copy assignment operator is trivial if:
6930 // - the assignment operator selected to copy each direct [subobject] is
6931 // trivial
6932 if (RD->hasTrivialCopyAssignment()) {
6933 if (Quals == Qualifiers::Const)
6934 return true;
6935 } else if (!Selected) {
6936 return false;
6937 }
6938 // In C++98, we are not supposed to perform overload resolution here, but we
6939 // treat that as a language defect.
6940 goto NeedOverloadResolution;
6941
6942 case Sema::CXXMoveConstructor:
6943 case Sema::CXXMoveAssignment:
6944 NeedOverloadResolution:
6945 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00006946 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00006947
6948 // The standard doesn't describe how to behave if the lookup is ambiguous.
6949 // We treat it as not making the member non-trivial, just like the standard
6950 // mandates for the default constructor. This should rarely matter, because
6951 // the member will also be deleted.
6952 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6953 return true;
6954
6955 if (!SMOR->getMethod()) {
6956 assert(SMOR->getKind() ==
6957 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
6958 return false;
6959 }
6960
6961 // We deliberately don't check if we found a deleted special member. We're
6962 // not supposed to!
6963 if (Selected)
6964 *Selected = SMOR->getMethod();
6965 return SMOR->getMethod()->isTrivial();
6966 }
6967
6968 llvm_unreachable("unknown special method kind");
6969}
6970
Benjamin Kramer3e350262013-02-15 12:30:38 +00006971static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006972 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00006973 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006974 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00006975
6976 // Look for constructor templates.
6977 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
6978 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
6979 if (CXXConstructorDecl *CD =
6980 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
6981 return CD;
6982 }
6983
Craig Topperc3ec1492014-05-26 06:22:03 +00006984 return nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00006985}
6986
6987/// The kind of subobject we are checking for triviality. The values of this
6988/// enumeration are used in diagnostics.
6989enum TrivialSubobjectKind {
6990 /// The subobject is a base class.
6991 TSK_BaseClass,
6992 /// The subobject is a non-static data member.
6993 TSK_Field,
6994 /// The object is actually the complete object.
6995 TSK_CompleteObject
6996};
6997
6998/// Check whether the special member selected for a given type would be trivial.
6999static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00007000 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00007001 Sema::CXXSpecialMember CSM,
7002 TrivialSubobjectKind Kind,
7003 bool Diagnose) {
7004 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7005 if (!SubRD)
7006 return true;
7007
7008 CXXMethodDecl *Selected;
7009 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Craig Topperc3ec1492014-05-26 06:22:03 +00007010 ConstRHS, Diagnose ? &Selected : nullptr))
Richard Smith92f241f2012-12-08 02:53:02 +00007011 return true;
7012
7013 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00007014 if (ConstRHS)
7015 SubType.addConst();
7016
Richard Smith92f241f2012-12-08 02:53:02 +00007017 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7018 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7019 << Kind << SubType.getUnqualifiedType();
7020 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7021 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7022 } else if (!Selected)
7023 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7024 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7025 else if (Selected->isUserProvided()) {
7026 if (Kind == TSK_CompleteObject)
7027 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7028 << Kind << SubType.getUnqualifiedType() << CSM;
7029 else {
7030 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7031 << Kind << SubType.getUnqualifiedType() << CSM;
7032 S.Diag(Selected->getLocation(), diag::note_declared_at);
7033 }
7034 } else {
7035 if (Kind != TSK_CompleteObject)
7036 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7037 << Kind << SubType.getUnqualifiedType() << CSM;
7038
7039 // Explain why the defaulted or deleted special member isn't trivial.
7040 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
7041 }
7042 }
7043
7044 return false;
7045}
7046
7047/// Check whether the members of a class type allow a special member to be
7048/// trivial.
7049static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7050 Sema::CXXSpecialMember CSM,
7051 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007052 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00007053 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7054 continue;
7055
7056 QualType FieldType = S.Context.getBaseElementType(FI->getType());
7057
7058 // Pretend anonymous struct or union members are members of this class.
7059 if (FI->isAnonymousStructOrUnion()) {
7060 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7061 CSM, ConstArg, Diagnose))
7062 return false;
7063 continue;
7064 }
7065
7066 // C++11 [class.ctor]p5:
7067 // A default constructor is trivial if [...]
7068 // -- no non-static data member of its class has a
7069 // brace-or-equal-initializer
7070 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7071 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007072 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00007073 return false;
7074 }
7075
7076 // Objective C ARC 4.3.5:
7077 // [...] nontrivally ownership-qualified types are [...] not trivially
7078 // default constructible, copy constructible, move constructible, copy
7079 // assignable, move assignable, or destructible [...]
7080 if (S.getLangOpts().ObjCAutoRefCount &&
7081 FieldType.hasNonTrivialObjCLifetime()) {
7082 if (Diagnose)
7083 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7084 << RD << FieldType.getObjCLifetime();
7085 return false;
7086 }
7087
Richard Smith41c35d62013-11-27 03:39:20 +00007088 bool ConstRHS = ConstArg && !FI->isMutable();
7089 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7090 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00007091 return false;
7092 }
7093
7094 return true;
7095}
7096
7097/// Diagnose why the specified class does not have a trivial special member of
7098/// the given kind.
7099void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7100 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00007101
Richard Smith41c35d62013-11-27 03:39:20 +00007102 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7103 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00007104 TSK_CompleteObject, /*Diagnose*/true);
7105}
7106
7107/// Determine whether a defaulted or deleted special member function is trivial,
7108/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7109/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7110bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7111 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00007112 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7113
7114 CXXRecordDecl *RD = MD->getParent();
7115
7116 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00007117
Richard Smith2002bfe2013-11-04 02:02:27 +00007118 // C++11 [class.copy]p12, p25: [DR1593]
7119 // A [special member] is trivial if [...] its parameter-type-list is
7120 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00007121 switch (CSM) {
7122 case CXXDefaultConstructor:
7123 case CXXDestructor:
7124 // Trivial default constructors and destructors cannot have parameters.
7125 break;
7126
7127 case CXXCopyConstructor:
7128 case CXXCopyAssignment: {
7129 // Trivial copy operations always have const, non-volatile parameter types.
7130 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00007131 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00007132 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7133 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7134 if (Diagnose)
7135 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7136 << Param0->getSourceRange() << Param0->getType()
7137 << Context.getLValueReferenceType(
7138 Context.getRecordType(RD).withConst());
7139 return false;
7140 }
7141 break;
7142 }
7143
7144 case CXXMoveConstructor:
7145 case CXXMoveAssignment: {
7146 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00007147 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00007148 const RValueReferenceType *RT =
7149 Param0->getType()->getAs<RValueReferenceType>();
7150 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7151 if (Diagnose)
7152 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7153 << Param0->getSourceRange() << Param0->getType()
7154 << Context.getRValueReferenceType(Context.getRecordType(RD));
7155 return false;
7156 }
7157 break;
7158 }
7159
7160 case CXXInvalid:
7161 llvm_unreachable("not a special member");
7162 }
7163
Richard Smith92f241f2012-12-08 02:53:02 +00007164 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7165 if (Diagnose)
7166 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7167 diag::note_nontrivial_default_arg)
7168 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7169 return false;
7170 }
7171 if (MD->isVariadic()) {
7172 if (Diagnose)
7173 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7174 return false;
7175 }
7176
7177 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7178 // A copy/move [constructor or assignment operator] is trivial if
7179 // -- the [member] selected to copy/move each direct base class subobject
7180 // is trivial
7181 //
7182 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7183 // A [default constructor or destructor] is trivial if
7184 // -- all the direct base classes have trivial [default constructors or
7185 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00007186 for (const auto &BI : RD->bases())
7187 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00007188 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00007189 return false;
7190
7191 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7192 // A copy/move [constructor or assignment operator] for a class X is
7193 // trivial if
7194 // -- for each non-static data member of X that is of class type (or array
7195 // thereof), the constructor selected to copy/move that member is
7196 // trivial
7197 //
7198 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7199 // A [default constructor or destructor] is trivial if
7200 // -- for all of the non-static data members of its class that are of class
7201 // type (or array thereof), each such class has a trivial [default
7202 // constructor or destructor]
7203 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
7204 return false;
7205
7206 // C++11 [class.dtor]p5:
7207 // A destructor is trivial if [...]
7208 // -- the destructor is not virtual
7209 if (CSM == CXXDestructor && MD->isVirtual()) {
7210 if (Diagnose)
7211 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7212 return false;
7213 }
7214
7215 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7216 // A [special member] for class X is trivial if [...]
7217 // -- class X has no virtual functions and no virtual base classes
7218 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7219 if (!Diagnose)
7220 return false;
7221
7222 if (RD->getNumVBases()) {
7223 // Check for virtual bases. We already know that the corresponding
7224 // member in all bases is trivial, so vbases must all be direct.
7225 CXXBaseSpecifier &BS = *RD->vbases_begin();
7226 assert(BS.isVirtual());
7227 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
7228 return false;
7229 }
7230
7231 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00007232 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00007233 if (MI->isVirtual()) {
7234 SourceLocation MLoc = MI->getLocStart();
7235 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7236 return false;
7237 }
7238 }
7239
7240 llvm_unreachable("dynamic class with no vbases and no virtual functions");
7241 }
7242
7243 // Looks like it's trivial!
7244 return true;
7245}
7246
Benjamin Kramer024e6192011-03-04 13:12:48 +00007247namespace {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007248struct FindHiddenVirtualMethod {
7249 Sema *S;
7250 CXXMethodDecl *Method;
7251 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7252 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007253
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007254private:
7255 /// Check whether any most overriden method from MD in Methods
7256 static bool CheckMostOverridenMethods(
7257 const CXXMethodDecl *MD,
7258 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7259 if (MD->size_overridden_methods() == 0)
7260 return Methods.count(MD->getCanonicalDecl());
7261 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7262 E = MD->end_overridden_methods();
7263 I != E; ++I)
7264 if (CheckMostOverridenMethods(*I, Methods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007265 return true;
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007266 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007267 }
7268
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007269public:
7270 /// Member lookup function that determines whether a given C++
7271 /// method overloads virtual methods in a base class without overriding any,
7272 /// to be used with CXXRecordDecl::lookupInBases().
7273 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7274 RecordDecl *BaseRecord =
7275 Specifier->getType()->getAs<RecordType>()->getDecl();
7276
7277 DeclarationName Name = Method->getDeclName();
7278 assert(Name.getNameKind() == DeclarationName::Identifier);
7279
7280 bool foundSameNameMethod = false;
7281 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7282 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7283 Path.Decls = Path.Decls.slice(1)) {
7284 NamedDecl *D = Path.Decls.front();
7285 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7286 MD = MD->getCanonicalDecl();
7287 foundSameNameMethod = true;
7288 // Interested only in hidden virtual methods.
7289 if (!MD->isVirtual())
7290 continue;
7291 // If the method we are checking overrides a method from its base
7292 // don't warn about the other overloaded methods. Clang deviates from
7293 // GCC by only diagnosing overloads of inherited virtual functions that
7294 // do not override any other virtual functions in the base. GCC's
7295 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7296 // function from a base class. These cases may be better served by a
7297 // warning (not specific to virtual functions) on call sites when the
7298 // call would select a different function from the base class, were it
7299 // visible.
7300 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7301 if (!S->IsOverload(Method, MD, false))
7302 return true;
7303 // Collect the overload only if its hidden.
7304 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7305 overloadedMethods.push_back(MD);
7306 }
7307 }
7308
7309 if (foundSameNameMethod)
7310 OverloadedMethods.append(overloadedMethods.begin(),
7311 overloadedMethods.end());
7312 return foundSameNameMethod;
7313 }
7314};
7315} // end anonymous namespace
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007316
David Blaikie282c92a2012-10-19 00:53:08 +00007317/// \brief Add the most overriden methods from MD to Methods
7318static void AddMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00007319 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00007320 if (MD->size_overridden_methods() == 0)
7321 Methods.insert(MD->getCanonicalDecl());
7322 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7323 E = MD->end_overridden_methods();
7324 I != E; ++I)
7325 AddMostOverridenMethods(*I, Methods);
7326}
7327
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007328/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007329/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007330void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7331 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00007332 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007333 return;
7334
7335 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7336 /*bool RecordPaths=*/false,
7337 /*bool DetectVirtual=*/false);
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007338 FindHiddenVirtualMethod FHVM;
7339 FHVM.Method = MD;
7340 FHVM.S = this;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007341
7342 // Keep the base methods that were overriden or introduced in the subclass
7343 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007344 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00007345 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7346 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7347 NamedDecl *ND = *I;
7348 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00007349 ND = shad->getTargetDecl();
7350 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007351 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007352 }
7353
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007354 if (DC->lookupInBases(FHVM, Paths))
7355 OverloadedMethods = FHVM.OverloadedMethods;
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007356}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007357
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007358void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7359 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7360 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7361 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7362 PartialDiagnostic PD = PDiag(
7363 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7364 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7365 Diag(overloadedMD->getLocation(), PD);
7366 }
7367}
7368
7369/// \brief Diagnose methods which overload virtual methods in a base class
7370/// without overriding any.
7371void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7372 if (MD->isInvalidDecl())
7373 return;
7374
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007375 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007376 return;
7377
7378 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7379 FindHiddenVirtualMethods(MD, OverloadedMethods);
7380 if (!OverloadedMethods.empty()) {
7381 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7382 << MD << (OverloadedMethods.size() > 1);
7383
7384 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007385 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00007386}
7387
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00007388void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00007389 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00007390 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00007391 SourceLocation RBrac,
7392 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00007393 if (!TagDecl)
7394 return;
Mike Stump11289f42009-09-09 15:08:12 +00007395
Douglas Gregorc9f9b862009-05-11 19:58:34 +00007396 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00007397
Rafael Espindola06e1b132012-07-12 04:32:30 +00007398 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
7399 if (l->getKind() != AttributeList::AT_Visibility)
7400 continue;
7401 l->setInvalid();
7402 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
7403 l->getName();
7404 }
7405
David Blaikie751c5582011-09-22 02:58:26 +00007406 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00007407 // strict aliasing violation!
7408 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00007409 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00007410
Douglas Gregor0be31a22010-07-02 17:43:08 +00007411 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00007412 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00007413}
7414
Douglas Gregor05379422008-11-03 17:51:48 +00007415/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7416/// special functions, such as the default constructor, copy
7417/// constructor, or destructor, to the given C++ class (C++
7418/// [special]p1). This routine can only be executed just before the
7419/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00007420void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Richard Smith5179eb72016-06-28 19:03:57 +00007421 if (ClassDecl->needsImplicitDefaultConstructor()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00007422 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00007423
Richard Smith5179eb72016-06-28 19:03:57 +00007424 if (ClassDecl->hasInheritedConstructor())
7425 DeclareImplicitDefaultConstructor(ClassDecl);
7426 }
Richard Smith12e79312016-05-13 06:47:56 +00007427
Richard Smitha87b7662016-05-13 18:48:05 +00007428 if (ClassDecl->needsImplicitCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00007429 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00007430
Richard Smith6b02d462012-12-08 08:32:28 +00007431 // If the properties or semantics of the copy constructor couldn't be
7432 // determined while the class was being declared, force a declaration
7433 // of it now.
Richard Smith12e79312016-05-13 06:47:56 +00007434 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7435 ClassDecl->hasInheritedConstructor())
Richard Smith6b02d462012-12-08 08:32:28 +00007436 DeclareImplicitCopyConstructor(ClassDecl);
Peter Collingbourne120eb542016-11-22 00:21:43 +00007437 // For the MS ABI we need to know whether the copy ctor is deleted. A
7438 // prerequisite for deleting the implicit copy ctor is that the class has a
7439 // move ctor or move assignment that is either user-declared or whose
7440 // semantics are inherited from a subobject. FIXME: We should provide a more
7441 // direct way for CodeGen to ask whether the constructor was deleted.
7442 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7443 (ClassDecl->hasUserDeclaredMoveConstructor() ||
7444 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7445 ClassDecl->hasUserDeclaredMoveAssignment() ||
7446 ClassDecl->needsOverloadResolutionForMoveAssignment()))
7447 DeclareImplicitCopyConstructor(ClassDecl);
Richard Smith6b02d462012-12-08 08:32:28 +00007448 }
7449
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007450 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00007451 ++ASTContext::NumImplicitMoveConstructors;
7452
Richard Smith12e79312016-05-13 06:47:56 +00007453 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7454 ClassDecl->hasInheritedConstructor())
Richard Smith6b02d462012-12-08 08:32:28 +00007455 DeclareImplicitMoveConstructor(ClassDecl);
7456 }
7457
Richard Smitha87b7662016-05-13 18:48:05 +00007458 if (ClassDecl->needsImplicitCopyAssignment()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007459 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00007460
7461 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007462 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00007463 // it shows up in the right place in the vtable and that we diagnose
7464 // problems with the implicit exception specification.
7465 if (ClassDecl->isDynamicClass() ||
Richard Smith12e79312016-05-13 06:47:56 +00007466 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7467 ClassDecl->hasInheritedAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007468 DeclareImplicitCopyAssignment(ClassDecl);
7469 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00007470
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007471 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00007472 ++ASTContext::NumImplicitMoveAssignmentOperators;
7473
7474 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00007475 if (ClassDecl->isDynamicClass() ||
Richard Smith12e79312016-05-13 06:47:56 +00007476 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7477 ClassDecl->hasInheritedAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00007478 DeclareImplicitMoveAssignment(ClassDecl);
7479 }
7480
Richard Smitha87b7662016-05-13 18:48:05 +00007481 if (ClassDecl->needsImplicitDestructor()) {
Douglas Gregor7454c562010-07-02 20:37:36 +00007482 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00007483
7484 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00007485 // have to declare the destructor immediately. This ensures that, e.g., it
7486 // shows up in the right place in the vtable and that we diagnose problems
7487 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00007488 if (ClassDecl->isDynamicClass() ||
7489 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00007490 DeclareImplicitDestructor(ClassDecl);
7491 }
Douglas Gregor05379422008-11-03 17:51:48 +00007492}
7493
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00007494unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Francois Pichet1c229c02011-04-22 22:18:13 +00007495 if (!D)
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00007496 return 0;
Francois Pichet1c229c02011-04-22 22:18:13 +00007497
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00007498 // The order of template parameters is not important here. All names
7499 // get added to the same scope.
7500 SmallVector<TemplateParameterList *, 4> ParameterLists;
7501
7502 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7503 D = TD->getTemplatedDecl();
7504
7505 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
7506 ParameterLists.push_back(PSD->getTemplateParameters());
7507
7508 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
7509 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
7510 ParameterLists.push_back(DD->getTemplateParameterList(i));
7511
7512 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7513 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
7514 ParameterLists.push_back(FTD->getTemplateParameters());
7515 }
7516 }
7517
7518 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7519 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
7520 ParameterLists.push_back(TD->getTemplateParameterList(i));
7521
7522 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
7523 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
7524 ParameterLists.push_back(CTD->getTemplateParameters());
7525 }
7526 }
7527
7528 unsigned Count = 0;
7529 for (TemplateParameterList *Params : ParameterLists) {
7530 if (Params->size() > 0)
7531 // Ignore explicit specializations; they don't contribute to the template
7532 // depth.
7533 ++Count;
7534 for (NamedDecl *Param : *Params) {
7535 if (Param->getDeclName()) {
7536 S->AddDecl(Param);
7537 IdResolver.AddDecl(Param);
Francois Pichet1c229c02011-04-22 22:18:13 +00007538 }
7539 }
7540 }
Francois Pichet1c229c02011-04-22 22:18:13 +00007541
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00007542 return Count;
Douglas Gregore44a2ad2009-05-27 23:11:45 +00007543}
7544
John McCall48871652010-08-21 09:40:31 +00007545void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00007546 if (!RecordD) return;
7547 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00007548 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00007549 PushDeclContext(S, Record);
7550}
7551
John McCall48871652010-08-21 09:40:31 +00007552void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00007553 if (!RecordD) return;
7554 PopDeclContext();
7555}
7556
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007557/// This is used to implement the constant expression evaluation part of the
7558/// attribute enable_if extension. There is nothing in standard C++ which would
7559/// require reentering parameters.
7560void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
7561 if (!Param)
7562 return;
7563
7564 S->AddDecl(Param);
7565 if (Param->getDeclName())
7566 IdResolver.AddDecl(Param);
7567}
7568
Douglas Gregor4d87df52008-12-16 21:30:33 +00007569/// ActOnStartDelayedCXXMethodDeclaration - We have completed
7570/// parsing a top-level (non-nested) C++ class, and we are now
7571/// parsing those parts of the given Method declaration that could
7572/// not be parsed earlier (C++ [class.mem]p2), such as default
7573/// arguments. This action should enter the scope of the given
7574/// Method declaration as if we had just parsed the qualified method
7575/// name. However, it should not bring the parameters into scope;
7576/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00007577void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00007578}
7579
7580/// ActOnDelayedCXXMethodParameter - We've already started a delayed
7581/// C++ method declaration. We're (re-)introducing the given
7582/// function parameter into scope for use in parsing later parts of
7583/// the method declaration. For example, we could see an
7584/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00007585void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00007586 if (!ParamD)
7587 return;
Mike Stump11289f42009-09-09 15:08:12 +00007588
John McCall48871652010-08-21 09:40:31 +00007589 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00007590
7591 // If this parameter has an unparsed default argument, clear it out
7592 // to make way for the parsed default argument.
7593 if (Param->hasUnparsedDefaultArg())
Craig Topperc3ec1492014-05-26 06:22:03 +00007594 Param->setDefaultArg(nullptr);
Douglas Gregor58354032008-12-24 00:01:03 +00007595
John McCall48871652010-08-21 09:40:31 +00007596 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00007597 if (Param->getDeclName())
7598 IdResolver.AddDecl(Param);
7599}
7600
7601/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
7602/// processing the delayed method declaration for Method. The method
7603/// declaration is now considered finished. There may be a separate
7604/// ActOnStartOfFunctionDef action later (not necessarily
7605/// immediately!) for this method, if it was also defined inside the
7606/// class body.
John McCall48871652010-08-21 09:40:31 +00007607void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00007608 if (!MethodD)
7609 return;
Mike Stump11289f42009-09-09 15:08:12 +00007610
Douglas Gregorc8c277a2009-08-24 11:57:43 +00007611 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00007612
John McCall48871652010-08-21 09:40:31 +00007613 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00007614
7615 // Now that we have our default arguments, check the constructor
7616 // again. It could produce additional diagnostics or affect whether
7617 // the class has implicitly-declared destructors, among other
7618 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007619 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
7620 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00007621
7622 // Check the default arguments, which we may have added.
7623 if (!Method->isInvalidDecl())
7624 CheckCXXDefaultArguments(Method);
7625}
7626
Douglas Gregor831c93f2008-11-05 20:51:48 +00007627/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00007628/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00007629/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00007630/// emit diagnostics and set the invalid bit to true. In any case, the type
7631/// will be updated to reflect a well-formed type for the constructor and
7632/// returned.
7633QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00007634 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007635 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007636
7637 // C++ [class.ctor]p3:
7638 // A constructor shall not be virtual (10.3) or static (9.4). A
7639 // constructor can be invoked for a const, volatile or const
7640 // volatile object. A constructor shall not be declared const,
7641 // volatile, or const volatile (9.3.2).
7642 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00007643 if (!D.isInvalidType())
7644 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7645 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
7646 << SourceRange(D.getIdentifierLoc());
7647 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007648 }
John McCall8e7d6562010-08-26 03:08:43 +00007649 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00007650 if (!D.isInvalidType())
7651 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7652 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7653 << SourceRange(D.getIdentifierLoc());
7654 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00007655 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00007656 }
Mike Stump11289f42009-09-09 15:08:12 +00007657
David Majnemer03f705f2014-07-08 18:18:04 +00007658 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7659 diagnoseIgnoredQualifiers(
7660 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
7661 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
7662 D.getDeclSpec().getRestrictSpecLoc(),
7663 D.getDeclSpec().getAtomicSpecLoc());
7664 D.setInvalidType();
7665 }
7666
Abramo Bagnara924a8f32010-12-10 16:29:40 +00007667 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00007668 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00007669 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00007670 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7671 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00007672 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00007673 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7674 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00007675 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00007676 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7677 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00007678 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007679 }
Mike Stump11289f42009-09-09 15:08:12 +00007680
Douglas Gregordb9d6642011-01-26 05:01:58 +00007681 // C++0x [class.ctor]p4:
7682 // A constructor shall not be declared with a ref-qualifier.
7683 if (FTI.hasRefQualifier()) {
7684 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
7685 << FTI.RefQualifierIsLValueRef
7686 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7687 D.setInvalidType();
7688 }
7689
Douglas Gregor831c93f2008-11-05 20:51:48 +00007690 // Rebuild the function type "R" without any type qualifiers (in
7691 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00007692 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00007693 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00007694 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00007695 return R;
7696
7697 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7698 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00007699 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00007700
7701 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00007702}
7703
Douglas Gregor4d87df52008-12-16 21:30:33 +00007704/// CheckConstructor - Checks a fully-formed constructor for
7705/// well-formedness, issuing any diagnostics required. Returns true if
7706/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007707void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00007708 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00007709 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
7710 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007711 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00007712
7713 // C++ [class.copy]p3:
7714 // A declaration of a constructor for a class X is ill-formed if
7715 // its first parameter is of type (optionally cv-qualified) X and
7716 // either there are no other parameters or else all other
7717 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00007718 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00007719 ((Constructor->getNumParams() == 1) ||
7720 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00007721 Constructor->getParamDecl(1)->hasDefaultArg())) &&
7722 Constructor->getTemplateSpecializationKind()
7723 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00007724 QualType ParamType = Constructor->getParamDecl(0)->getType();
7725 QualType ClassTy = Context.getTagDeclType(ClassDecl);
7726 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00007727 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00007728 const char *ConstRef
7729 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
7730 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00007731 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00007732 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00007733
7734 // FIXME: Rather that making the constructor invalid, we should endeavor
7735 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007736 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00007737 }
7738 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00007739}
7740
John McCalldeb646e2010-08-04 01:04:25 +00007741/// CheckDestructor - Checks a fully-formed destructor definition for
7742/// well-formedness, issuing any diagnostics required. Returns true
7743/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00007744bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00007745 CXXRecordDecl *RD = Destructor->getParent();
7746
Peter Collingbourneb289fe62013-05-20 14:12:25 +00007747 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00007748 SourceLocation Loc;
7749
7750 if (!Destructor->isImplicit())
7751 Loc = Destructor->getLocation();
7752 else
7753 Loc = RD->getLocation();
7754
7755 // If we have a virtual destructor, look up the deallocation function
Richard Smithb2f0f052016-10-10 18:54:32 +00007756 if (FunctionDecl *OperatorDelete =
7757 FindDeallocationFunctionForDestructor(Loc, RD)) {
7758 MarkFunctionReferenced(Loc, OperatorDelete);
7759 Destructor->setOperatorDelete(OperatorDelete);
7760 }
Anders Carlsson2a50e952009-11-15 22:49:34 +00007761 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00007762
7763 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00007764}
7765
Douglas Gregor831c93f2008-11-05 20:51:48 +00007766/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
7767/// the well-formednes of the destructor declarator @p D with type @p
7768/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00007769/// emit diagnostics and set the declarator to invalid. Even if this happens,
7770/// will be updated to reflect a well-formed type for the destructor and
7771/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00007772QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00007773 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007774 // C++ [class.dtor]p1:
7775 // [...] A typedef-name that names a class is a class-name
7776 // (7.1.3); however, a typedef-name that names a class shall not
7777 // be used as the identifier in the declarator for a destructor
7778 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00007779 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00007780 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00007781 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00007782 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00007783 else if (const TemplateSpecializationType *TST =
7784 DeclaratorType->getAs<TemplateSpecializationType>())
7785 if (TST->isTypeAlias())
7786 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
7787 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00007788
7789 // C++ [class.dtor]p2:
7790 // A destructor is used to destroy objects of its class type. A
7791 // destructor takes no parameters, and no return type can be
7792 // specified for it (not even void). The address of a destructor
7793 // shall not be taken. A destructor shall not be static. A
7794 // destructor can be invoked for a const, volatile or const
7795 // volatile object. A destructor shall not be declared const,
7796 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00007797 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00007798 if (!D.isInvalidType())
7799 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
7800 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00007801 << SourceRange(D.getIdentifierLoc())
7802 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7803
John McCall8e7d6562010-08-26 03:08:43 +00007804 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00007805 }
David Majnemer03f705f2014-07-08 18:18:04 +00007806 if (!D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007807 // Destructors don't have return types, but the parser will
7808 // happily parse something like:
7809 //
7810 // class X {
7811 // float ~X();
7812 // };
7813 //
7814 // The return type will be eliminated later.
David Majnemer03f705f2014-07-08 18:18:04 +00007815 if (D.getDeclSpec().hasTypeSpecifier())
7816 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
7817 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7818 << SourceRange(D.getIdentifierLoc());
7819 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7820 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
7821 SourceLocation(),
7822 D.getDeclSpec().getConstSpecLoc(),
7823 D.getDeclSpec().getVolatileSpecLoc(),
7824 D.getDeclSpec().getRestrictSpecLoc(),
7825 D.getDeclSpec().getAtomicSpecLoc());
7826 D.setInvalidType();
7827 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00007828 }
Mike Stump11289f42009-09-09 15:08:12 +00007829
Abramo Bagnara924a8f32010-12-10 16:29:40 +00007830 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00007831 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00007832 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00007833 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7834 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00007835 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00007836 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7837 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00007838 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00007839 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7840 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00007841 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007842 }
7843
Douglas Gregordb9d6642011-01-26 05:01:58 +00007844 // C++0x [class.dtor]p2:
7845 // A destructor shall not be declared with a ref-qualifier.
7846 if (FTI.hasRefQualifier()) {
7847 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
7848 << FTI.RefQualifierIsLValueRef
7849 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7850 D.setInvalidType();
7851 }
7852
Douglas Gregor831c93f2008-11-05 20:51:48 +00007853 // Make sure we don't have any parameters.
Alp Toker4284c6e2014-05-11 16:05:55 +00007854 if (FTIHasNonVoidParameters(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007855 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
7856
7857 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00007858 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00007859 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007860 }
7861
Mike Stump11289f42009-09-09 15:08:12 +00007862 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00007863 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007864 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00007865 D.setInvalidType();
7866 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00007867
7868 // Rebuild the function type "R" without any type qualifiers or
7869 // parameters (in case any of the errors above fired) and with
7870 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00007871 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00007872 if (!D.isInvalidType())
7873 return R;
7874
Douglas Gregor95755162010-07-01 05:10:53 +00007875 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00007876 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7877 EPI.Variadic = false;
7878 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00007879 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00007880 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00007881}
7882
Craig Toppere335f252015-10-04 04:53:55 +00007883static void extendLeft(SourceRange &R, SourceRange Before) {
Richard Smitha865a162014-12-19 02:07:47 +00007884 if (Before.isInvalid())
7885 return;
7886 R.setBegin(Before.getBegin());
7887 if (R.getEnd().isInvalid())
7888 R.setEnd(Before.getEnd());
7889}
7890
Craig Toppere335f252015-10-04 04:53:55 +00007891static void extendRight(SourceRange &R, SourceRange After) {
Richard Smitha865a162014-12-19 02:07:47 +00007892 if (After.isInvalid())
7893 return;
7894 if (R.getBegin().isInvalid())
7895 R.setBegin(After.getBegin());
7896 R.setEnd(After.getEnd());
7897}
7898
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007899/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
7900/// well-formednes of the conversion function declarator @p D with
7901/// type @p R. If there are any errors in the declarator, this routine
7902/// will emit diagnostics and return true. Otherwise, it will return
7903/// false. Either way, the type @p R will be updated to reflect a
7904/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007905void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00007906 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007907 // C++ [class.conv.fct]p1:
7908 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00007909 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00007910 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00007911 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007912 if (!D.isInvalidType())
7913 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00007914 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7915 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007916 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00007917 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007918 }
John McCall212fa2e2010-04-13 00:04:31 +00007919
Richard Smitha865a162014-12-19 02:07:47 +00007920 TypeSourceInfo *ConvTSI = nullptr;
7921 QualType ConvType =
7922 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
John McCall212fa2e2010-04-13 00:04:31 +00007923
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007924 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007925 // Conversion functions don't have return types, but the parser will
7926 // happily parse something like:
7927 //
7928 // class X {
7929 // float operator bool();
7930 // };
7931 //
7932 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00007933 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
7934 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7935 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00007936 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007937 }
7938
John McCall212fa2e2010-04-13 00:04:31 +00007939 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7940
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007941 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00007942 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007943 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
7944
7945 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00007946 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007947 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00007948 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007949 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007950 D.setInvalidType();
7951 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007952
John McCall212fa2e2010-04-13 00:04:31 +00007953 // Diagnose "&operator bool()" and other such nonsense. This
7954 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00007955 if (Proto->getReturnType() != ConvType) {
Richard Smitha865a162014-12-19 02:07:47 +00007956 bool NeedsTypedef = false;
7957 SourceRange Before, After;
7958
7959 // Walk the chunks and extract information on them for our diagnostic.
7960 bool PastFunctionChunk = false;
7961 for (auto &Chunk : D.type_objects()) {
7962 switch (Chunk.Kind) {
7963 case DeclaratorChunk::Function:
7964 if (!PastFunctionChunk) {
7965 if (Chunk.Fun.HasTrailingReturnType) {
7966 TypeSourceInfo *TRT = nullptr;
7967 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
7968 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
7969 }
7970 PastFunctionChunk = true;
7971 break;
7972 }
7973 // Fall through.
7974 case DeclaratorChunk::Array:
7975 NeedsTypedef = true;
7976 extendRight(After, Chunk.getSourceRange());
7977 break;
7978
7979 case DeclaratorChunk::Pointer:
7980 case DeclaratorChunk::BlockPointer:
7981 case DeclaratorChunk::Reference:
7982 case DeclaratorChunk::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00007983 case DeclaratorChunk::Pipe:
Richard Smitha865a162014-12-19 02:07:47 +00007984 extendLeft(Before, Chunk.getSourceRange());
7985 break;
7986
7987 case DeclaratorChunk::Paren:
7988 extendLeft(Before, Chunk.Loc);
7989 extendRight(After, Chunk.EndLoc);
7990 break;
7991 }
7992 }
7993
7994 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
7995 After.isValid() ? After.getBegin() :
7996 D.getIdentifierLoc();
7997 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
7998 DB << Before << After;
7999
8000 if (!NeedsTypedef) {
8001 DB << /*don't need a typedef*/0;
8002
8003 // If we can provide a correct fix-it hint, do so.
8004 if (After.isInvalid() && ConvTSI) {
8005 SourceLocation InsertLoc =
Craig Topper07fa1762015-11-15 02:31:46 +00008006 getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
Richard Smitha865a162014-12-19 02:07:47 +00008007 DB << FixItHint::CreateInsertion(InsertLoc, " ")
8008 << FixItHint::CreateInsertionFromRange(
8009 InsertLoc, CharSourceRange::getTokenRange(Before))
8010 << FixItHint::CreateRemoval(Before);
8011 }
8012 } else if (!Proto->getReturnType()->isDependentType()) {
8013 DB << /*typedef*/1 << Proto->getReturnType();
8014 } else if (getLangOpts().CPlusPlus11) {
8015 DB << /*alias template*/2 << Proto->getReturnType();
8016 } else {
8017 DB << /*might not be fixable*/3;
8018 }
8019
8020 // Recover by incorporating the other type chunks into the result type.
8021 // Note, this does *not* change the name of the function. This is compatible
8022 // with the GCC extension:
8023 // struct S { &operator int(); } s;
8024 // int &r = s.operator int(); // ok in GCC
8025 // S::operator int&() {} // error in GCC, function name is 'operator int'.
Alp Toker314cc812014-01-25 16:55:45 +00008026 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00008027 }
8028
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008029 // C++ [class.conv.fct]p4:
8030 // The conversion-type-id shall not represent a function type nor
8031 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008032 if (ConvType->isArrayType()) {
8033 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8034 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00008035 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008036 } else if (ConvType->isFunctionType()) {
8037 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8038 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00008039 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008040 }
8041
8042 // Rebuild the function type "R" without any parameters (in case any
8043 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00008044 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00008045 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00008046 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008047
Douglas Gregor5fb53972009-01-14 15:45:31 +00008048 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00008049 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00008050 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008051 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00008052 diag::warn_cxx98_compat_explicit_conversion_functions :
8053 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00008054 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008055}
8056
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008057/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8058/// the declaration of the given C++ conversion function. This routine
8059/// is responsible for recording the conversion function in the C++
8060/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00008061Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008062 assert(Conversion && "Expected to receive a conversion function declaration");
8063
Douglas Gregor4287b372008-12-12 08:25:50 +00008064 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008065
8066 // Make sure we aren't redeclaring the conversion function.
8067 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008068
8069 // C++ [class.conv.fct]p1:
8070 // [...] A conversion function is never used to convert a
8071 // (possibly cv-qualified) object to the (possibly cv-qualified)
8072 // same object type (or a reference to it), to a (possibly
8073 // cv-qualified) base class of that type (or a reference to it),
8074 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00008075 // FIXME: Suppress this warning if the conversion function ends up being a
8076 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00008077 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008078 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008079 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008080 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00008081 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8082 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00008083 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00008084 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008085 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8086 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00008087 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008088 << ClassType;
Richard Smith0f59cb32015-12-18 21:45:41 +00008089 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00008090 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008091 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008092 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00008093 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008094 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008095 }
8096
Douglas Gregor457104e2010-09-29 04:25:11 +00008097 if (FunctionTemplateDecl *ConversionTemplate
8098 = Conversion->getDescribedFunctionTemplate())
8099 return ConversionTemplate;
8100
John McCall48871652010-08-21 09:40:31 +00008101 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00008102}
8103
Richard Smithf283fdc2017-02-08 00:35:25 +00008104namespace {
8105/// Utility class to accumulate and print a diagnostic listing the invalid
8106/// specifier(s) on a declaration.
8107struct BadSpecifierDiagnoser {
8108 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8109 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8110 ~BadSpecifierDiagnoser() {
8111 Diagnostic << Specifiers;
8112 }
8113
8114 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8115 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8116 }
8117 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8118 return check(SpecLoc,
8119 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8120 }
8121 void check(SourceLocation SpecLoc, const char *Spec) {
8122 if (SpecLoc.isInvalid()) return;
8123 Diagnostic << SourceRange(SpecLoc, SpecLoc);
8124 if (!Specifiers.empty()) Specifiers += " ";
8125 Specifiers += Spec;
8126 }
8127
8128 Sema &S;
8129 Sema::SemaDiagnosticBuilder Diagnostic;
8130 std::string Specifiers;
8131};
8132}
8133
Richard Smith35845152017-02-07 01:37:30 +00008134/// Check the validity of a declarator that we parsed for a deduction-guide.
8135/// These aren't actually declarators in the grammar, so we need to check that
8136/// the user didn't specify any pieces that are not part of the deduction-guide
8137/// grammar.
8138void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8139 StorageClass &SC) {
Richard Smithf283fdc2017-02-08 00:35:25 +00008140 auto &DS = D.getMutableDeclSpec();
8141 // We leave 'friend' and 'virtual' to be rejected in the normal way.
8142 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8143 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8144 DS.isNoreturnSpecified() || DS.isConstexprSpecified() ||
8145 DS.isConceptSpecified()) {
8146 BadSpecifierDiagnoser Diagnoser(
8147 *this, D.getIdentifierLoc(),
8148 diag::err_deduction_guide_invalid_specifier);
8149
8150 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8151 DS.ClearStorageClassSpecs();
8152 SC = SC_None;
8153
8154 // 'explicit' is permitted.
8155 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8156 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8157 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8158 Diagnoser.check(DS.getConceptSpecLoc(), "concept");
8159 DS.ClearConstexprSpec();
8160 DS.ClearConceptSpec();
8161
8162 Diagnoser.check(DS.getConstSpecLoc(), "const");
8163 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8164 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8165 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8166 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8167 DS.ClearTypeQualifiers();
8168
8169 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8170 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8171 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8172 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8173 DS.ClearTypeSpecType();
8174 }
8175
8176 if (D.isInvalidType())
8177 return;
8178
8179 // Check the declarator is simple enough.
8180 bool FoundFunction = false;
8181 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8182 if (Chunk.Kind == DeclaratorChunk::Paren)
8183 continue;
8184 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8185 Diag(D.getDeclSpec().getLocStart(),
8186 diag::err_deduction_guide_with_complex_decl)
8187 << D.getSourceRange();
8188 break;
8189 }
8190 if (!Chunk.Fun.hasTrailingReturnType()) {
8191 Diag(D.getName().getLocStart(),
8192 diag::err_deduction_guide_no_trailing_return_type);
8193 break;
8194 }
Richard Smith3817e4a2017-02-10 19:49:50 +00008195
8196 // Check that the return type is written as a specialization of
8197 // the template specified as the deduction-guide's name.
8198 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8199 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8200 TypeSourceInfo *TSI = nullptr;
8201 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8202 assert(TSI && "deduction guide has valid type but invalid return type?");
8203 bool AcceptableReturnType = false;
8204 bool MightInstantiateToSpecialization = false;
8205 if (auto RetTST =
8206 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8207 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8208 bool TemplateMatches =
8209 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8210 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8211 AcceptableReturnType = true;
8212 else {
8213 // This could still instantiate to the right type, unless we know it
8214 // names the wrong class template.
8215 auto *TD = SpecifiedName.getAsTemplateDecl();
8216 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8217 !TemplateMatches);
8218 }
8219 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8220 MightInstantiateToSpecialization = true;
8221 }
8222
8223 if (!AcceptableReturnType) {
8224 Diag(TSI->getTypeLoc().getLocStart(),
8225 diag::err_deduction_guide_bad_trailing_return_type)
8226 << GuidedTemplate << TSI->getType() << MightInstantiateToSpecialization
8227 << TSI->getTypeLoc().getSourceRange();
8228 }
8229
8230 // Keep going to check that we don't have any inner declarator pieces (we
8231 // could still have a function returning a pointer to a function).
Richard Smithf283fdc2017-02-08 00:35:25 +00008232 FoundFunction = true;
8233 }
8234
Richard Smithc88aa3f2017-02-08 01:27:29 +00008235 if (D.isFunctionDefinition())
8236 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
Richard Smith35845152017-02-07 01:37:30 +00008237}
8238
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008239//===----------------------------------------------------------------------===//
8240// Namespace Handling
8241//===----------------------------------------------------------------------===//
8242
Richard Smith45bb8852012-10-04 22:13:39 +00008243/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
8244/// reopened.
8245static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8246 SourceLocation Loc,
8247 IdentifierInfo *II, bool *IsInline,
8248 NamespaceDecl *PrevNS) {
8249 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00008250
Richard Smithf501cc32012-10-05 01:46:25 +00008251 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8252 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8253 // inline namespaces, with the intention of bringing names into namespace std.
8254 //
8255 // We support this just well enough to get that case working; this is not
8256 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00008257 if (*IsInline && II && II->getName().startswith("__atomic") &&
8258 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00008259 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00008260 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8261 NS = NS->getPreviousDecl())
8262 NS->setInline(*IsInline);
8263 // Patch up the lookup table for the containing namespace. This isn't really
8264 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00008265 for (auto *I : PrevNS->decls())
8266 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00008267 PrevNS->getParent()->makeDeclVisibleInContext(ND);
8268 return;
8269 }
8270
8271 if (PrevNS->isInline())
8272 // The user probably just forgot the 'inline', so suggest that it
8273 // be added back.
8274 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8275 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8276 else
Richard Smith360cb252016-09-30 23:16:08 +00008277 S.Diag(Loc, diag::err_inline_namespace_mismatch);
Richard Smith45bb8852012-10-04 22:13:39 +00008278
8279 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8280 *IsInline = PrevNS->isInline();
8281}
John McCallb1be5232010-08-26 09:15:37 +00008282
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008283/// ActOnStartNamespaceDef - This is called at the start of a namespace
8284/// definition.
John McCall48871652010-08-21 09:40:31 +00008285Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00008286 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00008287 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00008288 SourceLocation IdentLoc,
8289 IdentifierInfo *II,
8290 SourceLocation LBrace,
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00008291 AttributeList *AttrList,
8292 UsingDirectiveDecl *&UD) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00008293 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8294 // For anonymous namespace, take the location of the left brace.
8295 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00008296 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00008297 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00008298 bool IsStd = false;
8299 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008300 Scope *DeclRegionScope = NamespcScope->getParent();
8301
Craig Topperc3ec1492014-05-26 06:22:03 +00008302 NamespaceDecl *PrevNS = nullptr;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008303 if (II) {
8304 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00008305 // The identifier in an original-namespace-definition shall not
8306 // have been previously defined in the declarative region in
8307 // which the original-namespace-definition appears. The
8308 // identifier in an original-namespace-definition is the name of
8309 // the namespace. Subsequently in that declarative region, it is
8310 // treated as an original-namespace-name.
8311 //
8312 // Since namespace names are unique in their scope, and we don't
Richard Smith97135cc2015-11-12 22:19:45 +00008313 // look through using directives, just look for any ordinary names
8314 // as if by qualified name lookup.
8315 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration);
8316 LookupQualifiedName(R, CurContext->getRedeclContext());
Richard Smithf2005d32015-12-29 23:34:32 +00008317 NamedDecl *PrevDecl =
8318 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
Douglas Gregore57e7522012-01-07 09:11:48 +00008319 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
Richard Smith97135cc2015-11-12 22:19:45 +00008320
Douglas Gregore57e7522012-01-07 09:11:48 +00008321 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00008322 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00008323 if (IsInline != PrevNS->isInline())
8324 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8325 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00008326 } else if (PrevDecl) {
8327 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00008328 Diag(Loc, diag::err_redefinition_different_kind)
8329 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00008330 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00008331 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00008332 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00008333 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00008334 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00008335 // This is the first "real" definition of the namespace "std", so update
8336 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00008337 PrevNS = getStdNamespace();
8338 IsStd = true;
8339 AddToKnown = !IsInline;
8340 } else {
8341 // We've seen this namespace for the first time.
8342 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00008343 }
Douglas Gregor91f84212008-12-11 16:49:14 +00008344 } else {
John McCall4fa53422009-10-01 00:25:31 +00008345 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00008346
8347 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00008348 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00008349 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00008350 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00008351 } else {
8352 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00008353 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00008354 }
8355
Richard Smith45bb8852012-10-04 22:13:39 +00008356 if (PrevNS && IsInline != PrevNS->isInline())
8357 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8358 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00008359 }
8360
8361 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8362 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00008363 if (IsInvalid)
8364 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00008365
8366 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00008367
Douglas Gregore57e7522012-01-07 09:11:48 +00008368 // FIXME: Should we be merging attributes?
8369 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00008370 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00008371
8372 if (IsStd)
8373 StdNamespace = Namespc;
8374 if (AddToKnown)
8375 KnownNamespaces[Namespc] = false;
8376
8377 if (II) {
8378 PushOnScopeChains(Namespc, DeclRegionScope);
8379 } else {
8380 // Link the anonymous namespace into its parent.
8381 DeclContext *Parent = CurContext->getRedeclContext();
8382 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8383 TU->setAnonymousNamespace(Namespc);
8384 } else {
8385 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00008386 }
John McCall4fa53422009-10-01 00:25:31 +00008387
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00008388 CurContext->addDecl(Namespc);
8389
John McCall4fa53422009-10-01 00:25:31 +00008390 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
8391 // behaves as if it were replaced by
8392 // namespace unique { /* empty body */ }
8393 // using namespace unique;
8394 // namespace unique { namespace-body }
8395 // where all occurrences of 'unique' in a translation unit are
8396 // replaced by the same identifier and this identifier differs
8397 // from all other identifiers in the entire program.
8398
8399 // We just create the namespace with an empty name and then add an
8400 // implicit using declaration, just like the standard suggests.
8401 //
8402 // CodeGen enforces the "universally unique" aspect by giving all
8403 // declarations semantically contained within an anonymous
8404 // namespace internal linkage.
8405
Douglas Gregore57e7522012-01-07 09:11:48 +00008406 if (!PrevNS) {
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00008407 UD = UsingDirectiveDecl::Create(Context, Parent,
8408 /* 'using' */ LBrace,
8409 /* 'namespace' */ SourceLocation(),
8410 /* qualifier */ NestedNameSpecifierLoc(),
8411 /* identifier */ SourceLocation(),
8412 Namespc,
8413 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00008414 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00008415 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00008416 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008417 }
8418
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00008419 ActOnDocumentableDecl(Namespc);
8420
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008421 // Although we could have an invalid decl (i.e. the namespace name is a
8422 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00008423 // FIXME: We should be able to push Namespc here, so that the each DeclContext
8424 // for the namespace has the declarations that showed up in that particular
8425 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00008426 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00008427 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008428}
8429
Sebastian Redla6602e92009-11-23 15:34:23 +00008430/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8431/// is a namespace alias, returns the namespace it points to.
8432static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8433 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8434 return AD->getNamespace();
8435 return dyn_cast_or_null<NamespaceDecl>(D);
8436}
8437
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008438/// ActOnFinishNamespaceDef - This callback is called after a namespace is
8439/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00008440void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008441 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8442 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00008443 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008444 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00008445 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00008446 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008447}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008448
John McCall28a0cf72010-08-25 07:42:41 +00008449CXXRecordDecl *Sema::getStdBadAlloc() const {
8450 return cast_or_null<CXXRecordDecl>(
8451 StdBadAlloc.get(Context.getExternalSource()));
8452}
8453
Richard Smith96269c52016-09-29 22:49:46 +00008454EnumDecl *Sema::getStdAlignValT() const {
8455 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
8456}
8457
John McCall28a0cf72010-08-25 07:42:41 +00008458NamespaceDecl *Sema::getStdNamespace() const {
8459 return cast_or_null<NamespaceDecl>(
8460 StdNamespace.get(Context.getExternalSource()));
8461}
8462
Gor Nishanov3e048bb2016-10-04 00:31:16 +00008463NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
8464 if (!StdExperimentalNamespaceCache) {
8465 if (auto Std = getStdNamespace()) {
8466 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
8467 SourceLocation(), LookupNamespaceName);
8468 if (!LookupQualifiedName(Result, Std) ||
8469 !(StdExperimentalNamespaceCache =
8470 Result.getAsSingle<NamespaceDecl>()))
8471 Result.suppressDiagnostics();
8472 }
8473 }
8474 return StdExperimentalNamespaceCache;
8475}
8476
Douglas Gregorcdf87022010-06-29 17:53:46 +00008477/// \brief Retrieve the special "std" namespace, which may require us to
8478/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00008479NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00008480 if (!StdNamespace) {
8481 // The "std" namespace has not yet been defined, so build one implicitly.
8482 StdNamespace = NamespaceDecl::Create(Context,
8483 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00008484 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00008485 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00008486 &PP.getIdentifierTable().get("std"),
Craig Topperc3ec1492014-05-26 06:22:03 +00008487 /*PrevDecl=*/nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00008488 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00008489 }
Eli Bendersky9a220fc2014-09-29 20:38:29 +00008490
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00008491 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00008492}
8493
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008494bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008495 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008496 "Looking for std::initializer_list outside of C++.");
8497
8498 // We're looking for implicit instantiations of
8499 // template <typename E> class std::initializer_list.
8500
8501 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
8502 return false;
8503
Craig Topperc3ec1492014-05-26 06:22:03 +00008504 ClassTemplateDecl *Template = nullptr;
8505 const TemplateArgument *Arguments = nullptr;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008506
Sebastian Redl43144e72012-01-17 22:49:58 +00008507 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008508
Sebastian Redl43144e72012-01-17 22:49:58 +00008509 ClassTemplateSpecializationDecl *Specialization =
8510 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
8511 if (!Specialization)
8512 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008513
Sebastian Redl43144e72012-01-17 22:49:58 +00008514 Template = Specialization->getSpecializedTemplate();
8515 Arguments = Specialization->getTemplateArgs().data();
8516 } else if (const TemplateSpecializationType *TST =
8517 Ty->getAs<TemplateSpecializationType>()) {
8518 Template = dyn_cast_or_null<ClassTemplateDecl>(
8519 TST->getTemplateName().getAsTemplateDecl());
8520 Arguments = TST->getArgs();
8521 }
8522 if (!Template)
8523 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008524
8525 if (!StdInitializerList) {
8526 // Haven't recognized std::initializer_list yet, maybe this is it.
8527 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
8528 if (TemplateClass->getIdentifier() !=
8529 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00008530 !getStdNamespace()->InEnclosingNamespaceSetOf(
8531 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008532 return false;
8533 // This is a template called std::initializer_list, but is it the right
8534 // template?
8535 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00008536 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008537 return false;
8538 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
8539 return false;
8540
8541 // It's the right template.
8542 StdInitializerList = Template;
8543 }
8544
Richard Smith7d7dee72015-02-24 03:30:14 +00008545 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008546 return false;
8547
8548 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00008549 if (Element)
8550 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008551 return true;
8552}
8553
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008554static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
8555 NamespaceDecl *Std = S.getStdNamespace();
8556 if (!Std) {
8557 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00008558 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008559 }
8560
8561 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
8562 Loc, Sema::LookupOrdinaryName);
8563 if (!S.LookupQualifiedName(Result, Std)) {
8564 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00008565 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008566 }
8567 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
8568 if (!Template) {
8569 Result.suppressDiagnostics();
8570 // We found something weird. Complain about the first thing we found.
8571 NamedDecl *Found = *Result.begin();
8572 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00008573 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008574 }
8575
8576 // We found some template called std::initializer_list. Now verify that it's
8577 // correct.
8578 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00008579 if (Params->getMinRequiredArguments() != 1 ||
8580 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008581 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00008582 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008583 }
8584
8585 return Template;
8586}
8587
8588QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
8589 if (!StdInitializerList) {
8590 StdInitializerList = LookupStdInitializerList(*this, Loc);
8591 if (!StdInitializerList)
8592 return QualType();
8593 }
8594
8595 TemplateArgumentListInfo Args(Loc, Loc);
8596 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
8597 Context.getTrivialTypeSourceInfo(Element,
8598 Loc)));
8599 return Context.getCanonicalType(
8600 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
8601}
8602
Richard Smith60437622017-02-09 19:17:44 +00008603bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
Sebastian Redlbe24ec22012-01-17 22:50:14 +00008604 // C++ [dcl.init.list]p2:
8605 // A constructor is an initializer-list constructor if its first parameter
8606 // is of type std::initializer_list<E> or reference to possibly cv-qualified
8607 // std::initializer_list<E> for some type E, and either there are no other
8608 // parameters or else all other parameters have default arguments.
8609 if (Ctor->getNumParams() < 1 ||
8610 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
8611 return false;
8612
8613 QualType ArgType = Ctor->getParamDecl(0)->getType();
8614 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
8615 ArgType = RT->getPointeeType().getUnqualifiedType();
8616
Craig Topperc3ec1492014-05-26 06:22:03 +00008617 return isStdInitializerList(ArgType, nullptr);
Sebastian Redlbe24ec22012-01-17 22:50:14 +00008618}
8619
Douglas Gregora172e082011-03-26 22:25:30 +00008620/// \brief Determine whether a using statement is in a context where it will be
8621/// apply in all contexts.
8622static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
8623 switch (CurContext->getDeclKind()) {
8624 case Decl::TranslationUnit:
8625 return true;
8626 case Decl::LinkageSpec:
8627 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
8628 default:
8629 return false;
8630 }
8631}
8632
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008633namespace {
8634
8635// Callback to only accept typo corrections that are namespaces.
8636class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008637public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008638 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008639 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008640 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008641 return false;
8642 }
8643};
8644
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008645}
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008646
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008647static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
8648 CXXScopeSpec &SS,
8649 SourceLocation IdentLoc,
8650 IdentifierInfo *Ident) {
8651 R.clear();
Kaelyn Takata89c881b2014-10-27 18:07:29 +00008652 if (TypoCorrection Corrected =
8653 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
8654 llvm::make_unique<NamespaceValidatorCCC>(),
8655 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00008656 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00008657 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
8658 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00008659 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00008660 S.diagnoseTypo(Corrected,
8661 S.PDiag(diag::err_using_directive_member_suggest)
8662 << Ident << DC << DroppedSpecifier << SS.getRange(),
8663 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00008664 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00008665 S.diagnoseTypo(Corrected,
8666 S.PDiag(diag::err_using_directive_suggest) << Ident,
8667 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00008668 }
Richard Smithde6d6c42015-12-29 19:43:10 +00008669 R.addDecl(Corrected.getFoundDecl());
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008670 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008671 }
8672 return false;
8673}
8674
John McCall48871652010-08-21 09:40:31 +00008675Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00008676 SourceLocation UsingLoc,
8677 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00008678 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00008679 SourceLocation IdentLoc,
8680 IdentifierInfo *NamespcName,
8681 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00008682 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8683 assert(NamespcName && "Invalid NamespcName.");
8684 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00008685
8686 // This can only happen along a recovery path.
Davide Italiano5be22332015-11-11 20:06:35 +00008687 while (S->isTemplateParamScope())
John McCall9b72f892010-11-10 02:40:36 +00008688 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00008689 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00008690
Craig Topperc3ec1492014-05-26 06:22:03 +00008691 UsingDirectiveDecl *UDir = nullptr;
8692 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregorcdf87022010-06-29 17:53:46 +00008693 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00008694 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00008695
Douglas Gregor34074322009-01-14 22:20:51 +00008696 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00008697 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
8698 LookupParsedName(R, S, &SS);
8699 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00008700 return nullptr;
John McCall27b18f82009-11-17 02:14:36 +00008701
Douglas Gregorcdf87022010-06-29 17:53:46 +00008702 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008703 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00008704 // Allow "using namespace std;" or "using namespace ::std;" even if
8705 // "std" hasn't been defined yet, for GCC compatibility.
8706 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
8707 NamespcName->isStr("std")) {
8708 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00008709 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00008710 R.resolveKind();
8711 }
8712 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008713 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00008714 }
8715
John McCall9f3059a2009-10-09 21:13:30 +00008716 if (!R.empty()) {
Richard Smithf2005d32015-12-29 23:34:32 +00008717 NamedDecl *Named = R.getRepresentativeDecl();
8718 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
8719 assert(NS && "expected namespace decl");
Aaron Ballman43f40102014-11-14 22:34:56 +00008720
Nico Riecke50e59a2014-11-24 17:29:52 +00008721 // The use of a nested name specifier may trigger deprecation warnings.
8722 DiagnoseUseOfDecl(Named, IdentLoc);
Aaron Ballman43f40102014-11-14 22:34:56 +00008723
Douglas Gregor889ceb72009-02-03 19:21:40 +00008724 // C++ [namespace.udir]p1:
8725 // A using-directive specifies that the names in the nominated
8726 // namespace can be used in the scope in which the
8727 // using-directive appears after the using-directive. During
8728 // unqualified name lookup (3.4.1), the names appear as if they
8729 // were declared in the nearest enclosing namespace which
8730 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00008731 // namespace. [Note: in this context, "contains" means "contains
8732 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00008733
8734 // Find enclosing context containing both using-directive and
8735 // nominated namespace.
8736 DeclContext *CommonAncestor = cast<DeclContext>(NS);
8737 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
8738 CommonAncestor = CommonAncestor->getParent();
8739
Sebastian Redla6602e92009-11-23 15:34:23 +00008740 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00008741 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00008742 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00008743
Douglas Gregora172e082011-03-26 22:25:30 +00008744 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00008745 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00008746 Diag(IdentLoc, diag::warn_using_directive_in_header);
8747 }
8748
Douglas Gregor889ceb72009-02-03 19:21:40 +00008749 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00008750 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00008751 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00008752 }
8753
Richard Smith54ecd982013-02-20 19:22:51 +00008754 if (UDir)
8755 ProcessDeclAttributeList(S, UDir, AttrList);
8756
John McCall48871652010-08-21 09:40:31 +00008757 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00008758}
8759
8760void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00008761 // If the scope has an associated entity and the using directive is at
8762 // namespace or translation unit scope, add the UsingDirectiveDecl into
8763 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00008764 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00008765 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00008766 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00008767 else
Yaron Keren065da7c2014-05-20 18:23:05 +00008768 // Otherwise, it is at block scope. The using-directives will affect lookup
Richard Smith05afe5e2012-03-13 03:12:56 +00008769 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00008770 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00008771}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008772
Douglas Gregorfec52632009-06-20 00:51:54 +00008773
John McCall48871652010-08-21 09:40:31 +00008774Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00008775 AccessSpecifier AS,
John McCall9b72f892010-11-10 02:40:36 +00008776 SourceLocation UsingLoc,
Richard Smith151c4562016-12-20 21:35:28 +00008777 SourceLocation TypenameLoc,
John McCall9b72f892010-11-10 02:40:36 +00008778 CXXScopeSpec &SS,
8779 UnqualifiedId &Name,
Richard Smith151c4562016-12-20 21:35:28 +00008780 SourceLocation EllipsisLoc,
8781 AttributeList *AttrList) {
Douglas Gregorfec52632009-06-20 00:51:54 +00008782 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00008783
Richard Smith151c4562016-12-20 21:35:28 +00008784 if (SS.isEmpty()) {
8785 Diag(Name.getLocStart(), diag::err_using_requires_qualname);
8786 return nullptr;
8787 }
8788
Douglas Gregor220f4272009-11-04 16:30:06 +00008789 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00008790 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00008791 case UnqualifiedId::IK_Identifier:
8792 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00008793 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00008794 case UnqualifiedId::IK_ConversionFunctionId:
8795 break;
8796
8797 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00008798 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00008799 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008800 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008801 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00008802 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00008803 diag::err_using_decl_constructor)
8804 << SS.getRange();
8805
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008806 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00008807
Craig Topperc3ec1492014-05-26 06:22:03 +00008808 return nullptr;
8809
Douglas Gregor220f4272009-11-04 16:30:06 +00008810 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008811 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00008812 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00008813 return nullptr;
8814
Douglas Gregor220f4272009-11-04 16:30:06 +00008815 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008816 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00008817 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00008818 return nullptr;
Richard Smith35845152017-02-07 01:37:30 +00008819
8820 case UnqualifiedId::IK_DeductionGuideName:
8821 llvm_unreachable("cannot parse qualified deduction guide name");
Douglas Gregor220f4272009-11-04 16:30:06 +00008822 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008823
8824 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
8825 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00008826 if (!TargetName)
Craig Topperc3ec1492014-05-26 06:22:03 +00008827 return nullptr;
John McCall3969e302009-12-08 07:46:18 +00008828
Richard Smithc2bc61b2013-03-18 21:12:30 +00008829 // Warn about access declarations.
Richard Smith6f1daa42016-12-16 00:58:48 +00008830 if (UsingLoc.isInvalid()) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00008831 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00008832 getLangOpts().CPlusPlus11 ? diag::err_access_decl
8833 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00008834 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00008835 }
8836
Richard Smith151c4562016-12-20 21:35:28 +00008837 if (EllipsisLoc.isInvalid()) {
8838 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
8839 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
8840 return nullptr;
8841 } else {
8842 if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
8843 !TargetNameInfo.containsUnexpandedParameterPack()) {
8844 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
8845 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
8846 EllipsisLoc = SourceLocation();
8847 }
8848 }
Douglas Gregorc4356532010-12-16 00:46:58 +00008849
Richard Smith151c4562016-12-20 21:35:28 +00008850 NamedDecl *UD =
8851 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
8852 SS, TargetNameInfo, EllipsisLoc, AttrList,
8853 /*IsInstantiation*/false);
John McCallb96ec562009-12-04 22:46:56 +00008854 if (UD)
8855 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00008856
John McCall48871652010-08-21 09:40:31 +00008857 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00008858}
8859
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008860/// \brief Determine whether a using declaration considers the given
8861/// declarations as "equivalent", e.g., if they are redeclarations of
8862/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00008863static bool
8864IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
8865 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008866 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008867
Richard Smithdda56e42011-04-15 14:24:37 +00008868 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00008869 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008870 return Context.hasSameType(TD1->getUnderlyingType(),
8871 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008872
8873 return false;
8874}
8875
8876
John McCall84d87672009-12-10 09:41:52 +00008877/// Determines whether to create a using shadow decl for a particular
8878/// decl, given the set of decls existing prior to this using lookup.
8879bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00008880 const LookupResult &Previous,
8881 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00008882 // Diagnose finding a decl which is not from a base class of the
8883 // current class. We do this now because there are cases where this
8884 // function will silently decide not to build a shadow decl, which
8885 // will pre-empt further diagnostics.
8886 //
Richard Smith5cbeb752016-05-05 02:13:49 +00008887 // We don't need to do this in C++11 because we do the check once on
John McCall84d87672009-12-10 09:41:52 +00008888 // the qualifier.
8889 //
8890 // FIXME: diagnose the following if we care enough:
8891 // struct A { int foo; };
8892 // struct B : A { using A::foo; };
8893 // template <class T> struct C : A {};
8894 // template <class T> struct D : C<T> { using B::foo; } // <---
8895 // This is invalid (during instantiation) in C++03 because B::foo
8896 // resolves to the using decl in B, which is not a base class of D<T>.
8897 // We can't diagnose it immediately because C<T> is an unknown
8898 // specialization. The UsingShadowDecl in D<T> then points directly
8899 // to A::foo, which will look well-formed when we instantiate.
8900 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008901 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00008902 DeclContext *OrigDC = Orig->getDeclContext();
8903
8904 // Handle enums and anonymous structs.
8905 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
8906 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
8907 while (OrigRec->isAnonymousStructOrUnion())
8908 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
8909
8910 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
8911 if (OrigDC == CurContext) {
8912 Diag(Using->getLocation(),
8913 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008914 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00008915 Diag(Orig->getLocation(), diag::note_using_decl_target);
Richard Smith151c4562016-12-20 21:35:28 +00008916 Using->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00008917 return true;
8918 }
8919
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008920 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00008921 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008922 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00008923 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008924 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00008925 Diag(Orig->getLocation(), diag::note_using_decl_target);
Richard Smith151c4562016-12-20 21:35:28 +00008926 Using->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00008927 return true;
8928 }
8929 }
8930
8931 if (Previous.empty()) return false;
8932
8933 NamedDecl *Target = Orig;
8934 if (isa<UsingShadowDecl>(Target))
8935 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
8936
John McCalla17e83e2009-12-11 02:33:26 +00008937 // If the target happens to be one of the previous declarations, we
8938 // don't have a conflict.
8939 //
8940 // FIXME: but we might be increasing its access, in which case we
8941 // should redeclare it.
Craig Topperc3ec1492014-05-26 06:22:03 +00008942 NamedDecl *NonTag = nullptr, *Tag = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00008943 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00008944 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8945 I != E; ++I) {
8946 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithe5a91462016-02-27 02:36:43 +00008947 // We can have UsingDecls in our Previous results because we use the same
8948 // LookupResult for checking whether the UsingDecl itself is a valid
8949 // redeclaration.
Richard Smith151c4562016-12-20 21:35:28 +00008950 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
Richard Smithe5a91462016-02-27 02:36:43 +00008951 continue;
8952
Richard Smithfd8634a2013-10-23 02:17:46 +00008953 if (IsEquivalentForUsingDecl(Context, D, Target)) {
8954 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
8955 PrevShadow = Shadow;
8956 FoundEquivalentDecl = true;
Richard Smith2de44e62016-01-12 20:34:32 +00008957 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
8958 // We don't conflict with an existing using shadow decl of an equivalent
8959 // declaration, but we're not a redeclaration of it.
8960 FoundEquivalentDecl = true;
Richard Smithfd8634a2013-10-23 02:17:46 +00008961 }
John McCalla17e83e2009-12-11 02:33:26 +00008962
Richard Smithf091e122015-09-15 01:28:55 +00008963 if (isVisible(D))
8964 (isa<TagDecl>(D) ? Tag : NonTag) = D;
John McCalla17e83e2009-12-11 02:33:26 +00008965 }
8966
Richard Smithfd8634a2013-10-23 02:17:46 +00008967 if (FoundEquivalentDecl)
8968 return false;
8969
Alp Tokera2794f92014-01-22 07:29:52 +00008970 if (FunctionDecl *FD = Target->getAsFunction()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008971 NamedDecl *OldDecl = nullptr;
8972 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
8973 /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00008974 case Ovl_Overload:
8975 return false;
8976
8977 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00008978 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00008979 break;
Richard Smith18819302014-02-06 01:31:33 +00008980
John McCall84d87672009-12-10 09:41:52 +00008981 // We found a decl with the exact signature.
8982 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00008983 // If we're in a record, we want to hide the target, so we
8984 // return true (without a diagnostic) to tell the caller not to
8985 // build a shadow decl.
8986 if (CurContext->isRecord())
8987 return true;
8988
8989 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00008990 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00008991 break;
8992 }
8993
8994 Diag(Target->getLocation(), diag::note_using_decl_target);
8995 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
Richard Smith151c4562016-12-20 21:35:28 +00008996 Using->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00008997 return true;
8998 }
8999
9000 // Target is not a function.
9001
John McCall84d87672009-12-10 09:41:52 +00009002 if (isa<TagDecl>(Target)) {
9003 // No conflict between a tag and a non-tag.
9004 if (!Tag) return false;
9005
John McCalle29c5cd2009-12-10 19:51:03 +00009006 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00009007 Diag(Target->getLocation(), diag::note_using_decl_target);
9008 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
Richard Smith151c4562016-12-20 21:35:28 +00009009 Using->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00009010 return true;
9011 }
9012
9013 // No conflict between a tag and a non-tag.
9014 if (!NonTag) return false;
9015
John McCalle29c5cd2009-12-10 19:51:03 +00009016 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00009017 Diag(Target->getLocation(), diag::note_using_decl_target);
9018 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
Richard Smith151c4562016-12-20 21:35:28 +00009019 Using->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00009020 return true;
9021}
9022
Richard Smith5179eb72016-06-28 19:03:57 +00009023/// Determine whether a direct base class is a virtual base class.
9024static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9025 if (!Derived->getNumVBases())
9026 return false;
9027 for (auto &B : Derived->bases())
9028 if (B.getType()->getAsCXXRecordDecl() == Base)
9029 return B.isVirtual();
9030 llvm_unreachable("not a direct base class");
9031}
9032
John McCall3f746822009-11-17 05:59:44 +00009033/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00009034UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00009035 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00009036 NamedDecl *Orig,
9037 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00009038 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00009039 NamedDecl *Target = Orig;
9040 if (isa<UsingShadowDecl>(Target)) {
9041 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9042 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00009043 }
Richard Smithfd8634a2013-10-23 02:17:46 +00009044
Richard Smith5179eb72016-06-28 19:03:57 +00009045 NamedDecl *NonTemplateTarget = Target;
9046 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9047 NonTemplateTarget = TargetTD->getTemplatedDecl();
9048
9049 UsingShadowDecl *Shadow;
9050 if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
9051 bool IsVirtualBase =
9052 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9053 UD->getQualifier()->getAsRecordDecl());
9054 Shadow = ConstructorUsingShadowDecl::Create(
9055 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9056 } else {
9057 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9058 Target);
9059 }
John McCall3f746822009-11-17 05:59:44 +00009060 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00009061
Douglas Gregor457104e2010-09-29 04:25:11 +00009062 Shadow->setAccess(UD->getAccess());
9063 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9064 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00009065
9066 Shadow->setPreviousDecl(PrevDecl);
9067
John McCall3f746822009-11-17 05:59:44 +00009068 if (S)
John McCall3969e302009-12-08 07:46:18 +00009069 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00009070 else
John McCall3969e302009-12-08 07:46:18 +00009071 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00009072
John McCall3969e302009-12-08 07:46:18 +00009073
John McCall84d87672009-12-10 09:41:52 +00009074 return Shadow;
9075}
John McCall3969e302009-12-08 07:46:18 +00009076
John McCall84d87672009-12-10 09:41:52 +00009077/// Hides a using shadow declaration. This is required by the current
9078/// using-decl implementation when a resolvable using declaration in a
9079/// class is followed by a declaration which would hide or override
9080/// one or more of the using decl's targets; for example:
9081///
9082/// struct Base { void foo(int); };
9083/// struct Derived : Base {
9084/// using Base::foo;
9085/// void foo(int);
9086/// };
9087///
9088/// The governing language is C++03 [namespace.udecl]p12:
9089///
9090/// When a using-declaration brings names from a base class into a
9091/// derived class scope, member functions in the derived class
9092/// override and/or hide member functions with the same name and
9093/// parameter types in a base class (rather than conflicting).
9094///
9095/// There are two ways to implement this:
9096/// (1) optimistically create shadow decls when they're not hidden
9097/// by existing declarations, or
9098/// (2) don't create any shadow decls (or at least don't make them
9099/// visible) until we've fully parsed/instantiated the class.
9100/// The problem with (1) is that we might have to retroactively remove
9101/// a shadow decl, which requires several O(n) operations because the
9102/// decl structures are (very reasonably) not designed for removal.
9103/// (2) avoids this but is very fiddly and phase-dependent.
9104void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00009105 if (Shadow->getDeclName().getNameKind() ==
9106 DeclarationName::CXXConversionFunctionName)
9107 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9108
John McCall84d87672009-12-10 09:41:52 +00009109 // Remove it from the DeclContext...
9110 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00009111
John McCall84d87672009-12-10 09:41:52 +00009112 // ...and the scope, if applicable...
9113 if (S) {
John McCall48871652010-08-21 09:40:31 +00009114 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00009115 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00009116 }
9117
John McCall84d87672009-12-10 09:41:52 +00009118 // ...and the using decl.
9119 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9120
9121 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00009122 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00009123}
9124
Richard Smith09d5b3a2014-05-01 00:35:04 +00009125/// Find the base specifier for a base class with the given type.
9126static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9127 QualType DesiredBase,
9128 bool &AnyDependentBases) {
9129 // Check whether the named type is a direct base class.
9130 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9131 for (auto &Base : Derived->bases()) {
9132 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9133 if (CanonicalDesiredBase == BaseType)
9134 return &Base;
9135 if (BaseType->isDependentType())
9136 AnyDependentBases = true;
9137 }
Craig Topperc3ec1492014-05-26 06:22:03 +00009138 return nullptr;
Richard Smith09d5b3a2014-05-01 00:35:04 +00009139}
9140
Benjamin Kramer8bf44352013-07-24 15:28:33 +00009141namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009142class UsingValidatorCCC : public CorrectionCandidateCallback {
9143public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00009144 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
Richard Smith09d5b3a2014-05-01 00:35:04 +00009145 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009146 : HasTypenameKeyword(HasTypenameKeyword),
Richard Smith09d5b3a2014-05-01 00:35:04 +00009147 IsInstantiation(IsInstantiation), OldNNS(NNS),
9148 RequireMemberOf(RequireMemberOf) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009149
Craig Toppera798a9d2014-03-02 09:32:10 +00009150 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00009151 NamedDecl *ND = Candidate.getCorrectionDecl();
9152
9153 // Keywords are not valid here.
9154 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009155 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00009156
9157 // Completely unqualified names are invalid for a 'using' declaration.
9158 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9159 return false;
9160
Richard Smith9385d702016-05-14 01:58:49 +00009161 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9162 // reject.
9163
Richard Smith09d5b3a2014-05-01 00:35:04 +00009164 if (RequireMemberOf) {
9165 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9166 if (FoundRecord && FoundRecord->isInjectedClassName()) {
9167 // No-one ever wants a using-declaration to name an injected-class-name
9168 // of a base class, unless they're declaring an inheriting constructor.
9169 ASTContext &Ctx = ND->getASTContext();
9170 if (!Ctx.getLangOpts().CPlusPlus11)
9171 return false;
9172 QualType FoundType = Ctx.getRecordType(FoundRecord);
9173
9174 // Check that the injected-class-name is named as a member of its own
9175 // type; we don't want to suggest 'using Derived::Base;', since that
9176 // means something else.
9177 NestedNameSpecifier *Specifier =
9178 Candidate.WillReplaceSpecifier()
9179 ? Candidate.getCorrectionSpecifier()
9180 : OldNNS;
9181 if (!Specifier->getAsType() ||
9182 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9183 return false;
9184
9185 // Check that this inheriting constructor declaration actually names a
9186 // direct base class of the current class.
9187 bool AnyDependentBases = false;
9188 if (!findDirectBaseWithType(RequireMemberOf,
9189 Ctx.getRecordType(FoundRecord),
9190 AnyDependentBases) &&
9191 !AnyDependentBases)
9192 return false;
9193 } else {
9194 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9195 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9196 return false;
9197
9198 // FIXME: Check that the base class member is accessible?
9199 }
Kaelyn Takatad14c0612015-09-30 18:23:35 +00009200 } else {
9201 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9202 if (FoundRecord && FoundRecord->isInjectedClassName())
9203 return false;
Richard Smith09d5b3a2014-05-01 00:35:04 +00009204 }
9205
Benjamin Kramer8bf44352013-07-24 15:28:33 +00009206 if (isa<TypeDecl>(ND))
9207 return HasTypenameKeyword || !IsInstantiation;
9208
9209 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009210 }
9211
9212private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009213 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009214 bool IsInstantiation;
Richard Smith09d5b3a2014-05-01 00:35:04 +00009215 NestedNameSpecifier *OldNNS;
Richard Smith21866c32014-04-30 18:03:21 +00009216 CXXRecordDecl *RequireMemberOf;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009217};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00009218} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009219
John McCalle61f2ba2009-11-18 02:36:19 +00009220/// Builds a using declaration.
9221///
9222/// \param IsInstantiation - Whether this call arises from an
9223/// instantiation of an unresolved using declaration. We treat
9224/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00009225NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
9226 SourceLocation UsingLoc,
Richard Smith151c4562016-12-20 21:35:28 +00009227 bool HasTypenameKeyword,
9228 SourceLocation TypenameLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00009229 CXXScopeSpec &SS,
Richard Smith09d5b3a2014-05-01 00:35:04 +00009230 DeclarationNameInfo NameInfo,
Richard Smith151c4562016-12-20 21:35:28 +00009231 SourceLocation EllipsisLoc,
Anders Carlsson696a3f12009-08-28 05:40:36 +00009232 AttributeList *AttrList,
Richard Smith151c4562016-12-20 21:35:28 +00009233 bool IsInstantiation) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00009234 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00009235 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00009236 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00009237
Anders Carlssonf038fc22009-08-28 05:49:21 +00009238 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00009239
Richard Smith5179eb72016-06-28 19:03:57 +00009240 // For an inheriting constructor declaration, the name of the using
9241 // declaration is the name of a constructor in this class, not in the
9242 // base class.
9243 DeclarationNameInfo UsingName = NameInfo;
9244 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9245 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9246 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9247 Context.getCanonicalType(Context.getRecordType(RD))));
9248
John McCall84d87672009-12-10 09:41:52 +00009249 // Do the redeclaration lookup in the current scope.
Richard Smith5179eb72016-06-28 19:03:57 +00009250 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00009251 ForRedeclaration);
9252 Previous.setHideTags(false);
9253 if (S) {
9254 LookupName(Previous, S);
9255
9256 // It is really dumb that we have to do this.
9257 LookupResult::Filter F = Previous.makeFilter();
9258 while (F.hasNext()) {
9259 NamedDecl *D = F.next();
9260 if (!isDeclInScope(D, CurContext, S))
9261 F.erase();
Richard Smith83e78f52014-04-11 01:03:38 +00009262 // If we found a local extern declaration that's not ordinarily visible,
9263 // and this declaration is being added to a non-block scope, ignore it.
9264 // We're only checking for scope conflicts here, not also for violations
9265 // of the linkage rules.
9266 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9267 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9268 F.erase();
John McCall84d87672009-12-10 09:41:52 +00009269 }
9270 F.done();
9271 } else {
9272 assert(IsInstantiation && "no scope in non-instantiation");
Richard Smithd8a9e372016-12-18 21:39:37 +00009273 if (CurContext->isRecord())
9274 LookupQualifiedName(Previous, CurContext);
9275 else {
9276 // No redeclaration check is needed here; in non-member contexts we
9277 // diagnosed all possible conflicts with other using-declarations when
9278 // building the template:
9279 //
9280 // For a dependent non-type using declaration, the only valid case is
9281 // if we instantiate to a single enumerator. We check for conflicts
9282 // between shadow declarations we introduce, and we check in the template
9283 // definition for conflicts between a non-type using declaration and any
9284 // other declaration, which together covers all cases.
9285 //
9286 // A dependent typename using declaration will never successfully
9287 // instantiate, since it will always name a class member, so we reject
9288 // that in the template definition.
9289 }
John McCall84d87672009-12-10 09:41:52 +00009290 }
9291
John McCall84d87672009-12-10 09:41:52 +00009292 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009293 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9294 SS, IdentLoc, Previous))
Craig Topperc3ec1492014-05-26 06:22:03 +00009295 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00009296
9297 // Check for bad qualifiers.
Richard Smithd8a9e372016-12-18 21:39:37 +00009298 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
9299 IdentLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00009300 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00009301
John McCall84c16cf2009-11-12 03:15:40 +00009302 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00009303 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009304 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Richard Smith151c4562016-12-20 21:35:28 +00009305 if (!LookupContext || EllipsisLoc.isValid()) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009306 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00009307 // FIXME: not all declaration name kinds are legal here
9308 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9309 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009310 QualifierLoc,
Richard Smith151c4562016-12-20 21:35:28 +00009311 IdentLoc, NameInfo.getName(),
9312 EllipsisLoc);
John McCallb96ec562009-12-04 22:46:56 +00009313 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009314 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
Richard Smith151c4562016-12-20 21:35:28 +00009315 QualifierLoc, NameInfo, EllipsisLoc);
John McCalle61f2ba2009-11-18 02:36:19 +00009316 }
Richard Smith09d5b3a2014-05-01 00:35:04 +00009317 D->setAccess(AS);
9318 CurContext->addDecl(D);
9319 return D;
Anders Carlssonf038fc22009-08-28 05:49:21 +00009320 }
John McCallb96ec562009-12-04 22:46:56 +00009321
Richard Smith09d5b3a2014-05-01 00:35:04 +00009322 auto Build = [&](bool Invalid) {
9323 UsingDecl *UD =
Richard Smith5179eb72016-06-28 19:03:57 +00009324 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
9325 UsingName, HasTypenameKeyword);
Richard Smith09d5b3a2014-05-01 00:35:04 +00009326 UD->setAccess(AS);
9327 CurContext->addDecl(UD);
9328 UD->setInvalidDecl(Invalid);
John McCall3969e302009-12-08 07:46:18 +00009329 return UD;
Richard Smith09d5b3a2014-05-01 00:35:04 +00009330 };
9331 auto BuildInvalid = [&]{ return Build(true); };
9332 auto BuildValid = [&]{ return Build(false); };
9333
9334 if (RequireCompleteDeclContext(SS, LookupContext))
9335 return BuildInvalid();
Anders Carlsson59140b32009-08-28 03:16:11 +00009336
Richard Smith78163e22015-04-01 19:31:06 +00009337 // Look up the target name.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00009338 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00009339
John McCall3969e302009-12-08 07:46:18 +00009340 // Unlike most lookups, we don't always want to hide tag
9341 // declarations: tag names are visible through the using declaration
9342 // even if hidden by ordinary names, *except* in a dependent context
9343 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00009344 if (!IsInstantiation)
9345 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00009346
John McCall5dadb652012-04-07 03:04:20 +00009347 // For the purposes of this lookup, we have a base object type
9348 // equal to that of the current context.
9349 if (CurContext->isRecord()) {
9350 R.setBaseObjectType(
9351 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
9352 }
9353
John McCall27b18f82009-11-17 02:14:36 +00009354 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00009355
Richard Smith78163e22015-04-01 19:31:06 +00009356 // Try to correct typos if possible. If constructor name lookup finds no
9357 // results, that means the named class has no explicit constructors, and we
9358 // suppressed declaring implicit ones (probably because it's dependent or
9359 // invalid).
9360 if (R.empty() &&
9361 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
Richard Smith46d04a32017-01-08 04:01:15 +00009362 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
9363 // it will believe that glibc provides a ::gets in cases where it does not,
9364 // and will try to pull it into namespace std with a using-declaration.
9365 // Just ignore the using-declaration in that case.
9366 auto *II = NameInfo.getName().getAsIdentifierInfo();
9367 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
9368 CurContext->isStdNamespace() &&
9369 isa<TranslationUnitDecl>(LookupContext) &&
9370 getSourceManager().isInSystemHeader(UsingLoc))
9371 return nullptr;
Kaelyn Takata89c881b2014-10-27 18:07:29 +00009372 if (TypoCorrection Corrected = CorrectTypo(
9373 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
9374 llvm::make_unique<UsingValidatorCCC>(
9375 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
9376 dyn_cast<CXXRecordDecl>(CurContext)),
9377 CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00009378 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009379 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00009380 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
9381 << NameInfo.getName() << LookupContext << 0
9382 << SS.getRange());
Richard Smith09d5b3a2014-05-01 00:35:04 +00009383
Benjamin Kramerae65d222017-01-24 12:49:59 +00009384 // If we picked a correction with no attached Decl we can't do anything
9385 // useful with it, bail out.
9386 NamedDecl *ND = Corrected.getCorrectionDecl();
9387 if (!ND)
9388 return BuildInvalid();
9389
Richard Smith09d5b3a2014-05-01 00:35:04 +00009390 // If we corrected to an inheriting constructor, handle it as one.
9391 auto *RD = dyn_cast<CXXRecordDecl>(ND);
9392 if (RD && RD->isInjectedClassName()) {
Richard Smith5179eb72016-06-28 19:03:57 +00009393 // The parent of the injected class name is the class itself.
9394 RD = cast<CXXRecordDecl>(RD->getParent());
9395
Richard Smith09d5b3a2014-05-01 00:35:04 +00009396 // Fix up the information we'll use to build the using declaration.
9397 if (Corrected.WillReplaceSpecifier()) {
9398 NestedNameSpecifierLocBuilder Builder;
9399 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
9400 QualifierLoc.getSourceRange());
9401 QualifierLoc = Builder.getWithLocInContext(Context);
9402 }
9403
Richard Smith5179eb72016-06-28 19:03:57 +00009404 // In this case, the name we introduce is the name of a derived class
9405 // constructor.
9406 auto *CurClass = cast<CXXRecordDecl>(CurContext);
9407 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9408 Context.getCanonicalType(Context.getRecordType(CurClass))));
9409 UsingName.setNamedTypeInfo(nullptr);
Richard Smith78163e22015-04-01 19:31:06 +00009410 for (auto *Ctor : LookupConstructors(RD))
9411 R.addDecl(Ctor);
Richard Smith5179eb72016-06-28 19:03:57 +00009412 R.resolveKind();
Richard Smith78163e22015-04-01 19:31:06 +00009413 } else {
Richard Smith5179eb72016-06-28 19:03:57 +00009414 // FIXME: Pick up all the declarations if we found an overloaded
9415 // function.
9416 UsingName.setName(ND->getDeclName());
Richard Smith78163e22015-04-01 19:31:06 +00009417 R.addDecl(ND);
Richard Smith09d5b3a2014-05-01 00:35:04 +00009418 }
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009419 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00009420 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009421 << NameInfo.getName() << LookupContext << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00009422 return BuildInvalid();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009423 }
Douglas Gregorfec52632009-06-20 00:51:54 +00009424 }
9425
Richard Smith09d5b3a2014-05-01 00:35:04 +00009426 if (R.isAmbiguous())
9427 return BuildInvalid();
Mike Stump11289f42009-09-09 15:08:12 +00009428
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009429 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00009430 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00009431 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00009432 Diag(IdentLoc, diag::err_using_typename_non_type);
9433 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9434 Diag((*I)->getUnderlyingDecl()->getLocation(),
9435 diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00009436 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00009437 }
9438 } else {
9439 // If we asked for a non-typename and we got a type, error out,
9440 // but only if this is an instantiation of an unresolved using
9441 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00009442 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00009443 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
9444 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00009445 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00009446 }
Anders Carlsson59140b32009-08-28 03:16:11 +00009447 }
9448
Richard Smith5cbeb752016-05-05 02:13:49 +00009449 // C++14 [namespace.udecl]p6:
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00009450 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00009451 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00009452 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
9453 << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00009454 return BuildInvalid();
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00009455 }
Mike Stump11289f42009-09-09 15:08:12 +00009456
Richard Smith5cbeb752016-05-05 02:13:49 +00009457 // C++14 [namespace.udecl]p7:
9458 // A using-declaration shall not name a scoped enumerator.
9459 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
9460 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
9461 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
9462 << SS.getRange();
9463 return BuildInvalid();
9464 }
9465 }
9466
Richard Smith09d5b3a2014-05-01 00:35:04 +00009467 UsingDecl *UD = BuildValid();
Richard Smith78163e22015-04-01 19:31:06 +00009468
Richard Smith5179eb72016-06-28 19:03:57 +00009469 // Some additional rules apply to inheriting constructors.
9470 if (UsingName.getName().getNameKind() ==
9471 DeclarationName::CXXConstructorName) {
Richard Smith78163e22015-04-01 19:31:06 +00009472 // Suppress access diagnostics; the access check is instead performed at the
9473 // point of use for an inheriting constructor.
9474 R.suppressDiagnostics();
Richard Smith5179eb72016-06-28 19:03:57 +00009475 if (CheckInheritingConstructorUsingDecl(UD))
9476 return UD;
Richard Smith78163e22015-04-01 19:31:06 +00009477 }
9478
John McCall84d87672009-12-10 09:41:52 +00009479 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00009480 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00009481 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
9482 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00009483 }
John McCall3f746822009-11-17 05:59:44 +00009484
9485 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00009486}
9487
Richard Smith151c4562016-12-20 21:35:28 +00009488NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
9489 ArrayRef<NamedDecl *> Expansions) {
9490 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
9491 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
9492 isa<UsingPackDecl>(InstantiatedFrom));
9493
9494 auto *UPD =
9495 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
9496 UPD->setAccess(InstantiatedFrom->getAccess());
9497 CurContext->addDecl(UPD);
9498 return UPD;
9499}
9500
Sebastian Redl08905022011-02-05 19:23:19 +00009501/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00009502bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009503 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00009504
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009505 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00009506 assert(SourceType &&
9507 "Using decl naming constructor doesn't have type in scope spec.");
9508 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
9509
9510 // Check whether the named type is a direct base class.
Richard Smith09d5b3a2014-05-01 00:35:04 +00009511 bool AnyDependentBases = false;
9512 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
9513 AnyDependentBases);
9514 if (!Base && !AnyDependentBases) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009515 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00009516 diag::err_using_decl_constructor_not_in_direct_base)
9517 << UD->getNameInfo().getSourceRange()
9518 << QualType(SourceType, 0) << TargetClass;
Richard Smith09d5b3a2014-05-01 00:35:04 +00009519 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00009520 return true;
9521 }
9522
Richard Smith09d5b3a2014-05-01 00:35:04 +00009523 if (Base)
9524 Base->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00009525
9526 return false;
9527}
9528
John McCall84d87672009-12-10 09:41:52 +00009529/// Checks that the given using declaration is not an invalid
9530/// redeclaration. Note that this is checking only for the using decl
9531/// itself, not for any ill-formedness among the UsingShadowDecls.
9532bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009533 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00009534 const CXXScopeSpec &SS,
9535 SourceLocation NameLoc,
9536 const LookupResult &Prev) {
Richard Smith4eeaec42016-12-18 22:01:46 +00009537 NestedNameSpecifier *Qual = SS.getScopeRep();
9538
John McCall84d87672009-12-10 09:41:52 +00009539 // C++03 [namespace.udecl]p8:
9540 // C++0x [namespace.udecl]p10:
9541 // A using-declaration is a declaration and can therefore be used
9542 // repeatedly where (and only where) multiple declarations are
9543 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00009544 //
John McCall032092f2010-11-29 18:01:58 +00009545 // That's in non-member contexts.
Richard Smith4eeaec42016-12-18 22:01:46 +00009546 if (!CurContext->getRedeclContext()->isRecord()) {
9547 // A dependent qualifier outside a class can only ever resolve to an
9548 // enumeration type. Therefore it conflicts with any other non-type
9549 // declaration in the same scope.
9550 // FIXME: How should we check for dependent type-type conflicts at block
9551 // scope?
9552 if (Qual->isDependent() && !HasTypenameKeyword) {
9553 for (auto *D : Prev) {
Richard Smith151c4562016-12-20 21:35:28 +00009554 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
Richard Smith4eeaec42016-12-18 22:01:46 +00009555 bool OldCouldBeEnumerator =
9556 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
9557 Diag(NameLoc,
9558 OldCouldBeEnumerator ? diag::err_redefinition
9559 : diag::err_redefinition_different_kind)
9560 << Prev.getLookupName();
9561 Diag(D->getLocation(), diag::note_previous_definition);
9562 return true;
9563 }
9564 }
9565 }
John McCall84d87672009-12-10 09:41:52 +00009566 return false;
Richard Smith4eeaec42016-12-18 22:01:46 +00009567 }
John McCall84d87672009-12-10 09:41:52 +00009568
9569 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
9570 NamedDecl *D = *I;
9571
9572 bool DTypename;
9573 NestedNameSpecifier *DQual;
9574 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009575 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009576 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00009577 } else if (UnresolvedUsingValueDecl *UD
9578 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
9579 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009580 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00009581 } else if (UnresolvedUsingTypenameDecl *UD
9582 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
9583 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009584 DQual = UD->getQualifier();
Richard Smith4eeaec42016-12-18 22:01:46 +00009585 } else continue;
John McCall84d87672009-12-10 09:41:52 +00009586
9587 // using decls differ if one says 'typename' and the other doesn't.
9588 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009589 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00009590
9591 // using decls differ if they name different scopes (but note that
9592 // template instantiation can cause this check to trigger when it
9593 // didn't before instantiation).
9594 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
9595 Context.getCanonicalNestedNameSpecifier(DQual))
9596 continue;
9597
9598 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00009599 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00009600 return true;
9601 }
9602
9603 return false;
9604}
9605
John McCall3969e302009-12-08 07:46:18 +00009606
John McCallb96ec562009-12-04 22:46:56 +00009607/// Checks that the given nested-name qualifier used in a using decl
9608/// in the current context is appropriately related to the current
9609/// scope. If an error is found, diagnoses it and returns true.
9610bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
Richard Smithd8a9e372016-12-18 21:39:37 +00009611 bool HasTypename,
John McCallb96ec562009-12-04 22:46:56 +00009612 const CXXScopeSpec &SS,
Richard Smith7ad0b882014-04-02 21:44:35 +00009613 const DeclarationNameInfo &NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00009614 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00009615 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00009616
John McCall3969e302009-12-08 07:46:18 +00009617 if (!CurContext->isRecord()) {
9618 // C++03 [namespace.udecl]p3:
9619 // C++0x [namespace.udecl]p8:
9620 // A using-declaration for a class member shall be a member-declaration.
9621
Richard Smithd8a9e372016-12-18 21:39:37 +00009622 // If we weren't able to compute a valid scope, it might validly be a
9623 // dependent class scope or a dependent enumeration unscoped scope. If
9624 // we have a 'typename' keyword, the scope must resolve to a class type.
9625 if ((HasTypename && !NamedContext) ||
9626 (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
Richard Smith5cbeb752016-05-05 02:13:49 +00009627 auto *RD = NamedContext
9628 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
9629 : nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00009630 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
Craig Topperc3ec1492014-05-26 06:22:03 +00009631 RD = nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00009632
John McCall3969e302009-12-08 07:46:18 +00009633 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
9634 << SS.getRange();
Richard Smith7ad0b882014-04-02 21:44:35 +00009635
9636 // If we have a complete, non-dependent source type, try to suggest a
9637 // way to get the same effect.
9638 if (!RD)
9639 return true;
9640
9641 // Find what this using-declaration was referring to.
9642 LookupResult R(*this, NameInfo, LookupOrdinaryName);
9643 R.setHideTags(false);
9644 R.suppressDiagnostics();
9645 LookupQualifiedName(R, RD);
9646
9647 if (R.getAsSingle<TypeDecl>()) {
9648 if (getLangOpts().CPlusPlus11) {
9649 // Convert 'using X::Y;' to 'using Y = X::Y;'.
9650 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
9651 << 0 // alias declaration
9652 << FixItHint::CreateInsertion(SS.getBeginLoc(),
9653 NameInfo.getName().getAsString() +
9654 " = ");
9655 } else {
9656 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
9657 SourceLocation InsertLoc =
Craig Topper07fa1762015-11-15 02:31:46 +00009658 getLocForEndOfToken(NameInfo.getLocEnd());
Richard Smith7ad0b882014-04-02 21:44:35 +00009659 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
9660 << 1 // typedef declaration
9661 << FixItHint::CreateReplacement(UsingLoc, "typedef")
9662 << FixItHint::CreateInsertion(
9663 InsertLoc, " " + NameInfo.getName().getAsString());
9664 }
9665 } else if (R.getAsSingle<VarDecl>()) {
9666 // Don't provide a fixit outside C++11 mode; we don't want to suggest
9667 // repeating the type of the static data member here.
9668 FixItHint FixIt;
9669 if (getLangOpts().CPlusPlus11) {
9670 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9671 FixIt = FixItHint::CreateReplacement(
9672 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
9673 }
9674
9675 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9676 << 2 // reference declaration
9677 << FixIt;
Richard Smithdce10ea2016-05-05 19:16:15 +00009678 } else if (R.getAsSingle<EnumConstantDecl>()) {
9679 // Don't provide a fixit outside C++11 mode; we don't want to suggest
9680 // repeating the type of the enumeration here, and we can't do so if
9681 // the type is anonymous.
9682 FixItHint FixIt;
9683 if (getLangOpts().CPlusPlus11) {
9684 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9685 FixIt = FixItHint::CreateReplacement(
Richard Smithd8a9e372016-12-18 21:39:37 +00009686 UsingLoc,
9687 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
Richard Smithdce10ea2016-05-05 19:16:15 +00009688 }
9689
9690 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9691 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
9692 << FixIt;
Richard Smith7ad0b882014-04-02 21:44:35 +00009693 }
John McCall3969e302009-12-08 07:46:18 +00009694 return true;
9695 }
9696
Richard Smithd8a9e372016-12-18 21:39:37 +00009697 // Otherwise, this might be valid.
John McCall3969e302009-12-08 07:46:18 +00009698 return false;
9699 }
9700
9701 // The current scope is a record.
9702
9703 // If the named context is dependent, we can't decide much.
9704 if (!NamedContext) {
9705 // FIXME: in C++0x, we can diagnose if we can prove that the
9706 // nested-name-specifier does not refer to a base class, which is
9707 // still possible in some cases.
9708
9709 // Otherwise we have to conservatively report that things might be
9710 // okay.
9711 return false;
9712 }
9713
9714 if (!NamedContext->isRecord()) {
9715 // Ideally this would point at the last name in the specifier,
9716 // but we don't have that level of source info.
9717 Diag(SS.getRange().getBegin(),
9718 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00009719 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00009720 return true;
9721 }
9722
Douglas Gregor7c842292010-12-21 07:41:49 +00009723 if (!NamedContext->isDependentContext() &&
9724 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
9725 return true;
9726
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009727 if (getLangOpts().CPlusPlus11) {
Richard Smith5cbeb752016-05-05 02:13:49 +00009728 // C++11 [namespace.udecl]p3:
John McCall3969e302009-12-08 07:46:18 +00009729 // In a using-declaration used as a member-declaration, the
9730 // nested-name-specifier shall name a base class of the class
9731 // being defined.
9732
9733 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
9734 cast<CXXRecordDecl>(NamedContext))) {
9735 if (CurContext == NamedContext) {
9736 Diag(NameLoc,
9737 diag::err_using_decl_nested_name_specifier_is_current_class)
9738 << SS.getRange();
9739 return true;
9740 }
9741
Eric Fiselier7ae80c62016-10-10 14:26:40 +00009742 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
9743 Diag(SS.getRange().getBegin(),
9744 diag::err_using_decl_nested_name_specifier_is_not_base_class)
9745 << SS.getScopeRep()
9746 << cast<CXXRecordDecl>(CurContext)
9747 << SS.getRange();
9748 }
John McCall3969e302009-12-08 07:46:18 +00009749 return true;
9750 }
9751
9752 return false;
9753 }
9754
9755 // C++03 [namespace.udecl]p4:
9756 // A using-declaration used as a member-declaration shall refer
9757 // to a member of a base class of the class being defined [etc.].
9758
9759 // Salient point: SS doesn't have to name a base class as long as
9760 // lookup only finds members from base classes. Therefore we can
9761 // diagnose here only if we can prove that that can't happen,
9762 // i.e. if the class hierarchies provably don't intersect.
9763
9764 // TODO: it would be nice if "definitely valid" results were cached
9765 // in the UsingDecl and UsingShadowDecl so that these checks didn't
9766 // need to be repeated.
9767
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00009768 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
9769 auto Collect = [&Bases](const CXXRecordDecl *Base) {
9770 Bases.insert(Base);
9771 return true;
John McCall3969e302009-12-08 07:46:18 +00009772 };
9773
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00009774 // Collect all bases. Return false if we find a dependent base.
9775 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
John McCall3969e302009-12-08 07:46:18 +00009776 return false;
9777
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00009778 // Returns true if the base is dependent or is one of the accumulated base
9779 // classes.
9780 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
9781 return !Bases.count(Base);
9782 };
9783
9784 // Return false if the class has a dependent base or if it or one
John McCall3969e302009-12-08 07:46:18 +00009785 // of its bases is present in the base set of the current context.
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00009786 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
9787 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
John McCall3969e302009-12-08 07:46:18 +00009788 return false;
9789
9790 Diag(SS.getRange().getBegin(),
9791 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00009792 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00009793 << cast<CXXRecordDecl>(CurContext)
9794 << SS.getRange();
9795
9796 return true;
John McCallb96ec562009-12-04 22:46:56 +00009797}
9798
Richard Smithdda56e42011-04-15 14:24:37 +00009799Decl *Sema::ActOnAliasDeclaration(Scope *S,
9800 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00009801 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00009802 SourceLocation UsingLoc,
9803 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00009804 AttributeList *AttrList,
David Majnemerf9bde282015-03-11 06:45:39 +00009805 TypeResult Type,
9806 Decl *DeclFromDeclSpec) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00009807 // Skip up to the relevant declaration scope.
Davide Italiano5be22332015-11-11 20:06:35 +00009808 while (S->isTemplateParamScope())
Richard Smith3f1b5d02011-05-05 21:57:07 +00009809 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00009810 assert((S->getFlags() & Scope::DeclScope) &&
9811 "got alias-declaration outside of declaration scope");
9812
9813 if (Type.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00009814 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00009815
9816 bool Invalid = false;
9817 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
Craig Topperc3ec1492014-05-26 06:22:03 +00009818 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky82e47802011-05-02 01:07:19 +00009819 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00009820
9821 if (DiagnoseClassNameShadow(CurContext, NameInfo))
Craig Topperc3ec1492014-05-26 06:22:03 +00009822 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00009823
9824 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00009825 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00009826 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00009827 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9828 TInfo->getTypeLoc().getBeginLoc());
9829 }
Richard Smithdda56e42011-04-15 14:24:37 +00009830
9831 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
9832 LookupName(Previous, S);
9833
9834 // Warn about shadowing the name of a template parameter.
9835 if (Previous.isSingleResult() &&
9836 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00009837 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00009838 Previous.clear();
9839 }
9840
9841 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
9842 "name in alias declaration must be an identifier");
9843 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
9844 Name.StartLocation,
9845 Name.Identifier, TInfo);
9846
9847 NewTD->setAccess(AS);
9848
9849 if (Invalid)
9850 NewTD->setInvalidDecl();
9851
Richard Smith54ecd982013-02-20 19:22:51 +00009852 ProcessDeclAttributeList(S, NewTD, AttrList);
9853
Richard Smith3f1b5d02011-05-05 21:57:07 +00009854 CheckTypedefForVariablyModifiedType(S, NewTD);
9855 Invalid |= NewTD->isInvalidDecl();
9856
Richard Smithdda56e42011-04-15 14:24:37 +00009857 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00009858
9859 NamedDecl *NewND;
9860 if (TemplateParamLists.size()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00009861 TypeAliasTemplateDecl *OldDecl = nullptr;
9862 TemplateParameterList *OldTemplateParams = nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00009863
9864 if (TemplateParamLists.size() != 1) {
9865 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009866 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
9867 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00009868 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009869 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00009870
Richard Smith882593f2016-04-06 17:38:58 +00009871 // Check that we can declare a template here.
9872 if (CheckTemplateDeclScope(S, TemplateParams))
9873 return nullptr;
9874
Richard Smith3f1b5d02011-05-05 21:57:07 +00009875 // Only consider previous declarations in the same scope.
9876 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
9877 /*ExplicitInstantiationOrSpecialization*/false);
9878 if (!Previous.empty()) {
9879 Redeclaration = true;
9880
9881 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
9882 if (!OldDecl && !Invalid) {
9883 Diag(UsingLoc, diag::err_redefinition_different_kind)
9884 << Name.Identifier;
9885
9886 NamedDecl *OldD = Previous.getRepresentativeDecl();
9887 if (OldD->getLocation().isValid())
9888 Diag(OldD->getLocation(), diag::note_previous_definition);
9889
9890 Invalid = true;
9891 }
9892
9893 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
9894 if (TemplateParameterListsAreEqual(TemplateParams,
9895 OldDecl->getTemplateParameters(),
9896 /*Complain=*/true,
9897 TPL_TemplateMatch))
9898 OldTemplateParams = OldDecl->getTemplateParameters();
9899 else
9900 Invalid = true;
9901
9902 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
9903 if (!Invalid &&
9904 !Context.hasSameType(OldTD->getUnderlyingType(),
9905 NewTD->getUnderlyingType())) {
9906 // FIXME: The C++0x standard does not clearly say this is ill-formed,
9907 // but we can't reasonably accept it.
9908 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
9909 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
9910 if (OldTD->getLocation().isValid())
9911 Diag(OldTD->getLocation(), diag::note_previous_definition);
9912 Invalid = true;
9913 }
9914 }
9915 }
9916
9917 // Merge any previous default template arguments into our parameters,
9918 // and check the parameter list.
9919 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
9920 TPC_TypeAliasTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +00009921 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00009922
9923 TypeAliasTemplateDecl *NewDecl =
9924 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
9925 Name.Identifier, TemplateParams,
9926 NewTD);
Richard Smith43ccec8e2014-08-26 03:52:16 +00009927 NewTD->setDescribedAliasTemplate(NewDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00009928
9929 NewDecl->setAccess(AS);
9930
9931 if (Invalid)
9932 NewDecl->setInvalidDecl();
9933 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00009934 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00009935
9936 NewND = NewDecl;
9937 } else {
David Majnemerf9bde282015-03-11 06:45:39 +00009938 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
9939 setTagNameForLinkagePurposes(TD, NewTD);
9940 handleTagNumbering(TD, S);
9941 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00009942 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
9943 NewND = NewTD;
9944 }
Richard Smithdda56e42011-04-15 14:24:37 +00009945
Richard Smith3cbf3f12016-07-15 20:53:25 +00009946 PushOnScopeChains(NewND, S);
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00009947 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00009948 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00009949}
9950
Richard Smithf4634362014-09-03 23:11:22 +00009951Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
9952 SourceLocation AliasLoc,
9953 IdentifierInfo *Alias, CXXScopeSpec &SS,
9954 SourceLocation IdentLoc,
9955 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00009956
Anders Carlssonbb1e4722009-03-28 23:53:49 +00009957 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00009958 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
9959 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00009960
John McCall27b18f82009-11-17 02:14:36 +00009961 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00009962 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00009963
John McCall9f3059a2009-10-09 21:13:30 +00009964 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00009965 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00009966 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00009967 return nullptr;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00009968 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00009969 }
Richard Smithf4634362014-09-03 23:11:22 +00009970 assert(!R.isAmbiguous() && !R.empty());
Richard Smithf2005d32015-12-29 23:34:32 +00009971 NamedDecl *ND = R.getRepresentativeDecl();
Richard Smithf4634362014-09-03 23:11:22 +00009972
9973 // Check if we have a previous declaration with the same name.
Richard Smith10568d82015-11-17 03:02:41 +00009974 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
9975 ForRedeclaration);
Richard Smith2b2a1762015-12-03 23:24:04 +00009976 LookupName(PrevR, S);
Richard Smithf4634362014-09-03 23:11:22 +00009977
Richard Smith2b2a1762015-12-03 23:24:04 +00009978 // Check we're not shadowing a template parameter.
9979 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
9980 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
9981 PrevR.clear();
9982 }
Aaron Ballman43f40102014-11-14 22:34:56 +00009983
Richard Smith2b2a1762015-12-03 23:24:04 +00009984 // Filter out any other lookup result from an enclosing scope.
9985 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
9986 /*AllowInlineNamespace*/false);
9987
9988 // Find the previous declaration and check that we can redeclare it.
9989 NamespaceAliasDecl *Prev = nullptr;
Richard Smith7d8d6722015-12-29 23:42:34 +00009990 if (PrevR.isSingleResult()) {
9991 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
9992 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Richard Smithf4634362014-09-03 23:11:22 +00009993 // We already have an alias with the same name that points to the same
9994 // namespace; check that it matches.
Richard Smith2b2a1762015-12-03 23:24:04 +00009995 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
9996 Prev = AD;
9997 } else if (isVisible(PrevDecl)) {
Richard Smithf4634362014-09-03 23:11:22 +00009998 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
9999 << Alias;
Richard Smithf2005d32015-12-29 23:34:32 +000010000 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
Richard Smithf4634362014-09-03 23:11:22 +000010001 << AD->getNamespace();
10002 return nullptr;
10003 }
Richard Smith2b2a1762015-12-03 23:24:04 +000010004 } else if (isVisible(PrevDecl)) {
Richard Smith7d8d6722015-12-29 23:42:34 +000010005 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
Richard Smithf4634362014-09-03 23:11:22 +000010006 ? diag::err_redefinition
10007 : diag::err_redefinition_different_kind;
10008 Diag(AliasLoc, DiagID) << Alias;
10009 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10010 return nullptr;
10011 }
10012 }
Mike Stump11289f42009-09-09 15:08:12 +000010013
Nico Riecke50e59a2014-11-24 17:29:52 +000010014 // The use of a nested name specifier may trigger deprecation warnings.
Aaron Ballman43f40102014-11-14 22:34:56 +000010015 DiagnoseUseOfDecl(ND, IdentLoc);
10016
Fariborz Jahanian423a81f2009-06-19 19:55:27 +000010017 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +000010018 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +000010019 Alias, SS.getWithLocInContext(Context),
Aaron Ballman43f40102014-11-14 22:34:56 +000010020 IdentLoc, ND);
Richard Smith2b2a1762015-12-03 23:24:04 +000010021 if (Prev)
10022 AliasDecl->setPreviousDecl(Prev);
Mike Stump11289f42009-09-09 15:08:12 +000010023
John McCalld8d0d432010-02-16 06:53:13 +000010024 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +000010025 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +000010026}
10027
Alexis Hunt6d5b96c2011-05-10 00:49:42 +000010028Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010029Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
10030 CXXMethodDecl *MD) {
10031 CXXRecordDecl *ClassDecl = MD->getParent();
10032
Douglas Gregor6d880b12010-07-01 22:31:05 +000010033 // C++ [except.spec]p14:
10034 // An implicitly declared special member function (Clause 12) shall have an
10035 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000010036 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +000010037 if (ClassDecl->isInvalidDecl())
10038 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +000010039
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010040 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000010041 for (const auto &B : ClassDecl->bases()) {
10042 if (B.isVirtual()) // Handled below.
Douglas Gregor6d880b12010-07-01 22:31:05 +000010043 continue;
10044
Aaron Ballman574705e2014-03-13 15:41:46 +000010045 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +000010046 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +000010047 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
10048 // If this is a deleted function, add it anyway. This might be conformant
10049 // with the standard. This might not. I'm not sure. It might not matter.
10050 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +000010051 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +000010052 }
Douglas Gregor6d880b12010-07-01 22:31:05 +000010053 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010054
10055 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000010056 for (const auto &B : ClassDecl->vbases()) {
10057 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +000010058 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +000010059 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
10060 // If this is a deleted function, add it anyway. This might be conformant
10061 // with the standard. This might not. I'm not sure. It might not matter.
10062 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000010063 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +000010064 }
Douglas Gregor6d880b12010-07-01 22:31:05 +000010065 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010066
10067 // Field constructors.
Richard Smithd6a15082017-01-07 00:48:55 +000010068 for (auto *F : ClassDecl->fields()) {
Richard Smith938f40b2011-06-11 17:19:42 +000010069 if (F->hasInClassInitializer()) {
Richard Smithd6a15082017-01-07 00:48:55 +000010070 Expr *E = F->getInClassInitializer();
10071 if (!E)
10072 // FIXME: It's a little wasteful to build and throw away a
10073 // CXXDefaultInitExpr here.
10074 E = BuildCXXDefaultInitExpr(Loc, F).get();
10075 if (E)
Richard Smith938f40b2011-06-11 17:19:42 +000010076 ExceptSpec.CalledExpr(E);
Richard Smith938f40b2011-06-11 17:19:42 +000010077 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +000010078 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +000010079 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
10080 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
10081 // If this is a deleted function, add it anyway. This might be conformant
10082 // with the standard. This might not. I'm not sure. It might not matter.
10083 // In particular, the problem is that this function never gets called. It
10084 // might just be ill-formed because this function attempts to refer to
10085 // a deleted function here.
10086 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000010087 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +000010088 }
Douglas Gregor6d880b12010-07-01 22:31:05 +000010089 }
John McCalldb40c7f2010-12-14 08:05:40 +000010090
Alexis Hunt6d5b96c2011-05-10 00:49:42 +000010091 return ExceptSpec;
10092}
10093
Richard Smithc2bc61b2013-03-18 21:12:30 +000010094Sema::ImplicitExceptionSpecification
Richard Smith5179eb72016-06-28 19:03:57 +000010095Sema::ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
10096 CXXConstructorDecl *CD) {
Richard Smithb7151b92013-04-10 06:11:48 +000010097 CXXRecordDecl *ClassDecl = CD->getParent();
10098
10099 // C++ [except.spec]p14:
10100 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +000010101 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +000010102 if (ClassDecl->isInvalidDecl())
10103 return ExceptSpec;
10104
Richard Smith5179eb72016-06-28 19:03:57 +000010105 auto Inherited = CD->getInheritedConstructor();
10106 InheritedConstructorInfo ICI(*this, Loc, Inherited.getShadowDecl());
Richard Smithb7151b92013-04-10 06:11:48 +000010107
Richard Smith5179eb72016-06-28 19:03:57 +000010108 // Direct and virtual base-class constructors.
10109 for (bool VBase : {false, true}) {
10110 for (CXXBaseSpecifier &B :
10111 VBase ? ClassDecl->vbases() : ClassDecl->bases()) {
10112 // Don't visit direct vbases twice.
10113 if (B.isVirtual() != VBase)
Richard Smithb7151b92013-04-10 06:11:48 +000010114 continue;
Richard Smithb7151b92013-04-10 06:11:48 +000010115
Richard Smith5179eb72016-06-28 19:03:57 +000010116 CXXRecordDecl *BaseClass = B.getType()->getAsCXXRecordDecl();
10117 if (!BaseClass)
Richard Smithb7151b92013-04-10 06:11:48 +000010118 continue;
Richard Smith5179eb72016-06-28 19:03:57 +000010119
10120 CXXConstructorDecl *Constructor =
10121 ICI.findConstructorForBase(BaseClass, Inherited.getConstructor())
10122 .first;
10123 if (!Constructor)
10124 Constructor = LookupDefaultConstructor(BaseClass);
Richard Smithb7151b92013-04-10 06:11:48 +000010125 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000010126 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +000010127 }
10128 }
10129
10130 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010131 for (const auto *F : ClassDecl->fields()) {
Richard Smithb7151b92013-04-10 06:11:48 +000010132 if (F->hasInClassInitializer()) {
10133 if (Expr *E = F->getInClassInitializer())
10134 ExceptSpec.CalledExpr(E);
Richard Smithb7151b92013-04-10 06:11:48 +000010135 } else if (const RecordType *RecordTy
10136 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
10137 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
10138 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
10139 if (Constructor)
10140 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
10141 }
10142 }
10143
Richard Smithc2bc61b2013-03-18 21:12:30 +000010144 return ExceptSpec;
10145}
10146
Richard Smith8bf22e52012-11-29 01:34:07 +000010147namespace {
10148/// RAII object to register a special member as being currently declared.
10149struct DeclaringSpecialMember {
10150 Sema &S;
10151 Sema::SpecialMemberDecl D;
Richard Smith12e79312016-05-13 06:47:56 +000010152 Sema::ContextRAII SavedContext;
Richard Smith8bf22e52012-11-29 01:34:07 +000010153 bool WasAlreadyBeingDeclared;
10154
10155 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
Richard Smith12e79312016-05-13 06:47:56 +000010156 : S(S), D(RD, CSM), SavedContext(S, RD) {
David Blaikie82e95a32014-11-19 07:49:47 +000010157 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
Richard Smith8bf22e52012-11-29 01:34:07 +000010158 if (WasAlreadyBeingDeclared)
10159 // This almost never happens, but if it does, ensure that our cache
10160 // doesn't contain a stale result.
10161 S.SpecialMemberCache.clear();
10162
10163 // FIXME: Register a note to be produced if we encounter an error while
10164 // declaring the special member.
10165 }
10166 ~DeclaringSpecialMember() {
10167 if (!WasAlreadyBeingDeclared)
10168 S.SpecialMembersBeingDeclared.erase(D);
10169 }
10170
10171 /// \brief Are we already trying to declare this special member?
10172 bool isAlreadyBeingDeclared() const {
10173 return WasAlreadyBeingDeclared;
10174 }
10175};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010176}
Richard Smith8bf22e52012-11-29 01:34:07 +000010177
Richard Smith12e79312016-05-13 06:47:56 +000010178void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10179 // Look up any existing declarations, but don't trigger declaration of all
10180 // implicit special members with this name.
10181 DeclarationName Name = FD->getDeclName();
10182 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10183 ForRedeclaration);
10184 for (auto *D : FD->getParent()->lookup(Name))
10185 if (auto *Acceptable = R.getAcceptableDecl(D))
10186 R.addDecl(Acceptable);
10187 R.resolveKind();
Richard Smitha87b7662016-05-13 18:48:05 +000010188 R.suppressDiagnostics();
Richard Smith12e79312016-05-13 06:47:56 +000010189
Richard Smithf445f192017-02-09 21:04:43 +000010190 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
Richard Smith12e79312016-05-13 06:47:56 +000010191}
10192
Alexis Hunt6d5b96c2011-05-10 00:49:42 +000010193CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
10194 CXXRecordDecl *ClassDecl) {
10195 // C++ [class.ctor]p5:
10196 // A default constructor for a class X is a constructor of class X
10197 // that can be called without an argument. If there is no
10198 // user-declared constructor for class X, a default constructor is
10199 // implicitly declared. An implicitly-declared default constructor
10200 // is an inline public member of its class.
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010201 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +000010202 "Should not build implicit default constructor!");
10203
Richard Smith8bf22e52012-11-29 01:34:07 +000010204 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
10205 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010206 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010207
Richard Smithb5800092012-06-10 05:43:50 +000010208 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10209 CXXDefaultConstructor,
10210 false);
10211
Douglas Gregor6d880b12010-07-01 22:31:05 +000010212 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +000010213 CanQualType ClassType
10214 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010215 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +000010216 DeclarationName Name
10217 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +000010218 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +000010219 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000010220 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
10221 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
10222 /*isImplicitlyDeclared=*/true, Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +000010223 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +000010224 DefaultCon->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010225
10226 if (getLangOpts().CUDA) {
10227 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
10228 DefaultCon,
10229 /* ConstRHS */ false,
10230 /* Diagnose */ false);
10231 }
Richard Smithd3b5c9082012-07-27 04:22:15 +000010232
10233 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +000010234 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000010235 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010236
Richard Smith6b02d462012-12-08 08:32:28 +000010237 // We don't need to use SpecialMemberIsTrivial here; triviality for default
10238 // constructors is easy to compute.
10239 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
10240
Douglas Gregor9672f922010-07-03 00:47:00 +000010241 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +000010242 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +000010243
Richard Smith12e79312016-05-13 06:47:56 +000010244 Scope *S = getScopeForContext(ClassDecl);
10245 CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
10246
10247 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
10248 SetDeclDeleted(DefaultCon, ClassLoc);
10249
10250 if (S)
Douglas Gregor9672f922010-07-03 00:47:00 +000010251 PushOnScopeChains(DefaultCon, S, false);
10252 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +000010253
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +000010254 return DefaultCon;
10255}
10256
Fariborz Jahanian423a81f2009-06-19 19:55:27 +000010257void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
10258 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +000010259 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +000010260 !Constructor->doesThisDeclarationHaveABody() &&
10261 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +000010262 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010263
Anders Carlsson423f5d82010-04-23 16:04:08 +000010264 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +000010265 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +000010266
Eli Friedmaneaf34142012-10-18 20:14:08 +000010267 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010268 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +000010269 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010270 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +000010271 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +000010272 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +000010273 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +000010274 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +000010275 }
Douglas Gregor73193272010-09-20 16:48:21 +000010276
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010277 // The exception specification is needed because we are defining the
10278 // function.
10279 ResolveExceptionSpec(CurrentLocation,
10280 Constructor->getType()->castAs<FunctionProtoType>());
10281
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010282 SourceLocation Loc = Constructor->getLocEnd().isValid()
10283 ? Constructor->getLocEnd()
10284 : Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +000010285 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +000010286
Eli Friedman276dd182013-09-05 00:02:25 +000010287 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +000010288 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +000010289
10290 if (ASTMutationListener *L = getASTMutationListener()) {
10291 L->CompletedImplicitDefinition(Constructor);
10292 }
Richard Trieuef64e942013-10-25 00:56:00 +000010293
10294 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +000010295}
10296
Richard Smith938f40b2011-06-11 17:19:42 +000010297void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +000010298 // Perform any delayed checks on exception specifications.
10299 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +000010300}
10301
Richard Smith5179eb72016-06-28 19:03:57 +000010302/// Find or create the fake constructor we synthesize to model constructing an
10303/// object of a derived class via a constructor of a base class.
10304CXXConstructorDecl *
10305Sema::findInheritingConstructor(SourceLocation Loc,
10306 CXXConstructorDecl *BaseCtor,
10307 ConstructorUsingShadowDecl *Shadow) {
10308 CXXRecordDecl *Derived = Shadow->getParent();
10309 SourceLocation UsingLoc = Shadow->getLocation();
Richard Smith185be182013-04-10 05:48:59 +000010310
Richard Smith5179eb72016-06-28 19:03:57 +000010311 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
10312 // For now we use the name of the base class constructor as a member of the
10313 // derived class to indicate a (fake) inherited constructor name.
10314 DeclarationName Name = BaseCtor->getDeclName();
Richard Smith185be182013-04-10 05:48:59 +000010315
Richard Smith5179eb72016-06-28 19:03:57 +000010316 // Check to see if we already have a fake constructor for this inherited
10317 // constructor call.
10318 for (NamedDecl *Ctor : Derived->lookup(Name))
10319 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
10320 ->getInheritedConstructor()
10321 .getConstructor(),
10322 BaseCtor))
10323 return cast<CXXConstructorDecl>(Ctor);
Richard Smith185be182013-04-10 05:48:59 +000010324
Richard Smith5179eb72016-06-28 19:03:57 +000010325 DeclarationNameInfo NameInfo(Name, UsingLoc);
10326 TypeSourceInfo *TInfo =
10327 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
10328 FunctionProtoTypeLoc ProtoLoc =
10329 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
Richard Smith185be182013-04-10 05:48:59 +000010330
Richard Smith5179eb72016-06-28 19:03:57 +000010331 // Check the inherited constructor is valid and find the list of base classes
10332 // from which it was inherited.
10333 InheritedConstructorInfo ICI(*this, Loc, Shadow);
Richard Smith185be182013-04-10 05:48:59 +000010334
Richard Smith5179eb72016-06-28 19:03:57 +000010335 bool Constexpr =
10336 BaseCtor->isConstexpr() &&
10337 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
10338 false, BaseCtor, &ICI);
Richard Smith185be182013-04-10 05:48:59 +000010339
Richard Smith5179eb72016-06-28 19:03:57 +000010340 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
10341 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
10342 BaseCtor->isExplicit(), /*Inline=*/true,
10343 /*ImplicitlyDeclared=*/true, Constexpr,
10344 InheritedConstructor(Shadow, BaseCtor));
10345 if (Shadow->isInvalidDecl())
10346 DerivedCtor->setInvalidDecl();
Richard Smith185be182013-04-10 05:48:59 +000010347
Richard Smith5179eb72016-06-28 19:03:57 +000010348 // Build an unevaluated exception specification for this fake constructor.
10349 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
10350 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10351 EPI.ExceptionSpec.Type = EST_Unevaluated;
10352 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
10353 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
10354 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +000010355
Richard Smith5179eb72016-06-28 19:03:57 +000010356 // Build the parameter declarations.
10357 SmallVector<ParmVarDecl *, 16> ParamDecls;
10358 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +000010359 TypeSourceInfo *TInfo =
Richard Smith5179eb72016-06-28 19:03:57 +000010360 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
10361 ParmVarDecl *PD = ParmVarDecl::Create(
10362 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
10363 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
10364 PD->setScopeInfo(0, I);
10365 PD->setImplicit();
10366 // Ensure attributes are propagated onto parameters (this matters for
10367 // format, pass_object_size, ...).
10368 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
10369 ParamDecls.push_back(PD);
10370 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +000010371 }
10372
Richard Smith5179eb72016-06-28 19:03:57 +000010373 // Set up the new constructor.
10374 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
10375 DerivedCtor->setAccess(BaseCtor->getAccess());
10376 DerivedCtor->setParams(ParamDecls);
10377 Derived->addDecl(DerivedCtor);
Richard Smith80a47022016-06-29 01:10:27 +000010378
10379 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
10380 SetDeclDeleted(DerivedCtor, UsingLoc);
10381
Richard Smith5179eb72016-06-28 19:03:57 +000010382 return DerivedCtor;
Sebastian Redl08905022011-02-05 19:23:19 +000010383}
10384
Richard Smith80a47022016-06-29 01:10:27 +000010385void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
10386 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
10387 Ctor->getInheritedConstructor().getShadowDecl());
10388 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
10389 /*Diagnose*/true);
10390}
10391
Richard Smithc2bc61b2013-03-18 21:12:30 +000010392void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
10393 CXXConstructorDecl *Constructor) {
10394 CXXRecordDecl *ClassDecl = Constructor->getParent();
10395 assert(Constructor->getInheritedConstructor() &&
10396 !Constructor->doesThisDeclarationHaveABody() &&
10397 !Constructor->isDeleted());
Richard Smith5179eb72016-06-28 19:03:57 +000010398 if (Constructor->isInvalidDecl())
10399 return;
Richard Smithc2bc61b2013-03-18 21:12:30 +000010400
Richard Smith5179eb72016-06-28 19:03:57 +000010401 ConstructorUsingShadowDecl *Shadow =
10402 Constructor->getInheritedConstructor().getShadowDecl();
10403 CXXConstructorDecl *InheritedCtor =
10404 Constructor->getInheritedConstructor().getConstructor();
10405
10406 // [class.inhctor.init]p1:
10407 // initialization proceeds as if a defaulted default constructor is used to
10408 // initialize the D object and each base class subobject from which the
10409 // constructor was inherited
10410
10411 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
10412 CXXRecordDecl *RD = Shadow->getParent();
10413 SourceLocation InitLoc = Shadow->getLocation();
10414
10415 // Initializations are performed "as if by a defaulted default constructor",
10416 // so enter the appropriate scope.
Richard Smithc2bc61b2013-03-18 21:12:30 +000010417 SynthesizedFunctionScope Scope(*this, Constructor);
10418 DiagnosticErrorTrap Trap(Diags);
Richard Smith5179eb72016-06-28 19:03:57 +000010419
10420 // Build explicit initializers for all base classes from which the
10421 // constructor was inherited.
10422 SmallVector<CXXCtorInitializer*, 8> Inits;
10423 for (bool VBase : {false, true}) {
10424 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
10425 if (B.isVirtual() != VBase)
10426 continue;
10427
10428 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
10429 if (!BaseRD)
10430 continue;
10431
10432 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
10433 if (!BaseCtor.first)
10434 continue;
10435
10436 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
10437 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
10438 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
10439
10440 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
10441 Inits.push_back(new (Context) CXXCtorInitializer(
10442 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
10443 SourceLocation()));
10444 }
10445 }
10446
10447 // We now proceed as if for a defaulted default constructor, with the relevant
10448 // initializers replaced.
10449
10450 bool HadError = SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits);
10451 if (HadError || Trap.hasErrorOccurred()) {
10452 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) << RD;
Richard Smithc2bc61b2013-03-18 21:12:30 +000010453 Constructor->setInvalidDecl();
10454 return;
10455 }
10456
Richard Smith5179eb72016-06-28 19:03:57 +000010457 // The exception specification is needed because we are defining the
10458 // function.
10459 ResolveExceptionSpec(CurrentLocation,
10460 Constructor->getType()->castAs<FunctionProtoType>());
10461
10462 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
Richard Smithc2bc61b2013-03-18 21:12:30 +000010463
Eli Friedman276dd182013-09-05 00:02:25 +000010464 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +000010465 MarkVTableUsed(CurrentLocation, ClassDecl);
10466
10467 if (ASTMutationListener *L = getASTMutationListener()) {
10468 L->CompletedImplicitDefinition(Constructor);
10469 }
Richard Smithc2bc61b2013-03-18 21:12:30 +000010470
Richard Smith5179eb72016-06-28 19:03:57 +000010471 DiagnoseUninitializedFields(*this, Constructor);
10472}
Richard Smithc2bc61b2013-03-18 21:12:30 +000010473
Alexis Huntf91729462011-05-12 22:46:25 +000010474Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010475Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
10476 CXXRecordDecl *ClassDecl = MD->getParent();
10477
Douglas Gregorf1203042010-07-01 19:09:28 +000010478 // C++ [except.spec]p14:
10479 // An implicitly declared special member function (Clause 12) shall have
10480 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +000010481 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +000010482 if (ClassDecl->isInvalidDecl())
10483 return ExceptSpec;
10484
Douglas Gregorf1203042010-07-01 19:09:28 +000010485 // Direct base-class destructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000010486 for (const auto &B : ClassDecl->bases()) {
10487 if (B.isVirtual()) // Handled below.
Douglas Gregorf1203042010-07-01 19:09:28 +000010488 continue;
10489
Aaron Ballman574705e2014-03-13 15:41:46 +000010490 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
10491 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +000010492 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +000010493 }
Sebastian Redl623ea822011-05-19 05:13:44 +000010494
Douglas Gregorf1203042010-07-01 19:09:28 +000010495 // Virtual base-class destructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000010496 for (const auto &B : ClassDecl->vbases()) {
10497 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
10498 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +000010499 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +000010500 }
Sebastian Redl623ea822011-05-19 05:13:44 +000010501
Douglas Gregorf1203042010-07-01 19:09:28 +000010502 // Field destructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010503 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorf1203042010-07-01 19:09:28 +000010504 if (const RecordType *RecordTy
10505 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +000010506 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +000010507 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +000010508 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010509
Alexis Huntf91729462011-05-12 22:46:25 +000010510 return ExceptSpec;
10511}
10512
10513CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
10514 // C++ [class.dtor]p2:
10515 // If a class has no user-declared destructor, a destructor is
10516 // declared implicitly. An implicitly-declared destructor is an
10517 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +000010518 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +000010519
Richard Smith8bf22e52012-11-29 01:34:07 +000010520 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
10521 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010522 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010523
Douglas Gregor7454c562010-07-02 20:37:36 +000010524 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +000010525 CanQualType ClassType
10526 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010527 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +000010528 DeclarationName Name
10529 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +000010530 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +000010531 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +000010532 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +000010533 QualType(), nullptr, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010534 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +000010535 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +000010536 Destructor->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010537
10538 if (getLangOpts().CUDA) {
10539 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
10540 Destructor,
10541 /* ConstRHS */ false,
10542 /* Diagnose */ false);
10543 }
Richard Smithd3b5c9082012-07-27 04:22:15 +000010544
10545 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +000010546 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000010547 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010548
Richard Smith6b02d462012-12-08 08:32:28 +000010549 // We don't need to use SpecialMemberIsTrivial here; triviality for
10550 // destructors is easy to compute.
10551 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
10552
Douglas Gregor7454c562010-07-02 20:37:36 +000010553 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +000010554 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +000010555
Richard Smith12e79312016-05-13 06:47:56 +000010556 Scope *S = getScopeForContext(ClassDecl);
10557 CheckImplicitSpecialMemberDeclaration(S, Destructor);
10558
Richard Smithb2f0f052016-10-10 18:54:32 +000010559 // We can't check whether an implicit destructor is deleted before we complete
10560 // the definition of the class, because its validity depends on the alignment
10561 // of the class. We'll check this from ActOnFields once the class is complete.
10562 if (ClassDecl->isCompleteDefinition() &&
10563 ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith12e79312016-05-13 06:47:56 +000010564 SetDeclDeleted(Destructor, ClassLoc);
10565
Douglas Gregor7454c562010-07-02 20:37:36 +000010566 // Introduce this destructor into its scope.
Richard Smith12e79312016-05-13 06:47:56 +000010567 if (S)
Douglas Gregor7454c562010-07-02 20:37:36 +000010568 PushOnScopeChains(Destructor, S, false);
10569 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +000010570
Douglas Gregorf1203042010-07-01 19:09:28 +000010571 return Destructor;
10572}
10573
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010574void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +000010575 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +000010576 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010577 !Destructor->doesThisDeclarationHaveABody() &&
10578 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010579 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +000010580 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010581 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010582
Douglas Gregor54818f02010-05-12 16:39:35 +000010583 if (Destructor->isInvalidDecl())
10584 return;
10585
Eli Friedmaneaf34142012-10-18 20:14:08 +000010586 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010587
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010588 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +000010589 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10590 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +000010591
Douglas Gregor54818f02010-05-12 16:39:35 +000010592 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +000010593 Diag(CurrentLocation, diag::note_member_synthesized_at)
10594 << CXXDestructor << Context.getTagDeclType(ClassDecl);
10595
10596 Destructor->setInvalidDecl();
10597 return;
10598 }
10599
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010600 // The exception specification is needed because we are defining the
10601 // function.
10602 ResolveExceptionSpec(CurrentLocation,
10603 Destructor->getType()->castAs<FunctionProtoType>());
10604
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010605 SourceLocation Loc = Destructor->getLocEnd().isValid()
10606 ? Destructor->getLocEnd()
10607 : Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +000010608 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +000010609 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010610 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +000010611
10612 if (ASTMutationListener *L = getASTMutationListener()) {
10613 L->CompletedImplicitDefinition(Destructor);
10614 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010615}
10616
Richard Smith84973e52012-04-21 18:42:51 +000010617/// \brief Perform any semantic analysis which needs to be delayed until all
10618/// pending class member declarations have been parsed.
10619void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +000010620 // If the context is an invalid C++ class, just suppress these checks.
10621 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
10622 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +000010623 DelayedDefaultedMemberExceptionSpecs.clear();
Richard Smith88f45492014-11-22 03:09:05 +000010624 DelayedExceptionSpecChecks.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +000010625 return;
10626 }
Reid Kleckner61195e12017-01-05 01:08:22 +000010627 checkForMultipleExportedDefaultConstructors(*this, Record);
Reid Klecknerbba3cb92015-03-17 19:00:50 +000010628 }
10629}
10630
Hans Wennborg99000c22015-08-15 01:18:16 +000010631void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
Reid Kleckner5b640342016-02-26 19:51:02 +000010632 referenceDLLExportedClassMethods();
10633}
10634
10635void Sema::referenceDLLExportedClassMethods() {
Hans Wennborg99000c22015-08-15 01:18:16 +000010636 if (!DelayedDllExportClasses.empty()) {
10637 // Calling ReferenceDllExportedMethods might cause the current function to
10638 // be called again, so use a local copy of DelayedDllExportClasses.
10639 SmallVector<CXXRecordDecl *, 4> WorkList;
10640 std::swap(DelayedDllExportClasses, WorkList);
10641 for (CXXRecordDecl *Class : WorkList)
10642 ReferenceDllExportedMethods(*this, Class);
10643 }
Reid Klecknerbba3cb92015-03-17 19:00:50 +000010644}
10645
Richard Smithd3b5c9082012-07-27 04:22:15 +000010646void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
10647 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010648 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +000010649 "adjusting dtor exception specs was introduced in c++11");
10650
Sebastian Redl623ea822011-05-19 05:13:44 +000010651 // C++11 [class.dtor]p3:
10652 // A declaration of a destructor that does not have an exception-
10653 // specification is implicitly considered to have the same exception-
10654 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +000010655 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +000010656 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010657 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +000010658 return;
10659
Chandler Carruth9a797572011-09-20 04:55:26 +000010660 // Replace the destructor's type, building off the existing one. Fortunately,
10661 // the only thing of interest in the destructor type is its extended info.
10662 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +000010663 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +000010664 EPI.ExceptionSpec.Type = EST_Unevaluated;
10665 EPI.ExceptionSpec.SourceDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000010666 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +000010667
Sebastian Redl623ea822011-05-19 05:13:44 +000010668 // FIXME: If the destructor has a body that could throw, and the newly created
10669 // spec doesn't allow exceptions, we should emit a warning, because this
10670 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +000010671 // However, we don't have a body or an exception specification yet, so it
10672 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +000010673}
10674
Pavel Labath58934982013-08-30 08:52:28 +000010675namespace {
10676/// \brief An abstract base class for all helper classes used in building the
10677// copy/move operators. These classes serve as factory functions and help us
10678// avoid using the same Expr* in the AST twice.
10679class ExprBuilder {
Aaron Ballmanabc18922015-02-15 22:54:08 +000010680 ExprBuilder(const ExprBuilder&) = delete;
10681 ExprBuilder &operator=(const ExprBuilder&) = delete;
Pavel Labath58934982013-08-30 08:52:28 +000010682
10683protected:
10684 static Expr *assertNotNull(Expr *E) {
10685 assert(E && "Expression construction must not fail.");
10686 return E;
10687 }
10688
10689public:
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000010690 ExprBuilder() {}
10691 virtual ~ExprBuilder() {}
Pavel Labath58934982013-08-30 08:52:28 +000010692
10693 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
10694};
10695
10696class RefBuilder: public ExprBuilder {
10697 VarDecl *Var;
10698 QualType VarType;
10699
10700public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010701 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010702 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +000010703 }
10704
10705 RefBuilder(VarDecl *Var, QualType VarType)
10706 : Var(Var), VarType(VarType) {}
10707};
10708
10709class ThisBuilder: public ExprBuilder {
10710public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010711 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010712 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
Pavel Labath58934982013-08-30 08:52:28 +000010713 }
10714};
10715
10716class CastBuilder: public ExprBuilder {
10717 const ExprBuilder &Builder;
10718 QualType Type;
10719 ExprValueKind Kind;
10720 const CXXCastPath &Path;
10721
10722public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010723 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010724 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
10725 CK_UncheckedDerivedToBase, Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010726 &Path).get());
Pavel Labath58934982013-08-30 08:52:28 +000010727 }
10728
10729 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
10730 const CXXCastPath &Path)
10731 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
10732};
10733
10734class DerefBuilder: public ExprBuilder {
10735 const ExprBuilder &Builder;
10736
10737public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010738 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010739 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010740 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +000010741 }
10742
10743 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10744};
10745
10746class MemberBuilder: public ExprBuilder {
10747 const ExprBuilder &Builder;
10748 QualType Type;
10749 CXXScopeSpec SS;
10750 bool IsArrow;
10751 LookupResult &MemberLookup;
10752
10753public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010754 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010755 return assertNotNull(S.BuildMemberReferenceExpr(
Craig Topperc3ec1492014-05-26 06:22:03 +000010756 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
Aaron Ballman6924dcd2015-09-01 14:49:24 +000010757 nullptr, MemberLookup, nullptr, nullptr).get());
Pavel Labath58934982013-08-30 08:52:28 +000010758 }
10759
10760 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
10761 LookupResult &MemberLookup)
10762 : Builder(Builder), Type(Type), IsArrow(IsArrow),
10763 MemberLookup(MemberLookup) {}
10764};
10765
10766class MoveCastBuilder: public ExprBuilder {
10767 const ExprBuilder &Builder;
10768
10769public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010770 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010771 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
10772 }
10773
10774 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10775};
10776
10777class LvalueConvBuilder: public ExprBuilder {
10778 const ExprBuilder &Builder;
10779
10780public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010781 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010782 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010783 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +000010784 }
10785
10786 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10787};
10788
10789class SubscriptBuilder: public ExprBuilder {
10790 const ExprBuilder &Base;
10791 const ExprBuilder &Index;
10792
10793public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010794 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010795 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010796 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +000010797 }
10798
10799 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
10800 : Base(Base), Index(Index) {}
10801};
10802
10803} // end anonymous namespace
10804
Richard Smith41ae3282012-11-14 00:50:40 +000010805/// When generating a defaulted copy or move assignment operator, if a field
10806/// should be copied with __builtin_memcpy rather than via explicit assignments,
10807/// do so. This optimization only applies for arrays of scalars, and for arrays
10808/// of class type where the selected copy/move-assignment operator is trivial.
10809static StmtResult
10810buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +000010811 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +000010812 // Compute the size of the memory buffer to be copied.
10813 QualType SizeType = S.Context.getSizeType();
10814 llvm::APInt Size(S.Context.getTypeSize(SizeType),
10815 S.Context.getTypeSizeInChars(T).getQuantity());
10816
10817 // Take the address of the field references for "from" and "to". We
10818 // directly construct UnaryOperators here because semantic analysis
10819 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +000010820 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000010821 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
10822 S.Context.getPointerType(From->getType()),
10823 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +000010824 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000010825 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
10826 S.Context.getPointerType(To->getType()),
10827 VK_RValue, OK_Ordinary, Loc);
10828
10829 const Type *E = T->getBaseElementTypeUnsafe();
10830 bool NeedsCollectableMemCpy =
10831 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
10832
10833 // Create a reference to the __builtin_objc_memmove_collectable function
10834 StringRef MemCpyName = NeedsCollectableMemCpy ?
10835 "__builtin_objc_memmove_collectable" :
10836 "__builtin_memcpy";
10837 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
10838 Sema::LookupOrdinaryName);
10839 S.LookupName(R, S.TUScope, true);
10840
10841 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
10842 if (!MemCpy)
10843 // Something went horribly wrong earlier, and we will have complained
10844 // about it.
10845 return StmtError();
10846
10847 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
Craig Topperc3ec1492014-05-26 06:22:03 +000010848 VK_RValue, Loc, nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +000010849 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
10850
10851 Expr *CallArgs[] = {
10852 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
10853 };
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010854 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
Richard Smith41ae3282012-11-14 00:50:40 +000010855 Loc, CallArgs, Loc);
10856
10857 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010858 return Call.getAs<Stmt>();
Richard Smith41ae3282012-11-14 00:50:40 +000010859}
10860
Sebastian Redl22653ba2011-08-30 19:58:05 +000010861/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +000010862/// \c To.
10863///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010864/// This routine is used to copy/move the members of a class with an
10865/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +000010866/// copied are arrays, this routine builds for loops to copy them.
10867///
10868/// \param S The Sema object used for type-checking.
10869///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010870/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +000010871///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010872/// \param T The type of the expressions being copied/moved. Both expressions
10873/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +000010874///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010875/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +000010876///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010877/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +000010878///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010879/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +000010880/// Otherwise, it's a non-static member subobject.
10881///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010882/// \param Copying Whether we're copying or moving.
10883///
Douglas Gregorb139cd52010-05-01 20:49:11 +000010884/// \param Depth Internal parameter recording the depth of the recursion.
10885///
Richard Smith41ae3282012-11-14 00:50:40 +000010886/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
10887/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +000010888static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +000010889buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +000010890 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +000010891 bool CopyingBaseSubobject, bool Copying,
10892 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +000010893 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +000010894 // Each subobject is assigned in the manner appropriate to its type:
10895 //
Sebastian Redl22653ba2011-08-30 19:58:05 +000010896 // - if the subobject is of class type, as if by a call to operator= with
10897 // the subobject as the object expression and the corresponding
10898 // subobject of x as a single function argument (as if by explicit
10899 // qualification; that is, ignoring any possible virtual overriding
10900 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +000010901 //
10902 // C++03 [class.copy]p13:
10903 // - if the subobject is of class type, the copy assignment operator for
10904 // the class is used (as if by explicit qualification; that is,
10905 // ignoring any possible virtual overriding functions in more derived
10906 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010907 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
10908 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +000010909
Douglas Gregorb139cd52010-05-01 20:49:11 +000010910 // Look for operator=.
10911 DeclarationName Name
10912 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10913 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
10914 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010915
Richard Smith52c0b582012-11-13 00:54:12 +000010916 // Prior to C++11, filter out any result that isn't a copy/move-assignment
10917 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010918 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +000010919 LookupResult::Filter F = OpLookup.makeFilter();
10920 while (F.hasNext()) {
10921 NamedDecl *D = F.next();
10922 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
10923 if (Method->isCopyAssignmentOperator() ||
10924 (!Copying && Method->isMoveAssignmentOperator()))
10925 continue;
10926
10927 F.erase();
10928 }
10929 F.done();
John McCallab8c2732010-03-16 06:11:48 +000010930 }
Richard Smith52c0b582012-11-13 00:54:12 +000010931
Douglas Gregor40c92bb2010-05-04 15:20:55 +000010932 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +000010933 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +000010934 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +000010935 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +000010936 // ambiguities), we need to cast "this" to that subobject type; to
10937 // ensure that we don't go through the virtual call mechanism, we need
10938 // to qualify the operator= name with the base class (see below). However,
10939 // this means that if the base class has a protected copy assignment
10940 // operator, the protected member access check will fail. So, we
10941 // rewrite "protected" access to "public" access in this case, since we
10942 // know by construction that we're calling from a derived class.
10943 if (CopyingBaseSubobject) {
10944 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
10945 L != LEnd; ++L) {
10946 if (L.getAccess() == AS_protected)
10947 L.setAccess(AS_public);
10948 }
10949 }
Richard Smith52c0b582012-11-13 00:54:12 +000010950
Douglas Gregorb139cd52010-05-01 20:49:11 +000010951 // Create the nested-name-specifier that will be used to qualify the
10952 // reference to operator=; this is required to suppress the virtual
10953 // call mechanism.
10954 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +000010955 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +000010956 SS.MakeTrivial(S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +000010957 NestedNameSpecifier::Create(S.Context, nullptr, false,
Manuel Klimeke7167412012-02-06 21:51:39 +000010958 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +000010959 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +000010960
Douglas Gregorb139cd52010-05-01 20:49:11 +000010961 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +000010962 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +000010963 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
10964 SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000010965 /*FirstQualifierInScope=*/nullptr,
Abramo Bagnara7945c982012-01-27 09:46:47 +000010966 OpLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000010967 /*TemplateArgs=*/nullptr, /*S*/nullptr,
Douglas Gregorb139cd52010-05-01 20:49:11 +000010968 /*SuppressQualifierCheck=*/true);
10969 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010970 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +000010971
Douglas Gregorb139cd52010-05-01 20:49:11 +000010972 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +000010973
Pavel Labath58934982013-08-30 08:52:28 +000010974 Expr *FromInst = From.build(S, Loc);
Craig Topperc3ec1492014-05-26 06:22:03 +000010975 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010976 OpEqualRef.getAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +000010977 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010978 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010979 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +000010980
Richard Smith41ae3282012-11-14 00:50:40 +000010981 // If we built a call to a trivial 'operator=' while copying an array,
10982 // bail out. We'll replace the whole shebang with a memcpy.
10983 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
10984 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
Craig Topperc3ec1492014-05-26 06:22:03 +000010985 return StmtResult((Stmt*)nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +000010986
Richard Smith52c0b582012-11-13 00:54:12 +000010987 // Convert to an expression-statement, and clean up any produced
10988 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +000010989 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010990 }
John McCallab8c2732010-03-16 06:11:48 +000010991
Richard Smith52c0b582012-11-13 00:54:12 +000010992 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +000010993 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +000010994 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010995 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +000010996 ExprResult Assignment = S.CreateBuiltinBinOp(
10997 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000010998 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010999 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +000011000 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +000011001 }
Richard Smith52c0b582012-11-13 00:54:12 +000011002
11003 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +000011004 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +000011005
Douglas Gregorb139cd52010-05-01 20:49:11 +000011006 // Construct a loop over the array bounds, e.g.,
11007 //
11008 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11009 //
11010 // that will copy each of the array elements.
11011 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +000011012
Douglas Gregorb139cd52010-05-01 20:49:11 +000011013 // Create the iteration variable.
Craig Topperc3ec1492014-05-26 06:22:03 +000011014 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011015 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000011016 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011017 llvm::raw_svector_ostream OS(Str);
11018 OS << "__i" << Depth;
11019 IterationVarName = &S.Context.Idents.get(OS.str());
11020 }
Abramo Bagnaradff19302011-03-08 08:55:46 +000011021 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +000011022 IterationVarName, SizeType,
11023 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +000011024 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +000011025
Douglas Gregorb139cd52010-05-01 20:49:11 +000011026 // Initialize the iteration variable to zero.
11027 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000011028 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000011029
Pavel Labath58934982013-08-30 08:52:28 +000011030 // Creates a reference to the iteration variable.
11031 RefBuilder IterationVarRef(IterationVar, SizeType);
11032 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +000011033
Douglas Gregorb139cd52010-05-01 20:49:11 +000011034 // Create the DeclStmt that holds the iteration variable.
11035 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000011036
Douglas Gregorb139cd52010-05-01 20:49:11 +000011037 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +000011038 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11039 MoveCastBuilder FromIndexMove(FromIndexCopy);
11040 const ExprBuilder *FromIndex;
11041 if (Copying)
11042 FromIndex = &FromIndexCopy;
11043 else
11044 FromIndex = &FromIndexMove;
11045
11046 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011047
11048 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +000011049 StmtResult Copy =
11050 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +000011051 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +000011052 Copying, Depth + 1);
11053 // Bail out if copying fails or if we determined that we should use memcpy.
11054 if (Copy.isInvalid() || !Copy.get())
11055 return Copy;
11056
11057 // Create the comparison against the array bound.
11058 llvm::APInt Upper
11059 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11060 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +000011061 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +000011062 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11063 BO_NE, S.Context.BoolTy,
11064 VK_RValue, OK_Ordinary, Loc, false);
11065
11066 // Create the pre-increment of the iteration variable.
11067 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +000011068 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
11069 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000011070
Douglas Gregorb139cd52010-05-01 20:49:11 +000011071 // Construct the loop that copies all elements of this array.
Richard Smith03a4aa32016-06-23 19:02:52 +000011072 return S.ActOnForStmt(
11073 Loc, Loc, InitStmt,
11074 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11075 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
Fariborz Jahanian41f79272009-06-25 21:45:19 +000011076}
11077
Richard Smith41ae3282012-11-14 00:50:40 +000011078static StmtResult
11079buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +000011080 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +000011081 bool CopyingBaseSubobject, bool Copying) {
11082 // Maybe we should use a memcpy?
11083 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11084 T.isTriviallyCopyableType(S.Context))
11085 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11086
11087 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11088 CopyingBaseSubobject,
11089 Copying, 0));
11090
11091 // If we ended up picking a trivial assignment operator for an array of a
11092 // non-trivially-copyable class type, just emit a memcpy.
11093 if (!Result.isInvalid() && !Result.get())
11094 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11095
11096 return Result;
11097}
11098
Richard Smithd3b5c9082012-07-27 04:22:15 +000011099Sema::ImplicitExceptionSpecification
11100Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
11101 CXXRecordDecl *ClassDecl = MD->getParent();
11102
11103 ImplicitExceptionSpecification ExceptSpec(*this);
11104 if (ClassDecl->isInvalidDecl())
11105 return ExceptSpec;
11106
11107 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000011108 assert(T->getNumParams() == 1 && "not a copy assignment op");
11109 unsigned ArgQuals =
11110 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000011111
Douglas Gregor68e11362010-07-01 17:48:08 +000011112 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +000011113 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +000011114 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +000011115
11116 // It is unspecified whether or not an implicit copy assignment operator
11117 // attempts to deduplicate calls to assignment operators of virtual bases are
11118 // made. As such, this exception specification is effectively unspecified.
11119 // Based on a similar decision made for constness in C++0x, we're erring on
11120 // the side of assuming such calls to be made regardless of whether they
11121 // actually happen.
Aaron Ballman574705e2014-03-13 15:41:46 +000011122 for (const auto &Base : ClassDecl->bases()) {
11123 if (Base.isVirtual())
Alexis Hunt491ec602011-06-21 23:42:56 +000011124 continue;
11125
Douglas Gregor330b9cf2010-07-02 21:50:04 +000011126 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000011127 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +000011128 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
11129 ArgQuals, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +000011130 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +000011131 }
Alexis Hunt491ec602011-06-21 23:42:56 +000011132
Aaron Ballman445a9392014-03-13 16:15:17 +000011133 for (const auto &Base : ClassDecl->vbases()) {
Alexis Hunt491ec602011-06-21 23:42:56 +000011134 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000011135 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +000011136 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
11137 ArgQuals, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +000011138 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +000011139 }
11140
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011141 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000011142 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +000011143 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
11144 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +000011145 LookupCopyingAssignment(FieldClassDecl,
11146 ArgQuals | FieldType.getCVRQualifiers(),
11147 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +000011148 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +000011149 }
Douglas Gregor68e11362010-07-01 17:48:08 +000011150 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000011151
Richard Smithd3b5c9082012-07-27 04:22:15 +000011152 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +000011153}
11154
11155CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11156 // Note: The following rules are largely analoguous to the copy
11157 // constructor rules. Note that virtual bases are not taken into account
11158 // for determining the argument type of the operator. Note also that
11159 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +000011160 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +000011161
Richard Smith8bf22e52012-11-29 01:34:07 +000011162 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11163 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000011164 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000011165
Alexis Hunt119f3652011-05-14 05:23:20 +000011166 QualType ArgType = Context.getTypeDeclType(ClassDecl);
11167 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +000011168 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11169 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +000011170 ArgType = ArgType.withConst();
11171 ArgType = Context.getLValueReferenceType(ArgType);
11172
Richard Smith99005e62013-05-07 03:19:20 +000011173 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11174 CXXCopyAssignment,
11175 Const);
11176
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000011177 // An implicitly-declared copy assignment operator is an inline public
11178 // member of its class.
11179 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +000011180 SourceLocation ClassLoc = ClassDecl->getLocation();
11181 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000011182 CXXMethodDecl *CopyAssignment =
11183 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000011184 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11185 /*isInline=*/true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000011186 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +000011187 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000011188 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +000011189
Eli Bendersky9a220fc2014-09-29 20:38:29 +000011190 if (getLangOpts().CUDA) {
11191 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11192 CopyAssignment,
11193 /* ConstRHS */ Const,
11194 /* Diagnose */ false);
11195 }
11196
Richard Smithd3b5c9082012-07-27 04:22:15 +000011197 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000011198 FunctionProtoType::ExtProtoInfo EPI =
11199 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000011200 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000011201
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000011202 // Add the parameter to the operator.
11203 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000011204 ClassLoc, ClassLoc,
11205 /*Id=*/nullptr, ArgType,
11206 /*TInfo=*/nullptr, SC_None,
11207 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000011208 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +000011209
Richard Smith6b02d462012-12-08 08:32:28 +000011210 CopyAssignment->setTrivial(
11211 ClassDecl->needsOverloadResolutionForCopyAssignment()
11212 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11213 : ClassDecl->hasTrivialCopyAssignment());
11214
Richard Smith6b02d462012-12-08 08:32:28 +000011215 // Note that we have added this copy-assignment operator.
11216 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
11217
Richard Smith12e79312016-05-13 06:47:56 +000011218 Scope *S = getScopeForContext(ClassDecl);
11219 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11220
11221 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11222 SetDeclDeleted(CopyAssignment, ClassLoc);
11223
11224 if (S)
Richard Smith6b02d462012-12-08 08:32:28 +000011225 PushOnScopeChains(CopyAssignment, S, false);
11226 ClassDecl->addDecl(CopyAssignment);
11227
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000011228 return CopyAssignment;
11229}
11230
Richard Smithd577fbb2013-06-13 03:23:42 +000011231/// Diagnose an implicit copy operation for a class which is odr-used, but
11232/// which is deprecated because the class has a user-declared copy constructor,
11233/// copy assignment operator, or destructor.
11234static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
11235 SourceLocation UseLoc) {
11236 assert(CopyOp->isImplicit());
11237
11238 CXXRecordDecl *RD = CopyOp->getParent();
Craig Topperc3ec1492014-05-26 06:22:03 +000011239 CXXMethodDecl *UserDeclaredOperation = nullptr;
Richard Smithd577fbb2013-06-13 03:23:42 +000011240
11241 // In Microsoft mode, assignment operations don't affect constructors and
11242 // vice versa.
11243 if (RD->hasUserDeclaredDestructor()) {
11244 UserDeclaredOperation = RD->getDestructor();
11245 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11246 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000011247 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011248 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +000011249 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011250 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +000011251 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +000011252 break;
11253 }
11254 }
11255 assert(UserDeclaredOperation);
11256 } else if (isa<CXXConstructorDecl>(CopyOp) &&
11257 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000011258 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011259 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +000011260 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011261 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000011262 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +000011263 break;
11264 }
11265 }
11266 assert(UserDeclaredOperation);
11267 }
11268
11269 if (UserDeclaredOperation) {
11270 S.Diag(UserDeclaredOperation->getLocation(),
11271 diag::warn_deprecated_copy_operation)
11272 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11273 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11274 S.Diag(UseLoc, diag::note_member_synthesized_at)
11275 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
11276 : Sema::CXXCopyAssignment)
11277 << RD;
11278 }
11279}
11280
Douglas Gregorb139cd52010-05-01 20:49:11 +000011281void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11282 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +000011283 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000011284 CopyAssignOperator->isOverloadedOperator() &&
11285 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000011286 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11287 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000011288 "DefineImplicitCopyAssignment called for wrong function");
11289
11290 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11291
11292 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
11293 CopyAssignOperator->setInvalidDecl();
11294 return;
11295 }
Richard Smithd577fbb2013-06-13 03:23:42 +000011296
11297 // C++11 [class.copy]p18:
11298 // The [definition of an implicitly declared copy assignment operator] is
11299 // deprecated if the class has a user-declared copy constructor or a
11300 // user-declared destructor.
11301 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11302 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
11303
Eli Friedman276dd182013-09-05 00:02:25 +000011304 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011305
Eli Friedmaneaf34142012-10-18 20:14:08 +000011306 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000011307 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011308
11309 // C++0x [class.copy]p30:
11310 // The implicitly-defined or explicitly-defaulted copy assignment operator
11311 // for a non-union class X performs memberwise copy assignment of its
11312 // subobjects. The direct base classes of X are assigned first, in the
11313 // order of their declaration in the base-specifier-list, and then the
11314 // immediate non-static data members of X are assigned, in the order in
11315 // which they were declared in the class definition.
11316
11317 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000011318 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011319
11320 // The parameter for the "other" object, which we are copying from.
11321 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11322 Qualifiers OtherQuals = Other->getType().getQualifiers();
11323 QualType OtherRefType = Other->getType();
11324 if (const LValueReferenceType *OtherRef
11325 = OtherRefType->getAs<LValueReferenceType>()) {
11326 OtherRefType = OtherRef->getPointeeType();
11327 OtherQuals = OtherRefType.getQualifiers();
11328 }
11329
11330 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011331 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
11332 ? CopyAssignOperator->getLocEnd()
11333 : CopyAssignOperator->getLocation();
11334
Pavel Labath58934982013-08-30 08:52:28 +000011335 // Builds a DeclRefExpr for the "other" object.
11336 RefBuilder OtherRef(Other, OtherRefType);
11337
11338 // Builds the "this" pointer.
11339 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011340
11341 // Assign base classes.
11342 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000011343 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000011344 // Form the assignment:
11345 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000011346 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +000011347 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000011348 Invalid = true;
11349 continue;
11350 }
11351
John McCallcf142162010-08-07 06:22:56 +000011352 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000011353 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +000011354
Douglas Gregorb139cd52010-05-01 20:49:11 +000011355 // Construct the "from" expression, which is an implicit cast to the
11356 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000011357 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
11358 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011359
11360 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000011361 DerefBuilder DerefThis(This);
11362 CastBuilder To(DerefThis,
11363 Context.getCVRQualifiedType(
11364 BaseType, CopyAssignOperator->getTypeQualifiers()),
11365 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011366
11367 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +000011368 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000011369 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000011370 /*CopyingBaseSubobject=*/true,
11371 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011372 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000011373 Diag(CurrentLocation, diag::note_member_synthesized_at)
11374 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11375 CopyAssignOperator->setInvalidDecl();
11376 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011377 }
11378
11379 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011380 Statements.push_back(Copy.getAs<Expr>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000011381 }
11382
Douglas Gregorb139cd52010-05-01 20:49:11 +000011383 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011384 for (auto *Field : ClassDecl->fields()) {
Richard Smith419bd092015-04-29 19:26:57 +000011385 // FIXME: We should form some kind of AST representation for the implied
11386 // memcpy in a union copy operation.
11387 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
Douglas Gregor556e5862011-10-10 17:22:13 +000011388 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +000011389
11390 if (Field->isInvalidDecl()) {
11391 Invalid = true;
11392 continue;
11393 }
11394
Douglas Gregorb139cd52010-05-01 20:49:11 +000011395 // Check for members of reference type; we can't copy those.
11396 if (Field->getType()->isReferenceType()) {
11397 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11398 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11399 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000011400 Diag(CurrentLocation, diag::note_member_synthesized_at)
11401 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011402 Invalid = true;
11403 continue;
11404 }
11405
11406 // Check for members of const-qualified, non-class type.
11407 QualType BaseType = Context.getBaseElementType(Field->getType());
11408 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11409 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11410 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11411 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000011412 Diag(CurrentLocation, diag::note_member_synthesized_at)
11413 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011414 Invalid = true;
11415 continue;
11416 }
John McCall1b1a1db2011-06-17 00:18:42 +000011417
11418 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000011419 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11420 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011421
11422 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000011423 if (FieldType->isIncompleteArrayType()) {
11424 assert(ClassDecl->hasFlexibleArrayMember() &&
11425 "Incomplete array type is not valid");
11426 continue;
11427 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000011428
11429 // Build references to the field in the object we're copying from and to.
11430 CXXScopeSpec SS; // Intentionally empty
11431 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11432 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011433 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011434 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000011435
11436 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
11437
11438 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011439
Douglas Gregorb139cd52010-05-01 20:49:11 +000011440 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000011441 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000011442 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000011443 /*CopyingBaseSubobject=*/false,
11444 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011445 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000011446 Diag(CurrentLocation, diag::note_member_synthesized_at)
11447 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11448 CopyAssignOperator->setInvalidDecl();
11449 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011450 }
11451
11452 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011453 Statements.push_back(Copy.getAs<Stmt>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000011454 }
11455
11456 if (!Invalid) {
11457 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +000011458 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000011459
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000011460 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +000011461 if (Return.isInvalid())
11462 Invalid = true;
11463 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011464 Statements.push_back(Return.getAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +000011465
11466 if (Trap.hasErrorOccurred()) {
11467 Diag(CurrentLocation, diag::note_member_synthesized_at)
11468 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11469 Invalid = true;
11470 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000011471 }
11472 }
11473
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000011474 // The exception specification is needed because we are defining the
11475 // function.
11476 ResolveExceptionSpec(CurrentLocation,
11477 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11478
Douglas Gregorb139cd52010-05-01 20:49:11 +000011479 if (Invalid) {
11480 CopyAssignOperator->setInvalidDecl();
11481 return;
11482 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011483
11484 StmtResult Body;
11485 {
11486 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011487 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011488 /*isStmtExpr=*/false);
11489 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11490 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011491 CopyAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +000011492
11493 if (ASTMutationListener *L = getASTMutationListener()) {
11494 L->CompletedImplicitDefinition(CopyAssignOperator);
11495 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +000011496}
11497
Sebastian Redl22653ba2011-08-30 19:58:05 +000011498Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000011499Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
11500 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +000011501
Richard Smithd3b5c9082012-07-27 04:22:15 +000011502 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011503 if (ClassDecl->isInvalidDecl())
11504 return ExceptSpec;
11505
11506 // C++0x [except.spec]p14:
11507 // An implicitly declared special member function (Clause 12) shall have an
11508 // exception-specification. [...]
11509
11510 // It is unspecified whether or not an implicit move assignment operator
11511 // attempts to deduplicate calls to assignment operators of virtual bases are
11512 // made. As such, this exception specification is effectively unspecified.
11513 // Based on a similar decision made for constness in C++0x, we're erring on
11514 // the side of assuming such calls to be made regardless of whether they
11515 // actually happen.
11516 // Note that a move constructor is not implicitly declared when there are
11517 // virtual bases, but it can still be user-declared and explicitly defaulted.
Aaron Ballman574705e2014-03-13 15:41:46 +000011518 for (const auto &Base : ClassDecl->bases()) {
11519 if (Base.isVirtual())
Sebastian Redl22653ba2011-08-30 19:58:05 +000011520 continue;
11521
11522 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000011523 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011524 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000011525 0, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +000011526 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011527 }
11528
Aaron Ballman445a9392014-03-13 16:15:17 +000011529 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000011530 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000011531 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011532 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000011533 0, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +000011534 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011535 }
11536
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011537 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000011538 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011539 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000011540 if (CXXMethodDecl *MoveAssign =
11541 LookupMovingAssignment(FieldClassDecl,
11542 FieldType.getCVRQualifiers(),
11543 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +000011544 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011545 }
11546 }
11547
11548 return ExceptSpec;
11549}
11550
11551CXXMethodDecl *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.
11661 Sema::SpecialMemberOverloadResult *SMOR =
11662 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
11663 /*ConstArg*/false, /*VolatileArg*/false,
11664 /*RValueThis*/true, /*ConstThis*/false,
11665 /*VolatileThis*/false);
11666 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
11667 !SMOR->getMethod()->isMoveAssignmentOperator())
11668 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.
11698 if (!SMOR->getMethod()->isDefaulted())
11699 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) {
11711 assert((MoveAssignOperator->isDefaulted() &&
11712 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");
11717
11718 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
11719
11720 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
11721 MoveAssignOperator->setInvalidDecl();
11722 return;
11723 }
11724
Eli Friedman276dd182013-09-05 00:02:25 +000011725 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011726
Eli Friedmaneaf34142012-10-18 20:14:08 +000011727 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011728 DiagnosticErrorTrap Trap(Diags);
11729
11730 // C++0x [class.copy]p28:
11731 // The implicitly-defined or move assignment operator for a non-union class
11732 // X performs memberwise move assignment of its subobjects. The direct base
11733 // classes of X are assigned first, in the order of their declaration in the
11734 // base-specifier-list, and then the immediate non-static data members of X
11735 // are assigned, in the order in which they were declared in the class
11736 // definition.
11737
Richard Smithb2504bd2013-11-04 04:26:14 +000011738 // Issue a warning if our implicit move assignment operator will move
11739 // from a virtual base more than once.
11740 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +000011741
Sebastian Redl22653ba2011-08-30 19:58:05 +000011742 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000011743 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +000011744
11745 // The parameter for the "other" object, which we are move from.
11746 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
11747 QualType OtherRefType = Other->getType()->
11748 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +000011749 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000011750 "Bad argument type of defaulted move assignment");
11751
11752 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011753 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
11754 ? MoveAssignOperator->getLocEnd()
11755 : MoveAssignOperator->getLocation();
Sebastian Redl22653ba2011-08-30 19:58:05 +000011756
Pavel Labath58934982013-08-30 08:52:28 +000011757 // Builds a reference to the "other" object.
11758 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011759 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +000011760 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011761
Pavel Labath58934982013-08-30 08:52:28 +000011762 // Builds the "this" pointer.
11763 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +000011764
Sebastian Redl22653ba2011-08-30 19:58:05 +000011765 // Assign base classes.
11766 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000011767 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +000011768 // C++11 [class.copy]p28:
11769 // It is unspecified whether subobjects representing virtual base classes
11770 // are assigned more than once by the implicitly-defined copy assignment
11771 // operator.
11772 // FIXME: Do not assign to a vbase that will be assigned by some other base
11773 // class. For a move-assignment, this can result in the vbase being moved
11774 // multiple times.
11775
Sebastian Redl22653ba2011-08-30 19:58:05 +000011776 // Form the assignment:
11777 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000011778 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +000011779 if (!BaseType->isRecordType()) {
11780 Invalid = true;
11781 continue;
11782 }
11783
11784 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000011785 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011786
11787 // Construct the "from" expression, which is an implicit cast to the
11788 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000011789 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011790
11791 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000011792 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011793
11794 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000011795 CastBuilder To(DerefThis,
11796 Context.getCVRQualifiedType(
11797 BaseType, MoveAssignOperator->getTypeQualifiers()),
11798 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011799
11800 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +000011801 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000011802 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000011803 /*CopyingBaseSubobject=*/true,
11804 /*Copying=*/false);
11805 if (Move.isInvalid()) {
11806 Diag(CurrentLocation, diag::note_member_synthesized_at)
11807 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11808 MoveAssignOperator->setInvalidDecl();
11809 return;
11810 }
11811
11812 // Success! Record the move.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011813 Statements.push_back(Move.getAs<Expr>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011814 }
11815
Sebastian Redl22653ba2011-08-30 19:58:05 +000011816 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011817 for (auto *Field : ClassDecl->fields()) {
Richard Smith419bd092015-04-29 19:26:57 +000011818 // FIXME: We should form some kind of AST representation for the implied
11819 // memcpy in a union copy operation.
11820 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
Douglas Gregor556e5862011-10-10 17:22:13 +000011821 continue;
11822
Eli Friedmanc9817fd2013-06-07 01:48:56 +000011823 if (Field->isInvalidDecl()) {
11824 Invalid = true;
11825 continue;
11826 }
11827
Sebastian Redl22653ba2011-08-30 19:58:05 +000011828 // Check for members of reference type; we can't move those.
11829 if (Field->getType()->isReferenceType()) {
11830 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11831 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11832 Diag(Field->getLocation(), diag::note_declared_at);
11833 Diag(CurrentLocation, diag::note_member_synthesized_at)
11834 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11835 Invalid = true;
11836 continue;
11837 }
11838
11839 // Check for members of const-qualified, non-class type.
11840 QualType BaseType = Context.getBaseElementType(Field->getType());
11841 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11842 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11843 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11844 Diag(Field->getLocation(), diag::note_declared_at);
11845 Diag(CurrentLocation, diag::note_member_synthesized_at)
11846 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11847 Invalid = true;
11848 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;
Sebastian Redl22653ba2011-08-30 19:58:05 +000011854
11855 QualType FieldType = Field->getType().getNonReferenceType();
11856 if (FieldType->isIncompleteArrayType()) {
11857 assert(ClassDecl->hasFlexibleArrayMember() &&
11858 "Incomplete array type is not valid");
11859 continue;
11860 }
11861
11862 // 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()) {
11882 Diag(CurrentLocation, diag::note_member_synthesized_at)
11883 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11884 MoveAssignOperator->setInvalidDecl();
11885 return;
11886 }
Richard Smith11d19592012-11-12 23:33:00 +000011887
Sebastian Redl22653ba2011-08-30 19:58:05 +000011888 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011889 Statements.push_back(Move.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011890 }
11891
11892 if (!Invalid) {
11893 // Add a "return *this;"
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011894 ExprResult ThisObj =
11895 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11896
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000011897 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011898 if (Return.isInvalid())
11899 Invalid = true;
11900 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011901 Statements.push_back(Return.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011902
11903 if (Trap.hasErrorOccurred()) {
11904 Diag(CurrentLocation, diag::note_member_synthesized_at)
11905 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11906 Invalid = true;
11907 }
11908 }
11909 }
11910
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000011911 // The exception specification is needed because we are defining the
11912 // function.
11913 ResolveExceptionSpec(CurrentLocation,
11914 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
11915
Sebastian Redl22653ba2011-08-30 19:58:05 +000011916 if (Invalid) {
11917 MoveAssignOperator->setInvalidDecl();
11918 return;
11919 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011920
11921 StmtResult Body;
11922 {
11923 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011924 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011925 /*isStmtExpr=*/false);
11926 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11927 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011928 MoveAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011929
11930 if (ASTMutationListener *L = getASTMutationListener()) {
11931 L->CompletedImplicitDefinition(MoveAssignOperator);
11932 }
11933}
11934
Richard Smithd3b5c9082012-07-27 04:22:15 +000011935Sema::ImplicitExceptionSpecification
11936Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
11937 CXXRecordDecl *ClassDecl = MD->getParent();
11938
11939 ImplicitExceptionSpecification ExceptSpec(*this);
11940 if (ClassDecl->isInvalidDecl())
11941 return ExceptSpec;
11942
11943 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000011944 assert(T->getNumParams() >= 1 && "not a copy ctor");
11945 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000011946
Douglas Gregor8453ddb2010-07-01 20:59:04 +000011947 // C++ [except.spec]p14:
11948 // An implicitly declared special member function (Clause 12) shall have an
11949 // exception-specification. [...]
Aaron Ballman574705e2014-03-13 15:41:46 +000011950 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor8453ddb2010-07-01 20:59:04 +000011951 // Virtual bases are handled below.
Aaron Ballman574705e2014-03-13 15:41:46 +000011952 if (Base.isVirtual())
Douglas Gregor8453ddb2010-07-01 20:59:04 +000011953 continue;
11954
Douglas Gregora6d69502010-07-02 23:41:54 +000011955 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000011956 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000011957 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000011958 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman574705e2014-03-13 15:41:46 +000011959 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000011960 }
Aaron Ballman445a9392014-03-13 16:15:17 +000011961 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregora6d69502010-07-02 23:41:54 +000011962 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000011963 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000011964 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000011965 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman445a9392014-03-13 16:15:17 +000011966 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000011967 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011968 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000011969 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000011970 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
11971 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000011972 LookupCopyingConstructor(FieldClassDecl,
11973 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000011974 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000011975 }
11976 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000011977
Richard Smithd3b5c9082012-07-27 04:22:15 +000011978 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000011979}
11980
11981CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
11982 CXXRecordDecl *ClassDecl) {
11983 // C++ [class.copy]p4:
11984 // If the class definition does not explicitly declare a copy
11985 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000011986 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000011987
Richard Smith8bf22e52012-11-29 01:34:07 +000011988 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
11989 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000011990 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000011991
Alexis Hunt913820d2011-05-13 06:10:58 +000011992 QualType ClassType = Context.getTypeDeclType(ClassDecl);
11993 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000011994 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000011995 if (Const)
11996 ArgType = ArgType.withConst();
11997 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000011998
Richard Smithb5800092012-06-10 05:43:50 +000011999 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12000 CXXCopyConstructor,
12001 Const);
12002
Douglas Gregor54be3392010-07-01 17:57:27 +000012003 DeclarationName Name
12004 = Context.DeclarationNames.getCXXConstructorName(
12005 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000012006 SourceLocation ClassLoc = ClassDecl->getLocation();
12007 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000012008
12009 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000012010 // member of its class.
12011 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000012012 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000012013 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000012014 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000012015 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000012016 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000012017
Eli Bendersky9a220fc2014-09-29 20:38:29 +000012018 if (getLangOpts().CUDA) {
12019 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
12020 CopyConstructor,
12021 /* ConstRHS */ Const,
12022 /* Diagnose */ false);
12023 }
12024
Richard Smithd3b5c9082012-07-27 04:22:15 +000012025 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000012026 FunctionProtoType::ExtProtoInfo EPI =
12027 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000012028 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000012029 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000012030
Douglas Gregor54be3392010-07-01 17:57:27 +000012031 // Add the parameter to the constructor.
12032 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000012033 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000012034 /*IdentifierInfo=*/nullptr,
12035 ArgType, /*TInfo=*/nullptr,
12036 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000012037 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000012038
Richard Smith6b02d462012-12-08 08:32:28 +000012039 CopyConstructor->setTrivial(
12040 ClassDecl->needsOverloadResolutionForCopyConstructor()
12041 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
12042 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000012043
Richard Smith6b02d462012-12-08 08:32:28 +000012044 // Note that we have declared this constructor.
12045 ++ASTContext::NumImplicitCopyConstructorsDeclared;
12046
Richard Smith12e79312016-05-13 06:47:56 +000012047 Scope *S = getScopeForContext(ClassDecl);
12048 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
12049
12050 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
12051 SetDeclDeleted(CopyConstructor, ClassLoc);
12052
12053 if (S)
Richard Smith6b02d462012-12-08 08:32:28 +000012054 PushOnScopeChains(CopyConstructor, S, false);
12055 ClassDecl->addDecl(CopyConstructor);
12056
Douglas Gregor54be3392010-07-01 17:57:27 +000012057 return CopyConstructor;
12058}
12059
Fariborz Jahanian477d2422009-06-22 23:34:40 +000012060void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000012061 CXXConstructorDecl *CopyConstructor) {
12062 assert((CopyConstructor->isDefaulted() &&
12063 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000012064 !CopyConstructor->doesThisDeclarationHaveABody() &&
12065 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000012066 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000012067
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000012068 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000012069 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000012070
Richard Smithd577fbb2013-06-13 03:23:42 +000012071 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000012072 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000012073 // deprecated if the class has a user-declared copy assignment operator
12074 // or a user-declared destructor.
12075 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12076 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
12077
Eli Friedmaneaf34142012-10-18 20:14:08 +000012078 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000012079 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000012080
David Blaikie3fc2f912013-01-17 05:26:25 +000012081 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000012082 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000012083 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000012084 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000012085 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000012086 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000012087 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
12088 ? CopyConstructor->getLocEnd()
12089 : CopyConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012090 Sema::CompoundScopeRAII CompoundScope(*this);
Daniel Jasperb3b0b802014-06-20 08:44:22 +000012091 CopyConstructor->setBody(
12092 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000012093 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000012094
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000012095 // The exception specification is needed because we are defining the
12096 // function.
12097 ResolveExceptionSpec(CurrentLocation,
12098 CopyConstructor->getType()->castAs<FunctionProtoType>());
12099
Eli Friedman276dd182013-09-05 00:02:25 +000012100 CopyConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000012101 MarkVTableUsed(CurrentLocation, ClassDecl);
12102
Sebastian Redlab238a72011-04-24 16:28:06 +000012103 if (ASTMutationListener *L = getASTMutationListener()) {
12104 L->CompletedImplicitDefinition(CopyConstructor);
12105 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000012106}
12107
Sebastian Redl22653ba2011-08-30 19:58:05 +000012108Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000012109Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
12110 CXXRecordDecl *ClassDecl = MD->getParent();
12111
Sebastian Redl22653ba2011-08-30 19:58:05 +000012112 // C++ [except.spec]p14:
12113 // An implicitly declared special member function (Clause 12) shall have an
12114 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000012115 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012116 if (ClassDecl->isInvalidDecl())
12117 return ExceptSpec;
12118
12119 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000012120 for (const auto &B : ClassDecl->bases()) {
12121 if (B.isVirtual()) // Handled below.
Sebastian Redl22653ba2011-08-30 19:58:05 +000012122 continue;
12123
Aaron Ballman574705e2014-03-13 15:41:46 +000012124 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000012125 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000012126 CXXConstructorDecl *Constructor =
12127 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012128 // If this is a deleted function, add it anyway. This might be conformant
12129 // with the standard. This might not. I'm not sure. It might not matter.
12130 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +000012131 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012132 }
12133 }
12134
12135 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000012136 for (const auto &B : ClassDecl->vbases()) {
12137 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000012138 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000012139 CXXConstructorDecl *Constructor =
12140 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012141 // If this is a deleted function, add it anyway. This might be conformant
12142 // with the standard. This might not. I'm not sure. It might not matter.
12143 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000012144 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012145 }
12146 }
12147
12148 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012149 for (const auto *F : ClassDecl->fields()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000012150 QualType FieldType = Context.getBaseElementType(F->getType());
12151 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
12152 CXXConstructorDecl *Constructor =
12153 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000012154 // If this is a deleted function, add it anyway. This might be conformant
12155 // with the standard. This might not. I'm not sure. It might not matter.
12156 // In particular, the problem is that this function never gets called. It
12157 // might just be ill-formed because this function attempts to refer to
12158 // a deleted function here.
12159 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000012160 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012161 }
12162 }
12163
12164 return ExceptSpec;
12165}
12166
12167CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12168 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000012169 assert(ClassDecl->needsImplicitMoveConstructor());
12170
Richard Smith8bf22e52012-11-29 01:34:07 +000012171 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12172 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000012173 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000012174
Sebastian Redl22653ba2011-08-30 19:58:05 +000012175 QualType ClassType = Context.getTypeDeclType(ClassDecl);
12176 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012177
Richard Smithb5800092012-06-10 05:43:50 +000012178 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12179 CXXMoveConstructor,
12180 false);
12181
Sebastian Redl22653ba2011-08-30 19:58:05 +000012182 DeclarationName Name
12183 = Context.DeclarationNames.getCXXConstructorName(
12184 Context.getCanonicalType(ClassType));
12185 SourceLocation ClassLoc = ClassDecl->getLocation();
12186 DeclarationNameInfo NameInfo(Name, ClassLoc);
12187
Richard Smith99005e62013-05-07 03:19:20 +000012188 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000012189 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000012190 // member of its class.
12191 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000012192 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000012193 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000012194 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012195 MoveConstructor->setAccess(AS_public);
12196 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000012197
Eli Bendersky9a220fc2014-09-29 20:38:29 +000012198 if (getLangOpts().CUDA) {
12199 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12200 MoveConstructor,
12201 /* ConstRHS */ false,
12202 /* Diagnose */ false);
12203 }
12204
Richard Smithd3b5c9082012-07-27 04:22:15 +000012205 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000012206 FunctionProtoType::ExtProtoInfo EPI =
12207 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000012208 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000012209 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000012210
Sebastian Redl22653ba2011-08-30 19:58:05 +000012211 // Add the parameter to the constructor.
12212 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12213 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000012214 /*IdentifierInfo=*/nullptr,
12215 ArgType, /*TInfo=*/nullptr,
12216 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000012217 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012218
Richard Smith6b02d462012-12-08 08:32:28 +000012219 MoveConstructor->setTrivial(
12220 ClassDecl->needsOverloadResolutionForMoveConstructor()
12221 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12222 : ClassDecl->hasTrivialMoveConstructor());
12223
Richard Smith12e79312016-05-13 06:47:56 +000012224 // Note that we have declared this constructor.
12225 ++ASTContext::NumImplicitMoveConstructorsDeclared;
12226
12227 Scope *S = getScopeForContext(ClassDecl);
12228 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12229
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000012230 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000012231 ClassDecl->setImplicitMoveConstructorIsDeleted();
12232 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012233 }
12234
Richard Smith12e79312016-05-13 06:47:56 +000012235 if (S)
Sebastian Redl22653ba2011-08-30 19:58:05 +000012236 PushOnScopeChains(MoveConstructor, S, false);
12237 ClassDecl->addDecl(MoveConstructor);
12238
12239 return MoveConstructor;
12240}
12241
12242void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12243 CXXConstructorDecl *MoveConstructor) {
12244 assert((MoveConstructor->isDefaulted() &&
12245 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000012246 !MoveConstructor->doesThisDeclarationHaveABody() &&
12247 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000012248 "DefineImplicitMoveConstructor - call it for implicit move ctor");
12249
12250 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12251 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12252
Eli Friedmaneaf34142012-10-18 20:14:08 +000012253 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012254 DiagnosticErrorTrap Trap(Diags);
12255
David Blaikie3fc2f912013-01-17 05:26:25 +000012256 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000012257 Trap.hasErrorOccurred()) {
12258 Diag(CurrentLocation, diag::note_member_synthesized_at)
12259 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
12260 MoveConstructor->setInvalidDecl();
12261 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000012262 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
12263 ? MoveConstructor->getLocEnd()
12264 : MoveConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012265 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000012266 MoveConstructor->setBody(ActOnCompoundStmt(
Daniel Jasperb3b0b802014-06-20 08:44:22 +000012267 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000012268 }
12269
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000012270 // The exception specification is needed because we are defining the
12271 // function.
12272 ResolveExceptionSpec(CurrentLocation,
12273 MoveConstructor->getType()->castAs<FunctionProtoType>());
12274
Eli Friedman276dd182013-09-05 00:02:25 +000012275 MoveConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000012276 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012277
12278 if (ASTMutationListener *L = getASTMutationListener()) {
12279 L->CompletedImplicitDefinition(MoveConstructor);
12280 }
12281}
12282
Douglas Gregor74f7d502012-02-15 19:33:52 +000012283bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000012284 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000012285}
Douglas Gregord3b672c2012-02-16 01:06:16 +000012286
12287void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000012288 SourceLocation CurrentLocation,
12289 CXXConversionDecl *Conv) {
12290 CXXRecordDecl *Lambda = Conv->getParent();
12291 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
12292 // If we are defining a specialization of a conversion to function-ptr
12293 // cache the deduced template arguments for this specialization
12294 // so that we can use them to retrieve the corresponding call-operator
12295 // and static-invoker.
Craig Topperc3ec1492014-05-26 06:22:03 +000012296 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
12297
Faisal Vali571df122013-09-29 08:45:24 +000012298 // Retrieve the corresponding call-operator specialization.
12299 if (Lambda->isGenericLambda()) {
12300 assert(Conv->isFunctionTemplateSpecialization());
12301 FunctionTemplateDecl *CallOpTemplate =
12302 CallOp->getDescribedFunctionTemplate();
12303 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
Craig Topperc3ec1492014-05-26 06:22:03 +000012304 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000012305 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000012306 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000012307 InsertPos);
12308 assert(CallOpSpec &&
12309 "Conversion operator must have a corresponding call operator");
12310 CallOp = cast<CXXMethodDecl>(CallOpSpec);
12311 }
12312 // Mark the call operator referenced (and add to pending instantiations
12313 // if necessary).
12314 // For both the conversion and static-invoker template specializations
12315 // we construct their body's in this function, so no need to add them
12316 // to the PendingInstantiations.
12317 MarkFunctionReferenced(CurrentLocation, CallOp);
12318
Eli Friedmaneaf34142012-10-18 20:14:08 +000012319 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000012320 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000012321
Alp Tokerf6a24ce2013-12-05 16:25:25 +000012322 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000012323 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
12324 // ... and get the corresponding specialization for a generic lambda.
12325 if (Lambda->isGenericLambda()) {
12326 assert(DeducedTemplateArgs &&
12327 "Must have deduced template arguments from Conversion Operator");
12328 FunctionTemplateDecl *InvokeTemplate =
12329 Invoker->getDescribedFunctionTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +000012330 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000012331 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000012332 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000012333 InsertPos);
12334 assert(InvokeSpec &&
12335 "Must have a corresponding static invoker specialization");
12336 Invoker = cast<CXXMethodDecl>(InvokeSpec);
12337 }
12338 // Construct the body of the conversion function { return __invoke; }.
12339 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012340 VK_LValue, Conv->getLocation()).get();
Faisal Vali571df122013-09-29 08:45:24 +000012341 assert(FunctionRef && "Can't refer to __invoke function?");
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012342 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
Faisal Vali571df122013-09-29 08:45:24 +000012343 Conv->setBody(new (Context) CompoundStmt(Context, Return,
12344 Conv->getLocation(),
12345 Conv->getLocation()));
12346
12347 Conv->markUsed(Context);
12348 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000012349
Faisal Vali571df122013-09-29 08:45:24 +000012350 // Fill in the __invoke function with a dummy implementation. IR generation
12351 // will fill in the actual details.
12352 Invoker->markUsed(Context);
12353 Invoker->setReferenced();
12354 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12355
Douglas Gregord3b672c2012-02-16 01:06:16 +000012356 if (ASTMutationListener *L = getASTMutationListener()) {
12357 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000012358 L->CompletedImplicitDefinition(Invoker);
12359 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000012360}
12361
Faisal Vali571df122013-09-29 08:45:24 +000012362
12363
Douglas Gregord3b672c2012-02-16 01:06:16 +000012364void Sema::DefineImplicitLambdaToBlockPointerConversion(
12365 SourceLocation CurrentLocation,
12366 CXXConversionDecl *Conv)
12367{
Faisal Vali850da1a2013-09-29 17:08:32 +000012368 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000012369
Eli Friedman276dd182013-09-05 00:02:25 +000012370 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000012371
Eli Friedmaneaf34142012-10-18 20:14:08 +000012372 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000012373 DiagnosticErrorTrap Trap(Diags);
12374
Douglas Gregored90df32012-02-22 05:02:47 +000012375 // Copy-initialize the lambda object as needed to capture it.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012376 Expr *This = ActOnCXXThis(CurrentLocation).get();
12377 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
Douglas Gregord3b672c2012-02-16 01:06:16 +000012378
Eli Friedman98b01ed2012-03-01 04:01:32 +000012379 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12380 Conv->getLocation(),
12381 Conv, DerefThis);
12382
12383 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12384 // behavior. Note that only the general conversion function does this
12385 // (since it's unusable otherwise); in the case where we inline the
12386 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012387 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000012388 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12389 CK_CopyAndAutoreleaseBlockObject,
Craig Topperc3ec1492014-05-26 06:22:03 +000012390 BuildBlock.get(), nullptr, VK_RValue);
Eli Friedman98b01ed2012-03-01 04:01:32 +000012391
12392 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000012393 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000012394 Conv->setInvalidDecl();
12395 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000012396 }
Douglas Gregored90df32012-02-22 05:02:47 +000012397
Douglas Gregored90df32012-02-22 05:02:47 +000012398 // Create the return statement that returns the block from the conversion
12399 // function.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000012400 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000012401 if (Return.isInvalid()) {
12402 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12403 Conv->setInvalidDecl();
12404 return;
12405 }
12406
12407 // Set the body of the conversion function.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012408 Stmt *ReturnS = Return.get();
Nico Webera2a0eb92012-12-29 20:03:39 +000012409 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000012410 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000012411 Conv->getLocation()));
12412
Douglas Gregored90df32012-02-22 05:02:47 +000012413 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000012414 if (ASTMutationListener *L = getASTMutationListener()) {
12415 L->CompletedImplicitDefinition(Conv);
12416 }
12417}
12418
Douglas Gregord2f70072012-03-10 06:53:13 +000012419/// \brief Determine whether the given list arguments contains exactly one
12420/// "real" (non-default) argument.
12421static bool hasOneRealArgument(MultiExprArg Args) {
12422 switch (Args.size()) {
12423 case 0:
12424 return false;
12425
12426 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012427 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000012428 return false;
12429
12430 // fall through
12431 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012432 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000012433 }
12434
12435 return false;
12436}
12437
John McCalldadc5752010-08-24 06:29:42 +000012438ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000012439Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Richard Smithc2bebe92016-05-11 20:37:46 +000012440 NamedDecl *FoundDecl,
Mike Stump11289f42009-09-09 15:08:12 +000012441 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000012442 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012443 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000012444 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000012445 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000012446 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000012447 unsigned ConstructKind,
12448 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000012449 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000012450
Douglas Gregor45cf7e32010-04-02 18:24:57 +000012451 // C++0x [class.copy]p34:
12452 // When certain criteria are met, an implementation is allowed to
12453 // omit the copy/move construction of a class object, even if the
12454 // copy/move constructor and/or destructor for the object have
12455 // side effects. [...]
12456 // - when a temporary class object that has not been bound to a
12457 // reference (12.2) would be copied/moved to a class object
12458 // with the same cv-unqualified type, the copy/move operation
12459 // can be omitted by constructing the temporary object
12460 // directly into the target of the omitted copy/move
Richard Smith5179eb72016-06-28 19:03:57 +000012461 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
Douglas Gregord2f70072012-03-10 06:53:13 +000012462 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000012463 Expr *SubExpr = ExprArgs[0];
Richard Smith5179eb72016-06-28 19:03:57 +000012464 Elidable = SubExpr->isTemporaryObject(
12465 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
Anders Carlsson250aada2009-08-16 05:13:48 +000012466 }
Mike Stump11289f42009-09-09 15:08:12 +000012467
Richard Smithc2bebe92016-05-11 20:37:46 +000012468 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12469 FoundDecl, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012470 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithf8adcdc2014-07-17 05:12:35 +000012471 IsListInitialization,
12472 IsStdInitListInitialization, RequiresZeroInit,
Richard Smithd59b8322012-12-19 01:39:02 +000012473 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000012474}
12475
John McCalldadc5752010-08-24 06:29:42 +000012476ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000012477Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Richard Smithc2bebe92016-05-11 20:37:46 +000012478 NamedDecl *FoundDecl,
12479 CXXConstructorDecl *Constructor,
12480 bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000012481 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012482 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000012483 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000012484 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000012485 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000012486 unsigned ConstructKind,
12487 SourceRange ParenRange) {
Richard Smith80a47022016-06-29 01:10:27 +000012488 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
Richard Smith5179eb72016-06-28 19:03:57 +000012489 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
Richard Smith80a47022016-06-29 01:10:27 +000012490 if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12491 return ExprError();
12492 }
Richard Smith5179eb72016-06-28 19:03:57 +000012493
Richard Smithc83bf822016-06-10 00:58:19 +000012494 return BuildCXXConstructExpr(
12495 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12496 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12497 RequiresZeroInit, ConstructKind, ParenRange);
12498}
12499
12500/// BuildCXXConstructExpr - Creates a complete call to a constructor,
12501/// including handling of its default argument expressions.
12502ExprResult
12503Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12504 CXXConstructorDecl *Constructor,
12505 bool Elidable,
12506 MultiExprArg ExprArgs,
12507 bool HadMultipleCandidates,
12508 bool IsListInitialization,
12509 bool IsStdInitListInitialization,
12510 bool RequiresZeroInit,
12511 unsigned ConstructKind,
12512 SourceRange ParenRange) {
Richard Smith5179eb72016-06-28 19:03:57 +000012513 assert(declaresSameEntity(
12514 Constructor->getParent(),
12515 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12516 "given constructor for wrong type");
Eli Friedmanfa0df832012-02-02 03:46:19 +000012517 MarkFunctionReferenced(ConstructLoc, Constructor);
Justin Lebar18e2d822016-08-15 23:00:49 +000012518 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
12519 return ExprError();
Richard Smith5179eb72016-06-28 19:03:57 +000012520
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012521 return CXXConstructExpr::Create(
Richard Smithc83bf822016-06-10 00:58:19 +000012522 Context, DeclInitType, ConstructLoc, Constructor, Elidable,
Richard Smithc2bebe92016-05-11 20:37:46 +000012523 ExprArgs, HadMultipleCandidates, IsListInitialization,
12524 IsStdInitListInitialization, RequiresZeroInit,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012525 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12526 ParenRange);
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000012527}
12528
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012529ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12530 assert(Field->hasInClassInitializer());
12531
12532 // If we already have the in-class initializer nothing needs to be done.
12533 if (Field->getInClassInitializer())
12534 return CXXDefaultInitExpr::Create(Context, Loc, Field);
12535
Richard Smithd6a15082017-01-07 00:48:55 +000012536 // If we might have already tried and failed to instantiate, don't try again.
12537 if (Field->isInvalidDecl())
12538 return ExprError();
12539
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012540 // Maybe we haven't instantiated the in-class initializer. Go check the
12541 // pattern FieldDecl to see if it has one.
12542 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12543
12544 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12545 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12546 DeclContext::lookup_result Lookup =
12547 ClassPattern->lookup(Field->getDeclName());
Reid Kleckner327b0642016-04-29 18:06:53 +000012548
12549 // Lookup can return at most two results: the pattern for the field, or the
12550 // injected class name of the parent record. No other member can have the
12551 // same name as the field.
Vassil Vassileve53a4b72016-10-26 10:24:29 +000012552 // In modules mode, lookup can return multiple results (coming from
12553 // different modules).
12554 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
Reid Kleckner327b0642016-04-29 18:06:53 +000012555 "more than two lookup results for field name");
12556 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
12557 if (!Pattern) {
12558 assert(isa<CXXRecordDecl>(Lookup[0]) &&
12559 "cannot have other non-field member with same name");
Vassil Vassileve53a4b72016-10-26 10:24:29 +000012560 for (auto L : Lookup)
12561 if (isa<FieldDecl>(L)) {
12562 Pattern = cast<FieldDecl>(L);
12563 break;
12564 }
12565 assert(Pattern && "We must have set the Pattern!");
Reid Kleckner327b0642016-04-29 18:06:53 +000012566 }
12567
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012568 if (InstantiateInClassInitializer(Loc, Field, Pattern,
Richard Smithd6a15082017-01-07 00:48:55 +000012569 getTemplateInstantiationArgs(Field))) {
12570 // Don't diagnose this again.
12571 Field->setInvalidDecl();
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012572 return ExprError();
Richard Smithd6a15082017-01-07 00:48:55 +000012573 }
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012574 return CXXDefaultInitExpr::Create(Context, Loc, Field);
12575 }
12576
12577 // DR1351:
12578 // If the brace-or-equal-initializer of a non-static data member
12579 // invokes a defaulted default constructor of its class or of an
12580 // enclosing class in a potentially evaluated subexpression, the
12581 // program is ill-formed.
12582 //
12583 // This resolution is unworkable: the exception specification of the
12584 // default constructor can be needed in an unevaluated context, in
12585 // particular, in the operand of a noexcept-expression, and we can be
12586 // unable to compute an exception specification for an enclosed class.
12587 //
12588 // Any attempt to resolve the exception specification of a defaulted default
12589 // constructor before the initializer is lexically complete will ultimately
12590 // come here at which point we can diagnose it.
12591 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
Richard Smith8dbc6b22016-11-22 22:55:12 +000012592 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
12593 << OutermostClass << Field;
12594 Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
Richard Smith8d148352017-01-23 23:14:23 +000012595 // Recover by marking the field invalid, unless we're in a SFINAE context.
12596 if (!isSFINAEContext())
12597 Field->setInvalidDecl();
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012598 return ExprError();
12599}
12600
John McCall03c48482010-02-02 09:10:11 +000012601void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000012602 if (VD->isInvalidDecl()) return;
12603
John McCall03c48482010-02-02 09:10:11 +000012604 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000012605 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000012606 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000012607 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000012608
Chandler Carruth86d17d32011-03-27 21:26:48 +000012609 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000012610 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000012611 CheckDestructorAccess(VD->getLocation(), Destructor,
12612 PDiag(diag::err_access_dtor_var)
12613 << VD->getDeclName()
12614 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000012615 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000012616
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000012617 if (Destructor->isTrivial()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000012618 if (!VD->hasGlobalStorage()) return;
12619
12620 // Emit warning for non-trivial dtor in global scope (a real global,
12621 // class-static, function-static).
12622 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
12623
12624 // TODO: this should be re-enabled for static locals by !CXAAtExit
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000012625 if (!VD->isStaticLocal())
Chandler Carruth86d17d32011-03-27 21:26:48 +000012626 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000012627}
12628
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012629/// \brief Given a constructor and the set of arguments provided for the
12630/// constructor, convert the arguments and add any required default arguments
12631/// to form a proper call to this constructor.
12632///
12633/// \returns true if an error occurred, false otherwise.
12634bool
12635Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
12636 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000012637 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000012638 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000012639 bool AllowExplicit,
12640 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012641 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
12642 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000012643 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012644
12645 const FunctionProtoType *Proto
12646 = Constructor->getType()->getAs<FunctionProtoType>();
12647 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012648 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000012649
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012650 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012651 if (NumArgs < NumParams)
12652 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012653 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012654 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012655
12656 VariadicCallType CallType =
12657 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012658 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012659 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012660 Proto, 0,
12661 llvm::makeArrayRef(Args, NumArgs),
12662 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000012663 CallType, AllowExplicit,
12664 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000012665 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000012666
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012667 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012668
Dmitri Gribenko765396f2013-01-13 20:46:02 +000012669 CheckConstructorCall(Constructor,
Craig Topper8c2a2a02014-08-30 16:55:39 +000012670 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000012671 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012672
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012673 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000012674}
12675
Anders Carlssone363c8e2009-12-12 00:32:00 +000012676static inline bool
12677CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
12678 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000012679 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000012680 if (isa<NamespaceDecl>(DC)) {
12681 return SemaRef.Diag(FnDecl->getLocation(),
12682 diag::err_operator_new_delete_declared_in_namespace)
12683 << FnDecl->getDeclName();
12684 }
12685
12686 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000012687 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000012688 return SemaRef.Diag(FnDecl->getLocation(),
12689 diag::err_operator_new_delete_declared_static)
12690 << FnDecl->getDeclName();
12691 }
12692
Anders Carlsson60659a82009-12-12 02:43:16 +000012693 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000012694}
12695
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012696static inline bool
12697CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
12698 CanQualType ExpectedResultType,
12699 CanQualType ExpectedFirstParamType,
12700 unsigned DependentParamTypeDiag,
12701 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000012702 QualType ResultType =
12703 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012704
12705 // Check that the result type is not dependent.
12706 if (ResultType->isDependentType())
12707 return SemaRef.Diag(FnDecl->getLocation(),
12708 diag::err_operator_new_delete_dependent_result_type)
12709 << FnDecl->getDeclName() << ExpectedResultType;
12710
12711 // Check that the result type is what we expect.
12712 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
12713 return SemaRef.Diag(FnDecl->getLocation(),
12714 diag::err_operator_new_delete_invalid_result_type)
12715 << FnDecl->getDeclName() << ExpectedResultType;
12716
12717 // A function template must have at least 2 parameters.
12718 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
12719 return SemaRef.Diag(FnDecl->getLocation(),
12720 diag::err_operator_new_delete_template_too_few_parameters)
12721 << FnDecl->getDeclName();
12722
12723 // The function decl must have at least 1 parameter.
12724 if (FnDecl->getNumParams() == 0)
12725 return SemaRef.Diag(FnDecl->getLocation(),
12726 diag::err_operator_new_delete_too_few_parameters)
12727 << FnDecl->getDeclName();
12728
Sylvestre Ledru830885c2012-07-23 08:59:39 +000012729 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012730 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
12731 if (FirstParamType->isDependentType())
12732 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
12733 << FnDecl->getDeclName() << ExpectedFirstParamType;
12734
12735 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000012736 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012737 ExpectedFirstParamType)
12738 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
12739 << FnDecl->getDeclName() << ExpectedFirstParamType;
12740
12741 return false;
12742}
12743
Anders Carlsson12308f42009-12-11 23:23:22 +000012744static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012745CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000012746 // C++ [basic.stc.dynamic.allocation]p1:
12747 // A program is ill-formed if an allocation function is declared in a
12748 // namespace scope other than global scope or declared static in global
12749 // scope.
12750 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12751 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012752
12753 CanQualType SizeTy =
12754 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
12755
12756 // C++ [basic.stc.dynamic.allocation]p1:
12757 // The return type shall be void*. The first parameter shall have type
12758 // std::size_t.
12759 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
12760 SizeTy,
12761 diag::err_operator_new_dependent_param_type,
12762 diag::err_operator_new_param_type))
12763 return true;
12764
12765 // C++ [basic.stc.dynamic.allocation]p1:
12766 // The first parameter shall not have an associated default argument.
12767 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000012768 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012769 diag::err_operator_new_default_arg)
12770 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
12771
12772 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000012773}
12774
12775static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000012776CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000012777 // C++ [basic.stc.dynamic.deallocation]p1:
12778 // A program is ill-formed if deallocation functions are declared in a
12779 // namespace scope other than global scope or declared static in global
12780 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000012781 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12782 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000012783
12784 // C++ [basic.stc.dynamic.deallocation]p2:
12785 // Each deallocation function shall return void and its first parameter
12786 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012787 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
12788 SemaRef.Context.VoidPtrTy,
12789 diag::err_operator_delete_dependent_param_type,
12790 diag::err_operator_delete_param_type))
12791 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000012792
Anders Carlsson12308f42009-12-11 23:23:22 +000012793 return false;
12794}
12795
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012796/// CheckOverloadedOperatorDeclaration - Check whether the declaration
12797/// of this overloaded operator is well-formed. If so, returns false;
12798/// otherwise, emits appropriate diagnostics and returns true.
12799bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000012800 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012801 "Expected an overloaded operator declaration");
12802
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012803 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
12804
Mike Stump11289f42009-09-09 15:08:12 +000012805 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012806 // The allocation and deallocation functions, operator new,
12807 // operator new[], operator delete and operator delete[], are
12808 // described completely in 3.7.3. The attributes and restrictions
12809 // found in the rest of this subclause do not apply to them unless
12810 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000012811 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000012812 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000012813
Anders Carlsson22f443f2009-12-12 00:26:23 +000012814 if (Op == OO_New || Op == OO_Array_New)
12815 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012816
12817 // C++ [over.oper]p6:
12818 // An operator function shall either be a non-static member
12819 // function or be a non-member function and have at least one
12820 // parameter whose type is a class, a reference to a class, an
12821 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000012822 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
12823 if (MethodDecl->isStatic())
12824 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012825 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012826 } else {
12827 bool ClassOrEnumParam = false;
David Majnemer59f77922016-06-24 04:05:48 +000012828 for (auto Param : FnDecl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012829 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000012830 if (ParamType->isDependentType() || ParamType->isRecordType() ||
12831 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012832 ClassOrEnumParam = true;
12833 break;
12834 }
12835 }
12836
Douglas Gregord69246b2008-11-17 16:14:12 +000012837 if (!ClassOrEnumParam)
12838 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000012839 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012840 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012841 }
12842
12843 // C++ [over.oper]p8:
12844 // An operator function cannot have default arguments (8.3.6),
12845 // except where explicitly stated below.
12846 //
Mike Stump11289f42009-09-09 15:08:12 +000012847 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012848 // (C++ [over.call]p1).
12849 if (Op != OO_Call) {
David Majnemer59f77922016-06-24 04:05:48 +000012850 for (auto Param : FnDecl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012851 if (Param->hasDefaultArg())
12852 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000012853 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012854 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012855 }
12856 }
12857
Douglas Gregor6cf08062008-11-10 13:38:07 +000012858 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
12859 { false, false, false }
12860#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
12861 , { Unary, Binary, MemberOnly }
12862#include "clang/Basic/OperatorKinds.def"
12863 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012864
Douglas Gregor6cf08062008-11-10 13:38:07 +000012865 bool CanBeUnaryOperator = OperatorUses[Op][0];
12866 bool CanBeBinaryOperator = OperatorUses[Op][1];
12867 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012868
12869 // C++ [over.oper]p8:
12870 // [...] Operator functions cannot have more or fewer parameters
12871 // than the number required for the corresponding operator, as
12872 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000012873 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000012874 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012875 if (Op != OO_Call &&
12876 ((NumParams == 1 && !CanBeUnaryOperator) ||
12877 (NumParams == 2 && !CanBeBinaryOperator) ||
12878 (NumParams < 1) || (NumParams > 2))) {
12879 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012880 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000012881 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012882 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000012883 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012884 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000012885 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000012886 assert(CanBeBinaryOperator &&
12887 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012888 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000012889 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012890
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012891 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012892 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012893 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000012894
Douglas Gregord69246b2008-11-17 16:14:12 +000012895 // Overloaded operators other than operator() cannot be variadic.
12896 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000012897 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000012898 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012899 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012900 }
12901
12902 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000012903 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
12904 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000012905 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012906 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012907 }
12908
12909 // C++ [over.inc]p1:
12910 // The user-defined function called operator++ implements the
12911 // prefix and postfix ++ operator. If this function is a member
12912 // function with no parameters, or a non-member function with one
12913 // parameter of class or enumeration type, it defines the prefix
12914 // increment operator ++ for objects of that type. If the function
12915 // is a member function with one parameter (which shall be of type
12916 // int) or a non-member function with two parameters (the second
12917 // of which shall be of type int), it defines the postfix
12918 // increment operator ++ for objects of that type.
12919 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
12920 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000012921 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012922
Richard Smith538b52a2014-01-30 22:24:05 +000012923 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
12924 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000012925 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000012926 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000012927 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012928 }
12929
Douglas Gregord69246b2008-11-17 16:14:12 +000012930 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012931}
Chris Lattner3b024a32008-12-17 07:09:26 +000012932
Richard Smithc28aee62016-02-17 00:04:04 +000012933static bool
12934checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
12935 FunctionTemplateDecl *TpDecl) {
12936 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
12937
12938 // Must have one or two template parameters.
12939 if (TemplateParams->size() == 1) {
12940 NonTypeTemplateParmDecl *PmDecl =
12941 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
12942
12943 // The template parameter must be a char parameter pack.
12944 if (PmDecl && PmDecl->isTemplateParameterPack() &&
12945 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
12946 return false;
12947
12948 } else if (TemplateParams->size() == 2) {
12949 TemplateTypeParmDecl *PmType =
12950 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
12951 NonTypeTemplateParmDecl *PmArgs =
12952 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
12953
12954 // The second template parameter must be a parameter pack with the
12955 // first template parameter as its type.
12956 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
12957 PmArgs->isTemplateParameterPack()) {
12958 const TemplateTypeParmType *TArgs =
12959 PmArgs->getType()->getAs<TemplateTypeParmType>();
12960 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
12961 TArgs->getIndex() == PmType->getIndex()) {
12962 if (SemaRef.ActiveTemplateInstantiations.empty())
12963 SemaRef.Diag(TpDecl->getLocation(),
12964 diag::ext_string_literal_operator_template);
12965 return false;
12966 }
12967 }
12968 }
12969
12970 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
12971 diag::err_literal_operator_template)
12972 << TpDecl->getTemplateParameters()->getSourceRange();
12973 return true;
12974}
12975
Alexis Huntc88db062010-01-13 09:01:02 +000012976/// CheckLiteralOperatorDeclaration - Check whether the declaration
12977/// of this literal operator function is well-formed. If so, returns
12978/// false; otherwise, emits appropriate diagnostics and returns true.
12979bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000012980 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000012981 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
12982 << FnDecl->getDeclName();
12983 return true;
12984 }
12985
Richard Smith72eebee2012-03-04 09:41:16 +000012986 if (FnDecl->isExternC()) {
12987 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
Alex Lorenz560ae562016-11-02 15:46:34 +000012988 if (const LinkageSpecDecl *LSD =
12989 FnDecl->getDeclContext()->getExternCContext())
12990 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
Richard Smith72eebee2012-03-04 09:41:16 +000012991 return true;
12992 }
12993
Richard Smithbcc22fc2012-03-09 08:00:36 +000012994 // This might be the definition of a literal operator template.
12995 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
Richard Smithc28aee62016-02-17 00:04:04 +000012996
Richard Smithbcc22fc2012-03-09 08:00:36 +000012997 // This might be a specialization of a literal operator template.
12998 if (!TpDecl)
12999 TpDecl = FnDecl->getPrimaryTemplate();
13000
Richard Smithb8b41d32013-10-07 19:57:58 +000013001 // template <char...> type operator "" name() and
13002 // template <class T, T...> type operator "" name() are the only valid
13003 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000013004 if (TpDecl) {
Richard Smithc28aee62016-02-17 00:04:04 +000013005 if (FnDecl->param_size() != 0) {
13006 Diag(FnDecl->getLocation(),
13007 diag::err_literal_operator_template_with_params);
13008 return true;
Alexis Hunt7dd26172010-04-07 23:11:06 +000013009 }
Richard Smithc28aee62016-02-17 00:04:04 +000013010
13011 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
13012 return true;
13013
13014 } else if (FnDecl->param_size() == 1) {
13015 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
13016
13017 QualType ParamType = Param->getType().getUnqualifiedType();
13018
13019 // Only unsigned long long int, long double, any character type, and const
13020 // char * are allowed as the only parameters.
13021 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
13022 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
13023 Context.hasSameType(ParamType, Context.CharTy) ||
13024 Context.hasSameType(ParamType, Context.WideCharTy) ||
13025 Context.hasSameType(ParamType, Context.Char16Ty) ||
13026 Context.hasSameType(ParamType, Context.Char32Ty)) {
13027 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
13028 QualType InnerType = Ptr->getPointeeType();
13029
13030 // Pointer parameter must be a const char *.
13031 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
13032 Context.CharTy) &&
13033 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
13034 Diag(Param->getSourceRange().getBegin(),
13035 diag::err_literal_operator_param)
13036 << ParamType << "'const char *'" << Param->getSourceRange();
13037 return true;
13038 }
13039
13040 } else if (ParamType->isRealFloatingType()) {
13041 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13042 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
13043 return true;
13044
13045 } else if (ParamType->isIntegerType()) {
13046 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13047 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
13048 return true;
13049
13050 } else {
13051 Diag(Param->getSourceRange().getBegin(),
13052 diag::err_literal_operator_invalid_param)
13053 << ParamType << Param->getSourceRange();
13054 return true;
13055 }
13056
13057 } else if (FnDecl->param_size() == 2) {
Alexis Hunt7dd26172010-04-07 23:11:06 +000013058 FunctionDecl::param_iterator Param = FnDecl->param_begin();
13059
Richard Smithc28aee62016-02-17 00:04:04 +000013060 // First, verify that the first parameter is correct.
Alexis Huntc88db062010-01-13 09:01:02 +000013061
Richard Smithc28aee62016-02-17 00:04:04 +000013062 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
13063
13064 // Two parameter function must have a pointer to const as a
13065 // first parameter; let's strip those qualifiers.
13066 const PointerType *PT = FirstParamType->getAs<PointerType>();
13067
13068 if (!PT) {
13069 Diag((*Param)->getSourceRange().getBegin(),
13070 diag::err_literal_operator_param)
13071 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13072 return true;
Alexis Huntc88db062010-01-13 09:01:02 +000013073 }
13074
Richard Smithc28aee62016-02-17 00:04:04 +000013075 QualType PointeeType = PT->getPointeeType();
13076 // First parameter must be const
13077 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
13078 Diag((*Param)->getSourceRange().getBegin(),
13079 diag::err_literal_operator_param)
13080 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13081 return true;
13082 }
Alexis Huntc88db062010-01-13 09:01:02 +000013083
Richard Smithc28aee62016-02-17 00:04:04 +000013084 QualType InnerType = PointeeType.getUnqualifiedType();
13085 // Only const char *, const wchar_t*, const char16_t*, and const char32_t*
13086 // are allowed as the first parameter to a two-parameter function
13087 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
13088 Context.hasSameType(InnerType, Context.WideCharTy) ||
13089 Context.hasSameType(InnerType, Context.Char16Ty) ||
13090 Context.hasSameType(InnerType, Context.Char32Ty))) {
13091 Diag((*Param)->getSourceRange().getBegin(),
13092 diag::err_literal_operator_param)
13093 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13094 return true;
13095 }
13096
13097 // Move on to the second and final parameter.
Alexis Huntc88db062010-01-13 09:01:02 +000013098 ++Param;
13099
Richard Smithc28aee62016-02-17 00:04:04 +000013100 // The second parameter must be a std::size_t.
13101 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
13102 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
13103 Diag((*Param)->getSourceRange().getBegin(),
13104 diag::err_literal_operator_param)
13105 << SecondParamType << Context.getSizeType()
13106 << (*Param)->getSourceRange();
13107 return true;
Alexis Huntc88db062010-01-13 09:01:02 +000013108 }
Richard Smithc28aee62016-02-17 00:04:04 +000013109 } else {
13110 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
Alexis Huntc88db062010-01-13 09:01:02 +000013111 return true;
13112 }
13113
Richard Smithc28aee62016-02-17 00:04:04 +000013114 // Parameters are good.
13115
Richard Smith768cecc2012-03-09 08:16:22 +000013116 // A parameter-declaration-clause containing a default argument is not
13117 // equivalent to any of the permitted forms.
David Majnemer59f77922016-06-24 04:05:48 +000013118 for (auto Param : FnDecl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000013119 if (Param->hasDefaultArg()) {
13120 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000013121 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000013122 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000013123 break;
13124 }
13125 }
13126
Richard Smith0df56f42012-03-08 02:39:21 +000013127 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000013128 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13129 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000013130 // C++11 [usrlit.suffix]p1:
13131 // Literal suffix identifiers that do not start with an underscore
13132 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000013133 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
Eric Fiseliercb2f3262016-12-30 04:51:10 +000013134 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000013135 }
Richard Smith0df56f42012-03-08 02:39:21 +000013136
Alexis Huntc88db062010-01-13 09:01:02 +000013137 return false;
13138}
13139
Douglas Gregor07665a62009-01-05 19:45:36 +000013140/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13141/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000013142/// the '{'. ExternLoc is the location of the 'extern', Lang is the
13143/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000013144/// the '{' brace. Otherwise, this linkage specification does not
13145/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000013146Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000013147 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000013148 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000013149 StringLiteral *Lit = cast<StringLiteral>(LangStr);
13150 if (!Lit->isAscii()) {
13151 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13152 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000013153 return nullptr;
Richard Smith4ee696d2014-02-17 23:25:27 +000013154 }
13155
13156 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000013157 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000013158 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000013159 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000013160 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000013161 Language = LinkageSpecDecl::lang_cxx;
13162 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000013163 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13164 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000013165 return nullptr;
Chris Lattner438e5012008-12-17 07:13:27 +000013166 }
Mike Stump11289f42009-09-09 15:08:12 +000013167
Chris Lattner438e5012008-12-17 07:13:27 +000013168 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000013169
Richard Smith4ee696d2014-02-17 23:25:27 +000013170 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13171 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000013172 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000013173 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000013174 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000013175 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000013176}
13177
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000013178/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000013179/// the C++ linkage specification LinkageSpec. If RBraceLoc is
13180/// valid, it's the position of the closing '}' brace in a linkage
13181/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000013182Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000013183 Decl *LinkageSpec,
13184 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000013185 if (RBraceLoc.isValid()) {
13186 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13187 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000013188 }
Richard Smith4ee696d2014-02-17 23:25:27 +000013189 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000013190 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000013191}
13192
Michael Han84324352013-02-22 17:15:32 +000013193Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13194 AttributeList *AttrList,
13195 SourceLocation SemiLoc) {
13196 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13197 // Attribute declarations appertain to empty declaration so we handle
13198 // them here.
13199 if (AttrList)
13200 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000013201
Michael Han84324352013-02-22 17:15:32 +000013202 CurContext->addDecl(ED);
13203 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000013204}
13205
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013206/// \brief Perform semantic analysis for the variable declaration that
13207/// occurs within a C++ catch clause, returning the newly-created
13208/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000013209VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000013210 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000013211 SourceLocation StartLoc,
13212 SourceLocation Loc,
13213 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013214 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000013215 QualType ExDeclType = TInfo->getType();
13216
Sebastian Redl54c04d42008-12-22 19:15:10 +000013217 // Arrays and functions decay.
13218 if (ExDeclType->isArrayType())
13219 ExDeclType = Context.getArrayDecayedType(ExDeclType);
13220 else if (ExDeclType->isFunctionType())
13221 ExDeclType = Context.getPointerType(ExDeclType);
13222
13223 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13224 // The exception-declaration shall not denote a pointer or reference to an
13225 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000013226 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000013227 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000013228 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000013229 Invalid = true;
13230 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013231
David Majnemere56d1a02016-06-08 16:05:07 +000013232 if (ExDeclType->isVariablyModifiedType()) {
13233 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13234 Invalid = true;
13235 }
13236
Sebastian Redl54c04d42008-12-22 19:15:10 +000013237 QualType BaseType = ExDeclType;
13238 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000013239 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000013240 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000013241 BaseType = Ptr->getPointeeType();
13242 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000013243 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000013244 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000013245 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000013246 BaseType = Ref->getPointeeType();
13247 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000013248 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000013249 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000013250 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000013251 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000013252 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000013253
Mike Stump11289f42009-09-09 15:08:12 +000013254 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013255 RequireNonAbstractType(Loc, ExDeclType,
13256 diag::err_abstract_type_in_decl,
13257 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000013258 Invalid = true;
13259
John McCall2ca705e2010-07-24 00:37:23 +000013260 // Only the non-fragile NeXT runtime currently supports C++ catches
13261 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000013262 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000013263 QualType T = ExDeclType;
13264 if (const ReferenceType *RT = T->getAs<ReferenceType>())
13265 T = RT->getPointeeType();
13266
13267 if (T->isObjCObjectType()) {
13268 Diag(Loc, diag::err_objc_object_catch);
13269 Invalid = true;
13270 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000013271 // FIXME: should this be a test for macosx-fragile specifically?
13272 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000013273 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000013274 }
13275 }
13276
Abramo Bagnaradff19302011-03-08 08:55:46 +000013277 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000013278 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000013279 ExDecl->setExceptionVariable(true);
13280
Douglas Gregor8ca0c642011-12-10 01:22:52 +000013281 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000013282 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000013283 Invalid = true;
13284
Douglas Gregor750734c2011-07-06 18:14:43 +000013285 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000013286 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000013287 // Insulate this from anything else we might currently be parsing.
13288 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
13289
Douglas Gregor6de584c2010-03-05 23:38:39 +000013290 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000013291 // The object declared in an exception-declaration or, if the
13292 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000013293 // copy-initialized (8.5) from the exception object. [...]
13294 // The object is destroyed when the handler exits, after the destruction
13295 // of any automatic objects initialized within the handler.
13296 //
Nick Lewycky0f292892013-09-22 10:06:57 +000013297 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000013298 // it can be destroyed later.
David Majnemerfba75df2015-03-03 04:38:34 +000013299 QualType initType = Context.getExceptionObjectType(ExDeclType);
John McCall1bf58462011-02-16 08:02:54 +000013300
13301 InitializedEntity entity =
13302 InitializedEntity::InitializeVariable(ExDecl);
13303 InitializationKind initKind =
13304 InitializationKind::CreateCopy(Loc, SourceLocation());
13305
13306 Expr *opaqueValue =
13307 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000013308 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13309 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000013310 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000013311 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000013312 else {
13313 // If the constructor used was non-trivial, set this as the
13314 // "initializer".
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013315 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000013316 if (!construct->getConstructor()->isTrivial()) {
13317 Expr *init = MaybeCreateExprWithCleanups(construct);
13318 ExDecl->setInit(init);
13319 }
13320
13321 // And make sure it's destructable.
13322 FinalizeVarWithDestructor(ExDecl, recordType);
13323 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000013324 }
13325 }
13326
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013327 if (Invalid)
13328 ExDecl->setInvalidDecl();
13329
13330 return ExDecl;
13331}
13332
13333/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13334/// handler.
John McCall48871652010-08-21 09:40:31 +000013335Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000013336 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000013337 bool Invalid = D.isInvalidType();
13338
13339 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000013340 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13341 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000013342 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13343 D.getIdentifierLoc());
13344 Invalid = true;
13345 }
13346
Sebastian Redl54c04d42008-12-22 19:15:10 +000013347 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000013348 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000013349 LookupOrdinaryName,
13350 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000013351 // The scope should be freshly made just for us. There is just no way
Aaron Ballman9ef622e2014-06-02 13:10:07 +000013352 // it contains any previous declaration, except for function parameters in
13353 // a function-try-block's catch statement.
John McCall48871652010-08-21 09:40:31 +000013354 assert(!S->isDeclScope(PrevDecl));
Aaron Ballman9ef622e2014-06-02 13:10:07 +000013355 if (isDeclInScope(PrevDecl, CurContext, S)) {
13356 Diag(D.getIdentifierLoc(), diag::err_redefinition)
13357 << D.getIdentifier();
13358 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13359 Invalid = true;
13360 } else if (PrevDecl->isTemplateParameter())
Sebastian Redl54c04d42008-12-22 19:15:10 +000013361 // Maybe we will complain about the shadowed template parameter.
13362 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000013363 }
13364
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000013365 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000013366 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13367 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000013368 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000013369 }
13370
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000013371 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013372 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000013373 D.getIdentifierLoc(),
13374 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000013375 if (Invalid)
13376 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000013377
Sebastian Redl54c04d42008-12-22 19:15:10 +000013378 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000013379 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013380 PushOnScopeChains(ExDecl, S);
13381 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000013382 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000013383
Douglas Gregor758a8692009-06-17 21:51:59 +000013384 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000013385 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000013386}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000013387
Abramo Bagnaraea947882011-03-08 16:41:52 +000013388Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000013389 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000013390 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000013391 SourceLocation RParenLoc) {
Richard Smith085a64f2014-06-20 19:57:12 +000013392 StringLiteral *AssertMessage =
13393 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000013394
Richard Smithded9c2e2012-07-11 22:37:56 +000013395 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
Craig Topperc3ec1492014-05-26 06:22:03 +000013396 return nullptr;
Richard Smithded9c2e2012-07-11 22:37:56 +000013397
13398 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13399 AssertMessage, RParenLoc, false);
13400}
13401
13402Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13403 Expr *AssertExpr,
13404 StringLiteral *AssertMessage,
13405 SourceLocation RParenLoc,
13406 bool Failed) {
Richard Smith085a64f2014-06-20 19:57:12 +000013407 assert(AssertExpr != nullptr && "Expected non-null condition");
Richard Smithded9c2e2012-07-11 22:37:56 +000013408 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13409 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000013410 // In a static_assert-declaration, the constant-expression shall be a
13411 // constant expression that can be contextually converted to bool.
13412 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13413 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000013414 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000013415
Richard Smith902ca212011-12-14 23:32:26 +000013416 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000013417 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000013418 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000013419 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000013420 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000013421
Richard Smithded9c2e2012-07-11 22:37:56 +000013422 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013423 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000013424 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith085a64f2014-06-20 19:57:12 +000013425 if (AssertMessage)
13426 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000013427 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith085a64f2014-06-20 19:57:12 +000013428 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000013429 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000013430 }
Anders Carlsson54b26982009-03-14 00:33:21 +000013431 }
Mike Stump11289f42009-09-09 15:08:12 +000013432
Abramo Bagnaraea947882011-03-08 16:41:52 +000013433 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000013434 AssertExpr, AssertMessage, RParenLoc,
13435 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000013436
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000013437 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000013438 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000013439}
Sebastian Redlf769df52009-03-24 22:27:57 +000013440
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013441/// \brief Perform semantic analysis of the given friend type declaration.
13442///
13443/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000013444FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000013445 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013446 TypeSourceInfo *TSInfo) {
13447 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
13448
13449 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000013450 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013451
Richard Smithc8239732011-10-18 21:39:00 +000013452 // C++03 [class.friend]p2:
13453 // An elaborated-type-specifier shall be used in a friend declaration
13454 // for a class.*
13455 //
13456 // * The class-key of the elaborated-type-specifier is required.
13457 if (!ActiveTemplateInstantiations.empty()) {
13458 // Do not complain about the form of friend template types during
13459 // template instantiation; we will already have complained when the
13460 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000013461 } else {
13462 if (!T->isElaboratedTypeSpecifier()) {
13463 // If we evaluated the type to a record type, suggest putting
13464 // a tag in front.
13465 if (const RecordType *RT = T->getAs<RecordType>()) {
13466 RecordDecl *RD = RT->getDecl();
Alp Tokera030cd02014-05-05 12:38:48 +000013467
13468 SmallString<16> InsertionText(" ");
13469 InsertionText += RD->getKindName();
13470
Nick Lewycky36722d22013-02-06 05:59:33 +000013471 Diag(TypeRange.getBegin(),
13472 getLangOpts().CPlusPlus11 ?
13473 diag::warn_cxx98_compat_unelaborated_friend_type :
13474 diag::ext_unelaborated_friend_type)
13475 << (unsigned) RD->getTagKind()
13476 << T
Craig Topper07fa1762015-11-15 02:31:46 +000013477 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
Nick Lewycky36722d22013-02-06 05:59:33 +000013478 InsertionText);
13479 } else {
13480 Diag(FriendLoc,
13481 getLangOpts().CPlusPlus11 ?
13482 diag::warn_cxx98_compat_nonclass_type_friend :
13483 diag::ext_nonclass_type_friend)
13484 << T
13485 << TypeRange;
13486 }
13487 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000013488 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013489 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000013490 diag::warn_cxx98_compat_enum_friend :
13491 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013492 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000013493 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013494 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013495
Nick Lewycky36722d22013-02-06 05:59:33 +000013496 // C++11 [class.friend]p3:
13497 // A friend declaration that does not declare a function shall have one
13498 // of the following forms:
13499 // friend elaborated-type-specifier ;
13500 // friend simple-type-specifier ;
13501 // friend typename-specifier ;
13502 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
13503 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
13504 }
Richard Smitha31a89a2012-09-20 01:31:00 +000013505
Douglas Gregor3b4abb62010-04-07 17:57:12 +000013506 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000013507 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000013508 // the friend declaration is ignored.
Nikola Smiljanic3a01af02014-05-23 12:48:27 +000013509 return FriendDecl::Create(Context, CurContext,
13510 TSInfo->getTypeLoc().getLocStart(), TSInfo,
13511 FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013512}
13513
John McCallace48cd2010-10-19 01:40:49 +000013514/// Handle a friend tag declaration where the scope specifier was
13515/// templated.
13516Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
13517 unsigned TagSpec, SourceLocation TagLoc,
13518 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000013519 IdentifierInfo *Name,
13520 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000013521 AttributeList *Attr,
13522 MultiTemplateParamsArg TempParamLists) {
13523 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13524
Richard Smithf445f192017-02-09 21:04:43 +000013525 bool IsMemberSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000013526 bool Invalid = false;
13527
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000013528 if (TemplateParameterList *TemplateParams =
13529 MatchTemplateParametersToScopeSpecifier(
Craig Topperc3ec1492014-05-26 06:22:03 +000013530 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
Richard Smithf445f192017-02-09 21:04:43 +000013531 IsMemberSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000013532 if (TemplateParams->size() > 0) {
13533 // This is a declaration of a class template.
13534 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +000013535 return nullptr;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000013536
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000013537 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
13538 NameLoc, Attr, TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000013539 /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000013540 FriendLoc, TempParamLists.size() - 1,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013541 TempParamLists.data()).get();
John McCallace48cd2010-10-19 01:40:49 +000013542 } else {
13543 // The "template<>" header is extraneous.
13544 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13545 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
Richard Smithf445f192017-02-09 21:04:43 +000013546 IsMemberSpecialization = true;
John McCallace48cd2010-10-19 01:40:49 +000013547 }
13548 }
13549
Craig Topperc3ec1492014-05-26 06:22:03 +000013550 if (Invalid) return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000013551
John McCallace48cd2010-10-19 01:40:49 +000013552 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000013553 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000013554 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000013555 isAllExplicitSpecializations = false;
13556 break;
13557 }
13558 }
13559
13560 // FIXME: don't ignore attributes.
13561
13562 // If it's explicit specializations all the way down, just forget
13563 // about the template header and build an appropriate non-templated
13564 // friend. TODO: for source fidelity, remember the headers.
13565 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013566 if (SS.isEmpty()) {
13567 bool Owned = false;
13568 bool IsDependent = false;
13569 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000013570 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013571 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000013572 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000013573 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013574 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000013575 /*UnderlyingType=*/TypeResult(),
13576 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013577 }
Richard Smith649c7b062014-01-08 00:56:48 +000013578
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000013579 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000013580 ElaboratedTypeKeyword Keyword
13581 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000013582 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000013583 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000013584 if (T.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +000013585 return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000013586
13587 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13588 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000013589 DependentNameTypeLoc TL =
13590 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000013591 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000013592 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000013593 TL.setNameLoc(NameLoc);
13594 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000013595 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000013596 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000013597 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000013598 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000013599 }
13600
13601 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000013602 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000013603 Friend->setAccess(AS_public);
13604 CurContext->addDecl(Friend);
13605 return Friend;
13606 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013607
13608 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
13609
13610
John McCallace48cd2010-10-19 01:40:49 +000013611
13612 // Handle the case of a templated-scope friend class. e.g.
13613 // template <class T> class A<T>::B;
13614 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000013615 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
13616 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000013617 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13618 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
13619 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000013620 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000013621 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000013622 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000013623 TL.setNameLoc(NameLoc);
13624
13625 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000013626 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000013627 Friend->setAccess(AS_public);
13628 Friend->setUnsupportedFriend(true);
13629 CurContext->addDecl(Friend);
13630 return Friend;
13631}
13632
13633
John McCall11083da2009-09-16 22:47:08 +000013634/// Handle a friend type declaration. This works in tandem with
13635/// ActOnTag.
13636///
13637/// Notes on friend class templates:
13638///
13639/// We generally treat friend class declarations as if they were
13640/// declaring a class. So, for example, the elaborated type specifier
13641/// in a friend declaration is required to obey the restrictions of a
13642/// class-head (i.e. no typedefs in the scope chain), template
13643/// parameters are required to match up with simple template-ids, &c.
13644/// However, unlike when declaring a template specialization, it's
13645/// okay to refer to a template specialization without an empty
13646/// template parameter declaration, e.g.
13647/// friend class A<T>::B<unsigned>;
13648/// We permit this as a special case; if there are any template
13649/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000013650/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000013651Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000013652 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013653 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000013654
13655 assert(DS.isFriendSpecified());
13656 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13657
John McCall11083da2009-09-16 22:47:08 +000013658 // Try to convert the decl specifier to a type. This works for
13659 // friend templates because ActOnTag never produces a ClassTemplateDecl
13660 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000013661 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000013662 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
13663 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000013664 if (TheDeclarator.isInvalidType())
Craig Topperc3ec1492014-05-26 06:22:03 +000013665 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000013666
Douglas Gregor6c110f32010-12-16 01:14:37 +000013667 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000013668 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000013669
John McCall11083da2009-09-16 22:47:08 +000013670 // This is definitely an error in C++98. It's probably meant to
13671 // be forbidden in C++0x, too, but the specification is just
13672 // poorly written.
13673 //
13674 // The problem is with declarations like the following:
13675 // template <T> friend A<T>::foo;
13676 // where deciding whether a class C is a friend or not now hinges
13677 // on whether there exists an instantiation of A that causes
13678 // 'foo' to equal C. There are restrictions on class-heads
13679 // (which we declare (by fiat) elaborated friend declarations to
13680 // be) that makes this tractable.
13681 //
13682 // FIXME: handle "template <> friend class A<T>;", which
13683 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000013684 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000013685 Diag(Loc, diag::err_tagless_friend_type_template)
13686 << DS.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000013687 return nullptr;
John McCall11083da2009-09-16 22:47:08 +000013688 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013689
John McCallaa74a0c2009-08-28 07:59:38 +000013690 // C++98 [class.friend]p1: A friend of a class is a function
13691 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000013692 // This is fixed in DR77, which just barely didn't make the C++03
13693 // deadline. It's also a very silly restriction that seriously
13694 // affects inner classes and which nobody else seems to implement;
13695 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000013696 //
13697 // But note that we could warn about it: it's always useless to
13698 // friend one of your own members (it's not, however, worthless to
13699 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000013700
John McCall11083da2009-09-16 22:47:08 +000013701 Decl *D;
David Majnemerdfecf1a2016-07-06 04:19:16 +000013702 if (!TempParams.empty())
John McCall11083da2009-09-16 22:47:08 +000013703 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
David Majnemerdfecf1a2016-07-06 04:19:16 +000013704 TempParams,
John McCall15ad0962010-03-25 18:04:51 +000013705 TSI,
John McCall11083da2009-09-16 22:47:08 +000013706 DS.getFriendSpecLoc());
13707 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000013708 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013709
13710 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +000013711 return nullptr;
13712
John McCall11083da2009-09-16 22:47:08 +000013713 D->setAccess(AS_public);
13714 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000013715
John McCall48871652010-08-21 09:40:31 +000013716 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000013717}
13718
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000013719NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
13720 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000013721 const DeclSpec &DS = D.getDeclSpec();
13722
13723 assert(DS.isFriendSpecified());
13724 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13725
13726 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000013727 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000013728
13729 // C++ [class.friend]p1
13730 // A friend of a class is a function or class....
13731 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000013732 // It *doesn't* see through dependent types, which is correct
13733 // according to [temp.arg.type]p3:
13734 // If a declaration acquires a function type through a
13735 // type dependent on a template-parameter and this causes
13736 // a declaration that does not use the syntactic form of a
13737 // function declarator to have a function type, the program
13738 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013739 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000013740 Diag(Loc, diag::err_unexpected_friend);
13741
13742 // It might be worthwhile to try to recover by creating an
13743 // appropriate declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000013744 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000013745 }
13746
13747 // C++ [namespace.memdef]p3
13748 // - If a friend declaration in a non-local class first declares a
13749 // class or function, the friend class or function is a member
13750 // of the innermost enclosing namespace.
13751 // - The name of the friend is not found by simple name lookup
13752 // until a matching declaration is provided in that namespace
13753 // scope (either before or after the class declaration granting
13754 // friendship).
13755 // - If a friend function is called, its name may be found by the
13756 // name lookup that considers functions from namespaces and
13757 // classes associated with the types of the function arguments.
13758 // - When looking for a prior declaration of a class or a function
13759 // declared as a friend, scopes outside the innermost enclosing
13760 // namespace scope are not considered.
13761
John McCallde3fd222010-10-12 23:13:28 +000013762 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000013763 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
13764 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000013765 assert(Name);
13766
Douglas Gregor6c110f32010-12-16 01:14:37 +000013767 // Check for unexpanded parameter packs.
13768 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
13769 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
13770 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000013771 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000013772
John McCall07e91c02009-08-06 02:15:43 +000013773 // The context we found the declaration in, or in which we should
13774 // create the declaration.
13775 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000013776 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000013777 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000013778 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000013779
Richard Smith114394f2013-08-09 04:35:01 +000013780 // There are five cases here.
13781 // - There's no scope specifier and we're in a local class. Only look
13782 // for functions declared in the immediately-enclosing block scope.
13783 // We recover from invalid scope qualifiers as if they just weren't there.
Craig Topperc3ec1492014-05-26 06:22:03 +000013784 FunctionDecl *FunctionContainingLocalClass = nullptr;
Richard Smith114394f2013-08-09 04:35:01 +000013785 if ((SS.isInvalid() || !SS.isSet()) &&
13786 (FunctionContainingLocalClass =
13787 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
13788 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000013789 // If a friend declaration appears in a local class and the name
13790 // specified is an unqualified name, a prior declaration is
13791 // looked up without considering scopes that are outside the
13792 // innermost enclosing non-class scope. For a friend function
13793 // declaration, if there is no prior declaration, the program is
13794 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000013795
13796 // Find the innermost enclosing non-class scope. This is the block
13797 // scope containing the local class definition (or for a nested class,
13798 // the outer local class).
13799 DCScope = S->getFnParent();
13800
13801 // Look up the function name in the scope.
13802 Previous.clear(LookupLocalFriendName);
13803 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
13804
13805 if (!Previous.empty()) {
13806 // All possible previous declarations must have the same context:
13807 // either they were declared at block scope or they are members of
13808 // one of the enclosing local classes.
13809 DC = Previous.getRepresentativeDecl()->getDeclContext();
13810 } else {
13811 // This is ill-formed, but provide the context that we would have
13812 // declared the function in, if we were permitted to, for error recovery.
13813 DC = FunctionContainingLocalClass;
13814 }
Richard Smith541b38b2013-09-20 01:15:31 +000013815 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000013816
13817 // C++ [class.friend]p6:
13818 // A function can be defined in a friend declaration of a class if and
13819 // only if the class is a non-local class (9.8), the function name is
13820 // unqualified, and the function has namespace scope.
13821 if (D.isFunctionDefinition()) {
13822 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
13823 }
13824
13825 // - There's no scope specifier, in which case we just go to the
13826 // appropriate scope and look for a function or function template
13827 // there as appropriate.
13828 } else if (SS.isInvalid() || !SS.isSet()) {
13829 // C++11 [namespace.memdef]p3:
13830 // If the name in a friend declaration is neither qualified nor
13831 // a template-id and the declaration is a function or an
13832 // elaborated-type-specifier, the lookup to determine whether
13833 // the entity has been previously declared shall not consider
13834 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000013835 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000013836
John McCallf7cfb222010-10-13 05:45:15 +000013837 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000013838 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000013839
Rafael Espindola3626b7e2013-04-25 20:12:36 +000013840 // Skip class contexts. If someone can cite chapter and verse
13841 // for this behavior, that would be nice --- it's what GCC and
13842 // EDG do, and it seems like a reasonable intent, but the spec
13843 // really only says that checks for unqualified existing
13844 // declarations should stop at the nearest enclosing namespace,
13845 // not that they should only consider the nearest enclosing
13846 // namespace.
13847 while (DC->isRecord())
13848 DC = DC->getParent();
13849
13850 DeclContext *LookupDC = DC;
13851 while (LookupDC->isTransparentContext())
13852 LookupDC = LookupDC->getParent();
13853
13854 while (true) {
13855 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000013856
Rafael Espindola3626b7e2013-04-25 20:12:36 +000013857 if (!Previous.empty()) {
13858 DC = LookupDC;
13859 break;
John McCallf4776592010-10-14 22:22:28 +000013860 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000013861
13862 if (isTemplateId) {
13863 if (isa<TranslationUnitDecl>(LookupDC)) break;
13864 } else {
13865 if (LookupDC->isFileContext()) break;
13866 }
13867 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000013868 }
13869
John McCallccbc0322010-10-13 06:22:15 +000013870 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000013871
John McCallde3fd222010-10-12 23:13:28 +000013872 // - There's a non-dependent scope specifier, in which case we
13873 // compute it and do a previous lookup there for a function
13874 // or function template.
13875 } else if (!SS.getScopeRep()->isDependent()) {
13876 DC = computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +000013877 if (!DC) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000013878
Craig Topperc3ec1492014-05-26 06:22:03 +000013879 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000013880
13881 LookupQualifiedName(Previous, DC);
13882
13883 // Ignore things found implicitly in the wrong scope.
13884 // TODO: better diagnostics for this case. Suggesting the right
13885 // qualified scope would be nice...
13886 LookupResult::Filter F = Previous.makeFilter();
13887 while (F.hasNext()) {
13888 NamedDecl *D = F.next();
13889 if (!DC->InEnclosingNamespaceSetOf(
13890 D->getDeclContext()->getRedeclContext()))
13891 F.erase();
13892 }
13893 F.done();
13894
13895 if (Previous.empty()) {
13896 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013897 Diag(Loc, diag::err_qualified_friend_not_found)
13898 << Name << TInfo->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +000013899 return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000013900 }
13901
13902 // C++ [class.friend]p1: A friend of a class is a function or
13903 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000013904 if (DC->Equals(CurContext))
13905 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013906 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000013907 diag::warn_cxx98_compat_friend_is_member :
13908 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000013909
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013910 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000013911 // C++ [class.friend]p6:
13912 // A function can be defined in a friend declaration of a class if and
13913 // only if the class is a non-local class (9.8), the function name is
13914 // unqualified, and the function has namespace scope.
13915 SemaDiagnosticBuilder DB
13916 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
13917
13918 DB << SS.getScopeRep();
13919 if (DC->isFileContext())
13920 DB << FixItHint::CreateRemoval(SS.getRange());
13921 SS.clear();
13922 }
John McCallde3fd222010-10-12 23:13:28 +000013923
13924 // - There's a scope specifier that does not match any template
13925 // parameter lists, in which case we use some arbitrary context,
13926 // create a method or method template, and wait for instantiation.
13927 // - There's a scope specifier that does match some template
13928 // parameter lists, which we don't handle right now.
13929 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013930 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000013931 // C++ [class.friend]p6:
13932 // A function can be defined in a friend declaration of a class if and
13933 // only if the class is a non-local class (9.8), the function name is
13934 // unqualified, and the function has namespace scope.
13935 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
13936 << SS.getScopeRep();
13937 }
13938
John McCallde3fd222010-10-12 23:13:28 +000013939 DC = CurContext;
13940 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000013941 }
David Majnemere14d5302015-09-30 22:07:43 +000013942
John McCallf7cfb222010-10-13 05:45:15 +000013943 if (!DC->isRecord()) {
David Majnemere14d5302015-09-30 22:07:43 +000013944 int DiagArg = -1;
13945 switch (D.getName().getKind()) {
13946 case UnqualifiedId::IK_ConstructorTemplateId:
13947 case UnqualifiedId::IK_ConstructorName:
13948 DiagArg = 0;
13949 break;
13950 case UnqualifiedId::IK_DestructorName:
13951 DiagArg = 1;
13952 break;
13953 case UnqualifiedId::IK_ConversionFunctionId:
13954 DiagArg = 2;
13955 break;
Richard Smith35845152017-02-07 01:37:30 +000013956 case UnqualifiedId::IK_DeductionGuideName:
13957 DiagArg = 3;
13958 break;
David Majnemere14d5302015-09-30 22:07:43 +000013959 case UnqualifiedId::IK_Identifier:
13960 case UnqualifiedId::IK_ImplicitSelfParam:
13961 case UnqualifiedId::IK_LiteralOperatorId:
13962 case UnqualifiedId::IK_OperatorFunctionId:
13963 case UnqualifiedId::IK_TemplateId:
13964 break;
David Majnemere14d5302015-09-30 22:07:43 +000013965 }
John McCall07e91c02009-08-06 02:15:43 +000013966 // This implies that it has to be an operator or function.
David Majnemere14d5302015-09-30 22:07:43 +000013967 if (DiagArg >= 0) {
13968 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
Craig Topperc3ec1492014-05-26 06:22:03 +000013969 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000013970 }
John McCall07e91c02009-08-06 02:15:43 +000013971 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013972
Douglas Gregordd847ba2011-11-03 16:37:14 +000013973 // FIXME: This is an egregious hack to cope with cases where the scope stack
13974 // does not contain the declaration context, i.e., in an out-of-line
13975 // definition of a class.
13976 Scope FakeDCScope(S, Scope::DeclScope, Diags);
13977 if (!DCScope) {
13978 FakeDCScope.setEntity(DC);
13979 DCScope = &FakeDCScope;
13980 }
Richard Smith114394f2013-08-09 04:35:01 +000013981
Francois Pichet00c7e6c2011-08-14 03:52:19 +000013982 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013983 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000013984 TemplateParams, AddToScope);
Craig Topperc3ec1492014-05-26 06:22:03 +000013985 if (!ND) return nullptr;
John McCall759e32b2009-08-31 22:39:49 +000013986
Douglas Gregora29a3ff2009-09-28 00:08:27 +000013987 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000013988
Richard Smith114394f2013-08-09 04:35:01 +000013989 // If we performed typo correction, we might have added a scope specifier
13990 // and changed the decl context.
13991 DC = ND->getDeclContext();
13992
John McCall759e32b2009-08-31 22:39:49 +000013993 // Add the function declaration to the appropriate lookup tables,
13994 // adjusting the redeclarations list as necessary. We don't
13995 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000013996 //
John McCall759e32b2009-08-31 22:39:49 +000013997 // Also update the scope-based lookup if the target context's
13998 // lookup context is in lexical scope.
13999 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000014000 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000014001 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000014002 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000014003 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000014004 }
John McCallaa74a0c2009-08-28 07:59:38 +000014005
14006 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000014007 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000014008 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000014009 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000014010 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000014011
John McCalla0a96892012-08-10 03:15:35 +000014012 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000014013 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000014014 } else {
14015 if (DC->isRecord()) CheckFriendAccess(ND);
14016
John McCall2c2eb122010-10-16 06:59:13 +000014017 FunctionDecl *FD;
14018 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
14019 FD = FTD->getTemplatedDecl();
14020 else
14021 FD = cast<FunctionDecl>(ND);
14022
David Majnemer502b0ed2013-06-25 23:09:30 +000014023 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
14024 // default argument expression, that declaration shall be a definition
14025 // and shall be the only declaration of the function or function
14026 // template in the translation unit.
14027 if (functionDeclHasDefaultArgument(FD)) {
Serge Pavlov06b7a872016-10-04 10:11:43 +000014028 // We can't look at FD->getPreviousDecl() because it may not have been set
Richard Smithfdf08882016-10-21 03:15:03 +000014029 // if we're in a dependent context. If the function is known to be a
14030 // redeclaration, we will have narrowed Previous down to the right decl.
14031 if (D.isRedeclaration()) {
David Majnemer502b0ed2013-06-25 23:09:30 +000014032 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
Serge Pavlov06b7a872016-10-04 10:11:43 +000014033 Diag(Previous.getRepresentativeDecl()->getLocation(),
14034 diag::note_previous_declaration);
David Majnemer502b0ed2013-06-25 23:09:30 +000014035 } else if (!D.isFunctionDefinition())
14036 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
14037 }
14038
John McCall2c2eb122010-10-16 06:59:13 +000014039 // Mark templated-scope function declarations as unsupported.
Richard Smith04b35e92014-09-29 05:57:29 +000014040 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
14041 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
14042 << SS.getScopeRep() << SS.getRange()
14043 << cast<CXXRecordDecl>(CurContext);
John McCall2c2eb122010-10-16 06:59:13 +000014044 FrD->setUnsupportedFriend(true);
Richard Smith04b35e92014-09-29 05:57:29 +000014045 }
John McCall2c2eb122010-10-16 06:59:13 +000014046 }
John McCallde3fd222010-10-12 23:13:28 +000014047
John McCall48871652010-08-21 09:40:31 +000014048 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000014049}
14050
John McCall48871652010-08-21 09:40:31 +000014051void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
14052 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000014053
Aaron Ballmanf96361e2013-01-16 23:39:10 +000014054 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000014055 if (!Fn) {
14056 Diag(DelLoc, diag::err_deleted_non_function);
14057 return;
14058 }
Richard Smithb4d2a152013-04-02 19:38:47 +000014059
Douglas Gregorec9fd132012-01-14 16:38:05 +000014060 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000014061 // Don't consider the implicit declaration we generate for explicit
14062 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000014063 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
14064 Prev->getPreviousDecl()) &&
14065 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000014066 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000014067 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
14068 Prev->isImplicit() ? diag::note_previous_implicit_declaration
14069 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000014070 }
Sebastian Redlf769df52009-03-24 22:27:57 +000014071 // If the declaration wasn't the first, we delete the function anyway for
14072 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000014073 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000014074 }
Richard Smithb4d2a152013-04-02 19:38:47 +000014075
Nico Rieck9de0a572014-05-29 16:51:19 +000014076 // dllimport/dllexport cannot be deleted.
14077 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
14078 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
14079 Fn->setInvalidDecl();
14080 }
14081
Richard Smithb4d2a152013-04-02 19:38:47 +000014082 if (Fn->isDeleted())
14083 return;
14084
14085 // See if we're deleting a function which is already known to override a
14086 // non-deleted virtual function.
Richard Smithf3cec652016-10-31 18:18:29 +000014087 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
Richard Smithb4d2a152013-04-02 19:38:47 +000014088 bool IssuedDiagnostic = false;
14089 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
14090 E = MD->end_overridden_methods();
14091 I != E; ++I) {
14092 if (!(*MD->begin_overridden_methods())->isDeleted()) {
14093 if (!IssuedDiagnostic) {
14094 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14095 IssuedDiagnostic = true;
14096 }
14097 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
14098 }
14099 }
Richard Smithf3cec652016-10-31 18:18:29 +000014100 // If this function was implicitly deleted because it was defaulted,
14101 // explain why it was deleted.
14102 if (IssuedDiagnostic && MD->isDefaulted())
14103 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14104 /*Diagnose*/true);
Richard Smithb4d2a152013-04-02 19:38:47 +000014105 }
14106
Richard Smithb63b6ee2014-01-22 01:43:19 +000014107 // C++11 [basic.start.main]p3:
14108 // A program that defines main as deleted [...] is ill-formed.
14109 if (Fn->isMain())
14110 Diag(DelLoc, diag::err_deleted_main);
14111
Eric Fiselier525a3512016-10-31 23:07:15 +000014112 // C++11 [dcl.fct.def.delete]p4:
14113 // A deleted function is implicitly inline.
14114 Fn->setImplicitlyInline();
Alexis Hunt4a8ea102011-05-06 20:44:56 +000014115 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000014116}
Sebastian Redl4c018662009-04-27 21:33:24 +000014117
Alexis Hunt5a7fa252011-05-12 06:15:49 +000014118void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000014119 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000014120
14121 if (MD) {
Richard Trieu3d1235a2016-09-27 23:44:07 +000014122 if (MD->getParent()->isDependentType()) {
14123 MD->setDefaulted();
14124 MD->setExplicitlyDefaulted();
14125 return;
14126 }
14127
Alexis Hunt5a7fa252011-05-12 06:15:49 +000014128 CXXSpecialMember Member = getSpecialMember(MD);
14129 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000014130 if (!MD->isInvalidDecl())
14131 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000014132 return;
14133 }
14134
14135 MD->setDefaulted();
14136 MD->setExplicitlyDefaulted();
14137
Alexis Hunt61ae8d32011-05-23 23:14:04 +000014138 // If this definition appears within the record, do the checking when
14139 // the record is complete.
14140 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000014141 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Vassil Vassilev8ffe3be2016-05-24 12:10:36 +000014142 // Ask the template instantiation pattern that actually had the
14143 // '= default' on it.
14144 Primary = Pattern;
Alexis Hunt61ae8d32011-05-23 23:14:04 +000014145
Richard Smith3901dfe2013-03-27 00:22:47 +000014146 // If the method was defaulted on its first declaration, we will have
14147 // already performed the checking in CheckCompletedCXXClass. Such a
14148 // declaration doesn't trigger an implicit definition.
Vassil Vassilev8ffe3be2016-05-24 12:10:36 +000014149 if (Primary->getCanonicalDecl()->isDefaulted())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000014150 return;
14151
Richard Smithd3b5c9082012-07-27 04:22:15 +000014152 CheckExplicitlyDefaultedSpecialMember(MD);
14153
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +000014154 if (!MD->isInvalidDecl())
14155 DefineImplicitSpecialMember(*this, MD, DefaultLoc);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000014156 } else {
14157 Diag(DefaultLoc, diag::err_default_special_members);
14158 }
14159}
14160
Sebastian Redl4c018662009-04-27 21:33:24 +000014161static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
Benjamin Kramer642f1732015-07-02 21:03:14 +000014162 for (Stmt *SubStmt : S->children()) {
Sebastian Redl4c018662009-04-27 21:33:24 +000014163 if (!SubStmt)
14164 continue;
14165 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000014166 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000014167 diag::err_return_in_constructor_handler);
14168 if (!isa<Expr>(SubStmt))
14169 SearchForReturnInStmt(Self, SubStmt);
14170 }
14171}
14172
14173void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14174 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14175 CXXCatchStmt *Handler = TryBlock->getHandler(I);
14176 SearchForReturnInStmt(*this, Handler);
14177 }
14178}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000014179
David Blaikie68f71a32013-01-18 23:03:15 +000014180bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000014181 const CXXMethodDecl *Old) {
14182 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
14183 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
14184
14185 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14186
14187 // If the calling conventions match, everything is fine
14188 if (NewCC == OldCC)
14189 return false;
14190
Hans Wennborg2545efe2013-12-11 17:42:11 +000014191 // If the calling conventions mismatch because the new function is static,
14192 // suppress the calling convention mismatch error; the error about static
14193 // function override (err_static_overrides_virtual from
14194 // Sema::CheckFunctionDeclaration) is more clear.
14195 if (New->getStorageClass() == SC_Static)
14196 return false;
14197
Reid Kleckner78af0702013-08-27 23:08:25 +000014198 Diag(New->getLocation(),
14199 diag::err_conflicting_overriding_cc_attributes)
14200 << New->getDeclName() << New->getType() << Old->getType();
14201 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14202 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000014203}
14204
Mike Stump11289f42009-09-09 15:08:12 +000014205bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000014206 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000014207 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14208 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000014209
Chandler Carruth284bb2e2010-02-15 11:53:20 +000014210 if (Context.hasSameType(NewTy, OldTy) ||
14211 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000014212 return false;
Mike Stump11289f42009-09-09 15:08:12 +000014213
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014214 // Check if the return types are covariant
14215 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000014216
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014217 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000014218 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14219 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014220 NewClassTy = NewPT->getPointeeType();
14221 OldClassTy = OldPT->getPointeeType();
14222 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000014223 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14224 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14225 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14226 NewClassTy = NewRT->getPointeeType();
14227 OldClassTy = OldRT->getPointeeType();
14228 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014229 }
14230 }
Mike Stump11289f42009-09-09 15:08:12 +000014231
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014232 // The return types aren't either both pointers or references to a class type.
14233 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000014234 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014235 diag::err_different_return_type_for_overriding_virtual_function)
Alp Tokerd0787eb2014-07-02 01:47:15 +000014236 << New->getDeclName() << NewTy << OldTy
14237 << New->getReturnTypeSourceRange();
14238 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14239 << Old->getReturnTypeSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000014240
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014241 return true;
14242 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000014243
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000014244 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
David Majnemerd3d91bd2016-01-26 01:37:01 +000014245 // C++14 [class.virtual]p8:
14246 // If the class type in the covariant return type of D::f differs from
14247 // that of B::f, the class type in the return type of D::f shall be
14248 // complete at the point of declaration of D::f or shall be the class
14249 // type D.
14250 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14251 if (!RT->isBeingDefined() &&
14252 RequireCompleteType(New->getLocation(), NewClassTy,
14253 diag::err_covariant_return_incomplete,
14254 New->getDeclName()))
14255 return true;
14256 }
14257
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014258 // Check if the new class derives from the old class.
Richard Smith0f59cb32015-12-18 21:45:41 +000014259 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
Alp Tokerd0787eb2014-07-02 01:47:15 +000014260 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14261 << New->getDeclName() << NewTy << OldTy
14262 << New->getReturnTypeSourceRange();
14263 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14264 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014265 return true;
14266 }
Mike Stump11289f42009-09-09 15:08:12 +000014267
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014268 // Check if we the conversion from derived to base is valid.
Alp Tokerd0787eb2014-07-02 01:47:15 +000014269 if (CheckDerivedToBaseConversion(
14270 NewClassTy, OldClassTy,
14271 diag::err_covariant_return_inaccessible_base,
14272 diag::err_covariant_return_ambiguous_derived_to_base_conv,
14273 New->getLocation(), New->getReturnTypeSourceRange(),
14274 New->getDeclName(), nullptr)) {
John McCallc1465822011-02-14 07:13:47 +000014275 // FIXME: this note won't trigger for delayed access control
14276 // diagnostics, and it's impossible to get an undelayed error
14277 // here from access control during the original parse because
14278 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Alp Tokerd0787eb2014-07-02 01:47:15 +000014279 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14280 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014281 return true;
14282 }
14283 }
Mike Stump11289f42009-09-09 15:08:12 +000014284
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014285 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000014286 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014287 Diag(New->getLocation(),
14288 diag::err_covariant_return_type_different_qualifications)
Alp Tokerd0787eb2014-07-02 01:47:15 +000014289 << New->getDeclName() << NewTy << OldTy
14290 << New->getReturnTypeSourceRange();
14291 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14292 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014293 return true;
David Majnemerfedb8d42016-01-26 01:39:17 +000014294 }
Mike Stump11289f42009-09-09 15:08:12 +000014295
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014296
14297 // The new class type must have the same or less qualifiers as the old type.
14298 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14299 Diag(New->getLocation(),
14300 diag::err_covariant_return_type_class_type_more_qualified)
Alp Tokerd0787eb2014-07-02 01:47:15 +000014301 << New->getDeclName() << NewTy << OldTy
14302 << New->getReturnTypeSourceRange();
14303 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14304 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014305 return true;
David Majnemerfedb8d42016-01-26 01:39:17 +000014306 }
Mike Stump11289f42009-09-09 15:08:12 +000014307
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014308 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000014309}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014310
Douglas Gregor21920e372009-12-01 17:24:26 +000014311/// \brief Mark the given method pure.
14312///
14313/// \param Method the method to be marked pure.
14314///
14315/// \param InitRange the source range that covers the "0" initializer.
14316bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000014317 SourceLocation EndLoc = InitRange.getEnd();
14318 if (EndLoc.isValid())
14319 Method->setRangeEnd(EndLoc);
14320
Douglas Gregor21920e372009-12-01 17:24:26 +000014321 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14322 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000014323 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000014324 }
Douglas Gregor21920e372009-12-01 17:24:26 +000014325
14326 if (!Method->isInvalidDecl())
14327 Diag(Method->getLocation(), diag::err_non_virtual_pure)
14328 << Method->getDeclName() << InitRange;
14329 return true;
14330}
14331
Richard Smith9ba0fec2015-06-30 01:28:56 +000014332void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14333 if (D->getFriendObjectKind())
14334 Diag(D->getLocation(), diag::err_pure_friend);
14335 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14336 CheckPureMethod(M, ZeroLoc);
14337 else
14338 Diag(D->getLocation(), diag::err_illegal_initializer);
14339}
14340
Douglas Gregor926410d2012-02-21 02:22:07 +000014341/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014342static bool isStaticDataMember(const Decl *D) {
14343 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14344 return Var->isStaticDataMember();
14345
14346 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000014347}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014348
John McCall1f4ee7b2009-12-19 09:28:58 +000014349/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
14350/// an initializer for the out-of-line declaration 'Dcl'. The scope
14351/// is a fresh scope pushed for just this purpose.
14352///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014353/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14354/// static data member of class X, names should be looked up in the scope of
14355/// class X.
John McCall48871652010-08-21 09:40:31 +000014356void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014357 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000014358 if (!D || D->isInvalidDecl())
14359 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014360
Richard Smitha2302242013-12-05 07:51:02 +000014361 // We will always have a nested name specifier here, but this declaration
14362 // might not be out of line if the specifier names the current namespace:
14363 // extern int n;
14364 // int ::n = 0;
14365 if (D->isOutOfLine())
14366 EnterDeclaratorContext(S, D->getDeclContext());
14367
Douglas Gregor926410d2012-02-21 02:22:07 +000014368 // If we are parsing the initializer for a static data member, push a
14369 // new expression evaluation context that is associated with this static
14370 // data member.
14371 if (isStaticDataMember(D))
14372 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014373}
14374
14375/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000014376/// initializer for the out-of-line declaration 'D'.
14377void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014378 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000014379 if (!D || D->isInvalidDecl())
14380 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014381
Douglas Gregor926410d2012-02-21 02:22:07 +000014382 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000014383 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000014384
Richard Smitha2302242013-12-05 07:51:02 +000014385 if (D->isOutOfLine())
14386 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014387}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014388
14389/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14390/// C++ if/switch/while/for statement.
14391/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000014392DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014393 // C++ 6.4p2:
14394 // The declarator shall not specify a function or an array.
14395 // The type-specifier-seq shall not contain typedef and shall not declare a
14396 // new class or enumeration.
14397 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14398 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000014399
14400 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000014401 if (!Dcl)
14402 return true;
14403
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000014404 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14405 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014406 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000014407 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014408 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014409
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014410 return Dcl;
14411}
Anders Carlssonf98849e2009-12-02 17:15:43 +000014412
Douglas Gregor4daf6a32011-07-28 19:11:31 +000014413void Sema::LoadExternalVTableUses() {
14414 if (!ExternalSource)
14415 return;
14416
14417 SmallVector<ExternalVTableUse, 4> VTables;
14418 ExternalSource->ReadUsedVTables(VTables);
14419 SmallVector<VTableUse, 4> NewUses;
14420 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14421 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14422 = VTablesUsed.find(VTables[I].Record);
14423 // Even if a definition wasn't required before, it may be required now.
14424 if (Pos != VTablesUsed.end()) {
14425 if (!Pos->second && VTables[I].DefinitionRequired)
14426 Pos->second = true;
14427 continue;
14428 }
14429
14430 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14431 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14432 }
14433
14434 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14435}
14436
Douglas Gregor88d292c2010-05-13 16:44:06 +000014437void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
14438 bool DefinitionRequired) {
14439 // Ignore any vtable uses in unevaluated operands or for classes that do
14440 // not have a vtable.
14441 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000014442 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000014443 return;
14444
Douglas Gregor88d292c2010-05-13 16:44:06 +000014445 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000014446 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014447 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
14448 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
14449 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
14450 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000014451 // If we already had an entry, check to see if we are promoting this vtable
Nico Weberf1cebf02015-01-06 23:54:59 +000014452 // to require a definition. If so, we need to reappend to the VTableUses
Daniel Dunbar53217762010-05-25 00:33:13 +000014453 // list, since we may have already processed the first entry.
14454 if (DefinitionRequired && !Pos.first->second) {
14455 Pos.first->second = true;
14456 } else {
14457 // Otherwise, we can early exit.
14458 return;
14459 }
Hans Wennborg3d791542014-02-24 15:58:24 +000014460 } else {
14461 // The Microsoft ABI requires that we perform the destructor body
14462 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
14463 // the deleting destructor is emitted with the vtable, not with the
14464 // destructor definition as in the Itanium ABI.
Hans Wennborg34804352016-04-13 20:21:15 +000014465 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Reid Klecknerad1e22b2016-06-29 18:29:21 +000014466 CXXDestructorDecl *DD = Class->getDestructor();
14467 if (DD && DD->isVirtual() && !DD->isDeleted()) {
14468 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
14469 // If this is an out-of-line declaration, marking it referenced will
14470 // not do anything. Manually call CheckDestructor to look up operator
14471 // delete().
14472 ContextRAII SavedContext(*this, DD);
14473 CheckDestructor(DD);
14474 } else {
14475 MarkFunctionReferenced(Loc, Class->getDestructor());
14476 }
Hans Wennborg34804352016-04-13 20:21:15 +000014477 }
Hans Wennborg3d791542014-02-24 15:58:24 +000014478 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000014479 }
14480
14481 // Local classes need to have their virtual members marked
14482 // immediately. For all other classes, we mark their virtual members
14483 // at the end of the translation unit.
14484 if (Class->isLocalClass())
14485 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000014486 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000014487 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000014488}
14489
Douglas Gregor88d292c2010-05-13 16:44:06 +000014490bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000014491 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014492 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000014493 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000014494
Douglas Gregor88d292c2010-05-13 16:44:06 +000014495 // Note: The VTableUses vector could grow as a result of marking
14496 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000014497 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000014498 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000014499 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014500 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000014501 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014502 if (!Class)
14503 continue;
Reid Klecknerb792e062016-12-06 21:44:41 +000014504 TemplateSpecializationKind ClassTSK =
14505 Class->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014506
14507 SourceLocation Loc = VTableUses[I].second;
14508
Richard Smithd3b5c9082012-07-27 04:22:15 +000014509 bool DefineVTable = true;
14510
Douglas Gregor88d292c2010-05-13 16:44:06 +000014511 // If this class has a key function, but that key function is
14512 // defined in another translation unit, we don't need to emit the
14513 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000014514 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000014515 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000014516 // The key function is in another translation unit.
14517 DefineVTable = false;
14518 TemplateSpecializationKind TSK =
14519 KeyFunction->getTemplateSpecializationKind();
14520 assert(TSK != TSK_ExplicitInstantiationDefinition &&
14521 TSK != TSK_ImplicitInstantiation &&
14522 "Instantiations don't have key functions");
14523 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014524 } else if (!KeyFunction) {
14525 // If we have a class with no key function that is the subject
14526 // of an explicit instantiation declaration, suppress the
14527 // vtable; it will live with the explicit instantiation
14528 // definition.
Reid Klecknerb792e062016-12-06 21:44:41 +000014529 bool IsExplicitInstantiationDeclaration =
14530 ClassTSK == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000014531 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000014532 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000014533 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014534 if (TSK == TSK_ExplicitInstantiationDeclaration)
14535 IsExplicitInstantiationDeclaration = true;
14536 else if (TSK == TSK_ExplicitInstantiationDefinition) {
14537 IsExplicitInstantiationDeclaration = false;
14538 break;
14539 }
14540 }
14541
14542 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000014543 DefineVTable = false;
14544 }
14545
14546 // The exception specifications for all virtual members may be needed even
14547 // if we are not providing an authoritative form of the vtable in this TU.
14548 // We may choose to emit it available_externally anyway.
14549 if (!DefineVTable) {
14550 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
14551 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014552 }
14553
14554 // Mark all of the virtual members of this class as referenced, so
14555 // that we can build a vtable. Then, tell the AST consumer that a
14556 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000014557 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014558 MarkVirtualMembersReferenced(Loc, Class);
14559 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
Nico Weberb6a5d052015-01-15 04:07:35 +000014560 if (VTablesUsed[Canonical])
14561 Consumer.HandleVTable(Class);
Douglas Gregor88d292c2010-05-13 16:44:06 +000014562
Reid Klecknerb792e062016-12-06 21:44:41 +000014563 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
14564 // no key function or the key function is inlined. Don't warn in C++ ABIs
14565 // that lack key functions, since the user won't be able to make one.
14566 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
14567 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +000014568 const FunctionDecl *KeyFunctionDef = nullptr;
Reid Klecknerb792e062016-12-06 21:44:41 +000014569 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
14570 KeyFunctionDef->isInlined())) {
14571 Diag(Class->getLocation(),
14572 ClassTSK == TSK_ExplicitInstantiationDefinition
14573 ? diag::warn_weak_template_vtable
14574 : diag::warn_weak_vtable)
14575 << Class;
14576 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000014577 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000014578 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000014579 VTableUses.clear();
14580
Douglas Gregor97509692011-04-22 22:25:37 +000014581 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000014582}
Anders Carlsson82fccd02009-12-07 08:24:59 +000014583
Richard Smithd3b5c9082012-07-27 04:22:15 +000014584void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
14585 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000014586 for (const auto *I : RD->methods())
14587 if (I->isVirtual() && !I->isPure())
14588 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000014589}
14590
Rafael Espindola5b334082010-03-26 00:36:59 +000014591void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
14592 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000014593 // Mark all functions which will appear in RD's vtable as used.
14594 CXXFinalOverriderMap FinalOverriders;
14595 RD->getFinalOverriders(FinalOverriders);
14596 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
14597 E = FinalOverriders.end();
14598 I != E; ++I) {
14599 for (OverridingMethods::const_iterator OI = I->second.begin(),
14600 OE = I->second.end();
14601 OI != OE; ++OI) {
14602 assert(OI->second.size() > 0 && "no final overrider");
14603 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000014604
Richard Smith4ff9ff92012-07-07 06:59:51 +000014605 // C++ [basic.def.odr]p2:
14606 // [...] A virtual member function is used if it is not pure. [...]
14607 if (!Overrider->isPure())
14608 MarkFunctionReferenced(Loc, Overrider);
14609 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000014610 }
Rafael Espindola5b334082010-03-26 00:36:59 +000014611
14612 // Only classes that have virtual bases need a VTT.
14613 if (RD->getNumVBases() == 0)
14614 return;
14615
Aaron Ballman574705e2014-03-13 15:41:46 +000014616 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000014617 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000014618 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000014619 if (Base->getNumVBases() == 0)
14620 continue;
14621 MarkVirtualMembersReferenced(Loc, Base);
14622 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000014623}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014624
14625/// SetIvarInitializers - This routine builds initialization ASTs for the
14626/// Objective-C implementation whose ivars need be initialized.
14627void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000014628 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014629 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000014630 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000014631 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014632 CollectIvarsToConstructOrDestruct(OID, ivars);
14633 if (ivars.empty())
14634 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000014635 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014636 for (unsigned i = 0; i < ivars.size(); i++) {
14637 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000014638 if (Field->isInvalidDecl())
14639 continue;
14640
Alexis Hunt1d792652011-01-08 20:30:50 +000014641 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014642 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
14643 InitializationKind InitKind =
14644 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000014645
14646 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
14647 ExprResult MemberInit =
14648 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000014649 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014650 // Note, MemberInit could actually come back empty if no initialization
14651 // is required (e.g., because it would call a trivial default constructor)
14652 if (!MemberInit.get() || MemberInit.isInvalid())
14653 continue;
John McCallacf0ee52010-10-08 02:01:28 +000014654
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014655 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000014656 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
14657 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014658 MemberInit.getAs<Expr>(),
Alexis Hunt1d792652011-01-08 20:30:50 +000014659 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014660 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000014661
14662 // Be sure that the destructor is accessible and is marked as referenced.
Nico Weberaa0117c2014-11-12 03:44:43 +000014663 if (const RecordType *RecordTy =
14664 Context.getBaseElementType(Field->getType())
14665 ->getAs<RecordType>()) {
14666 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000014667 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000014668 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000014669 CheckDestructorAccess(Field->getLocation(), Destructor,
14670 PDiag(diag::err_access_dtor_ivar)
14671 << Context.getBaseElementType(Field->getType()));
14672 }
14673 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014674 }
14675 ObjCImplementation->setIvarInitializers(Context,
14676 AllToInit.data(), AllToInit.size());
14677 }
14678}
Alexis Hunt6118d662011-05-04 05:57:24 +000014679
Alexis Hunt27a761d2011-05-04 23:29:54 +000014680static
14681void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
14682 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
14683 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
14684 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
14685 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000014686 if (Ctor->isInvalidDecl())
14687 return;
14688
Richard Smith802c4b72012-08-23 06:16:52 +000014689 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
14690
14691 // Target may not be determinable yet, for instance if this is a dependent
14692 // call in an uninstantiated template.
14693 if (Target) {
Craig Topperc3ec1492014-05-26 06:22:03 +000014694 const FunctionDecl *FNTarget = nullptr;
Richard Smith802c4b72012-08-23 06:16:52 +000014695 (void)Target->hasBody(FNTarget);
14696 Target = const_cast<CXXConstructorDecl*>(
14697 cast_or_null<CXXConstructorDecl>(FNTarget));
14698 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000014699
14700 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
14701 // Avoid dereferencing a null pointer here.
Craig Topperc3ec1492014-05-26 06:22:03 +000014702 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000014703
David Blaikie82e95a32014-11-19 07:49:47 +000014704 if (!Current.insert(Canonical).second)
Alexis Hunt27a761d2011-05-04 23:29:54 +000014705 return;
14706
14707 // We know that beyond here, we aren't chaining into a cycle.
14708 if (!Target || !Target->isDelegatingConstructor() ||
14709 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014710 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000014711 Current.clear();
14712 // We've hit a cycle.
14713 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
14714 Current.count(TCanonical)) {
14715 // If we haven't diagnosed this cycle yet, do so now.
14716 if (!Invalid.count(TCanonical)) {
14717 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000014718 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000014719 << Ctor;
14720
Richard Smith802c4b72012-08-23 06:16:52 +000014721 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000014722 if (TCanonical != Canonical)
14723 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
14724
14725 CXXConstructorDecl *C = Target;
14726 while (C->getCanonicalDecl() != Canonical) {
Craig Topperc3ec1492014-05-26 06:22:03 +000014727 const FunctionDecl *FNTarget = nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000014728 (void)C->getTargetConstructor()->hasBody(FNTarget);
14729 assert(FNTarget && "Ctor cycle through bodiless function");
14730
Richard Smith802c4b72012-08-23 06:16:52 +000014731 C = const_cast<CXXConstructorDecl*>(
14732 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000014733 S.Diag(C->getLocation(), diag::note_which_delegates_to);
14734 }
14735 }
14736
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014737 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000014738 Current.clear();
14739 } else {
14740 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
14741 }
14742}
14743
14744
Alexis Hunt6118d662011-05-04 05:57:24 +000014745void Sema::CheckDelegatingCtorCycles() {
14746 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
14747
Douglas Gregorbae31202011-07-27 21:57:17 +000014748 for (DelegatingCtorDeclsType::iterator
14749 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000014750 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000014751 I != E; ++I)
14752 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000014753
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014754 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
14755 CE = Invalid.end();
14756 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000014757 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000014758}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000014759
Douglas Gregor3024f072012-04-16 07:05:22 +000014760namespace {
14761 /// \brief AST visitor that finds references to the 'this' expression.
14762 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
14763 Sema &S;
14764
14765 public:
14766 explicit FindCXXThisExpr(Sema &S) : S(S) { }
14767
14768 bool VisitCXXThisExpr(CXXThisExpr *E) {
14769 S.Diag(E->getLocation(), diag::err_this_static_member_func)
14770 << E->isImplicit();
14771 return false;
14772 }
14773 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000014774}
Douglas Gregor3024f072012-04-16 07:05:22 +000014775
14776bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
14777 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14778 if (!TSInfo)
14779 return false;
14780
14781 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000014782 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000014783 if (!ProtoTL)
14784 return false;
14785
14786 // C++11 [expr.prim.general]p3:
14787 // [The expression this] shall not appear before the optional
14788 // cv-qualifier-seq and it shall not appear within the declaration of a
14789 // static member function (although its type and value category are defined
14790 // within a static member function as they are within a non-static member
14791 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000014792 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000014793 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000014794 FindCXXThisExpr Finder(*this);
14795
14796 // If the return type came after the cv-qualifier-seq, check it now.
14797 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000014798 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000014799 return true;
14800
14801 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000014802 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
14803 return true;
14804
14805 return checkThisInStaticMemberFunctionAttributes(Method);
14806}
14807
14808bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
14809 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14810 if (!TSInfo)
14811 return false;
14812
14813 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000014814 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000014815 if (!ProtoTL)
14816 return false;
14817
David Blaikie6adc78e2013-02-18 22:06:02 +000014818 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000014819 FindCXXThisExpr Finder(*this);
14820
Douglas Gregor3024f072012-04-16 07:05:22 +000014821 switch (Proto->getExceptionSpecType()) {
Richard Smith0b3a4622014-11-13 20:01:57 +000014822 case EST_Unparsed:
Richard Smithf623c962012-04-17 00:58:00 +000014823 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000014824 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000014825 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000014826 case EST_DynamicNone:
14827 case EST_MSAny:
14828 case EST_None:
14829 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000014830
Douglas Gregor3024f072012-04-16 07:05:22 +000014831 case EST_ComputedNoexcept:
14832 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
14833 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000014834
Douglas Gregor3024f072012-04-16 07:05:22 +000014835 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000014836 for (const auto &E : Proto->exceptions()) {
14837 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000014838 return true;
14839 }
14840 break;
14841 }
Douglas Gregor433e0532012-04-16 18:27:27 +000014842
14843 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000014844}
14845
14846bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
14847 FindCXXThisExpr Finder(*this);
14848
14849 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014850 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000014851 // FIXME: This should be emitted by tblgen.
Craig Topperc3ec1492014-05-26 06:22:03 +000014852 Expr *Arg = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +000014853 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014854 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000014855 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014856 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000014857 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014858 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014859 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014860 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014861 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014862 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000014863 Arg = ETLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000014864 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014865 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000014866 Arg = STLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000014867 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
Aaron Ballman18d85ae2014-03-20 16:02:49 +000014868 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000014869 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014870 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014871 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014872 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014873 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014874 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014875 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014876 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014877 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014878 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014879 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000014880
14881 if (Arg && !Finder.TraverseStmt(Arg))
14882 return true;
14883
14884 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
14885 if (!Finder.TraverseStmt(Args[I]))
14886 return true;
14887 }
14888 }
14889
14890 return false;
14891}
14892
Richard Smith2e321552014-11-12 02:00:47 +000014893void Sema::checkExceptionSpecification(
14894 bool IsTopLevel, ExceptionSpecificationType EST,
14895 ArrayRef<ParsedType> DynamicExceptions,
14896 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
14897 SmallVectorImpl<QualType> &Exceptions,
14898 FunctionProtoType::ExceptionSpecInfo &ESI) {
Douglas Gregor433e0532012-04-16 18:27:27 +000014899 Exceptions.clear();
Richard Smith8acb4282014-07-31 21:57:55 +000014900 ESI.Type = EST;
Douglas Gregor433e0532012-04-16 18:27:27 +000014901 if (EST == EST_Dynamic) {
14902 Exceptions.reserve(DynamicExceptions.size());
14903 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
14904 // FIXME: Preserve type source info.
14905 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
14906
Richard Smith2e321552014-11-12 02:00:47 +000014907 if (IsTopLevel) {
14908 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
14909 collectUnexpandedParameterPacks(ET, Unexpanded);
14910 if (!Unexpanded.empty()) {
14911 DiagnoseUnexpandedParameterPacks(
14912 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
14913 Unexpanded);
14914 continue;
14915 }
Douglas Gregor433e0532012-04-16 18:27:27 +000014916 }
14917
14918 // Check that the type is valid for an exception spec, and
14919 // drop it if not.
14920 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
14921 Exceptions.push_back(ET);
14922 }
Richard Smith8acb4282014-07-31 21:57:55 +000014923 ESI.Exceptions = Exceptions;
Douglas Gregor433e0532012-04-16 18:27:27 +000014924 return;
14925 }
Richard Smith8acb4282014-07-31 21:57:55 +000014926
Douglas Gregor433e0532012-04-16 18:27:27 +000014927 if (EST == EST_ComputedNoexcept) {
14928 // If an error occurred, there's no expression here.
14929 if (NoexceptExpr) {
14930 assert((NoexceptExpr->isTypeDependent() ||
14931 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
14932 Context.BoolTy) &&
14933 "Parser should have made sure that the expression is boolean");
Richard Smith2e321552014-11-12 02:00:47 +000014934 if (IsTopLevel && NoexceptExpr &&
14935 DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
Richard Smith8acb4282014-07-31 21:57:55 +000014936 ESI.Type = EST_BasicNoexcept;
Douglas Gregor433e0532012-04-16 18:27:27 +000014937 return;
14938 }
Richard Smith8acb4282014-07-31 21:57:55 +000014939
Douglas Gregor433e0532012-04-16 18:27:27 +000014940 if (!NoexceptExpr->isValueDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +000014941 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
Douglas Gregore2b37442012-05-04 22:38:52 +000014942 diag::err_noexcept_needs_constant_expression,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014943 /*AllowFold*/ false).get();
Richard Smith8acb4282014-07-31 21:57:55 +000014944 ESI.NoexceptExpr = NoexceptExpr;
Douglas Gregor433e0532012-04-16 18:27:27 +000014945 }
14946 return;
14947 }
14948}
14949
Richard Smith0b3a4622014-11-13 20:01:57 +000014950void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
14951 ExceptionSpecificationType EST,
14952 SourceRange SpecificationRange,
14953 ArrayRef<ParsedType> DynamicExceptions,
14954 ArrayRef<SourceRange> DynamicExceptionRanges,
14955 Expr *NoexceptExpr) {
14956 if (!MethodD)
14957 return;
14958
14959 // Dig out the method we're referring to.
14960 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
14961 MethodD = FunTmpl->getTemplatedDecl();
14962
14963 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
14964 if (!Method)
14965 return;
14966
14967 // Check the exception specification.
14968 llvm::SmallVector<QualType, 4> Exceptions;
14969 FunctionProtoType::ExceptionSpecInfo ESI;
14970 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
14971 DynamicExceptionRanges, NoexceptExpr, Exceptions,
14972 ESI);
14973
14974 // Update the exception specification on the function type.
14975 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
14976
14977 if (Method->isStatic())
14978 checkThisInStaticMemberFunctionExceptionSpec(Method);
14979
14980 if (Method->isVirtual()) {
14981 // Check overrides, which we previously had to delay.
14982 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
14983 OEnd = Method->end_overridden_methods();
14984 O != OEnd; ++O)
14985 CheckOverridingFunctionExceptionSpec(Method, *O);
14986 }
14987}
14988
John McCall5e77d762013-04-16 07:28:30 +000014989/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
14990///
14991MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
14992 SourceLocation DeclStart,
14993 Declarator &D, Expr *BitWidth,
14994 InClassInitStyle InitStyle,
14995 AccessSpecifier AS,
14996 AttributeList *MSPropertyAttr) {
14997 IdentifierInfo *II = D.getIdentifier();
14998 if (!II) {
14999 Diag(DeclStart, diag::err_anonymous_property);
Craig Topperc3ec1492014-05-26 06:22:03 +000015000 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +000015001 }
15002 SourceLocation Loc = D.getIdentifierLoc();
15003
15004 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15005 QualType T = TInfo->getType();
15006 if (getLangOpts().CPlusPlus) {
15007 CheckExtraCXXDefaultArguments(D);
15008
15009 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15010 UPPC_DataMemberType)) {
15011 D.setInvalidType();
15012 T = Context.IntTy;
15013 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15014 }
15015 }
15016
15017 DiagnoseFunctionSpecifiers(D.getDeclSpec());
15018
Richard Smith62f19e72016-06-25 00:15:56 +000015019 if (D.getDeclSpec().isInlineSpecified())
15020 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15021 << getLangOpts().CPlusPlus1z;
John McCall5e77d762013-04-16 07:28:30 +000015022 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15023 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15024 diag::err_invalid_thread)
15025 << DeclSpec::getSpecifierName(TSCS);
15026
15027 // Check to see if this name was declared as a member previously
Craig Topperc3ec1492014-05-26 06:22:03 +000015028 NamedDecl *PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000015029 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
15030 LookupName(Previous, S);
15031 switch (Previous.getResultKind()) {
15032 case LookupResult::Found:
15033 case LookupResult::FoundUnresolvedValue:
15034 PrevDecl = Previous.getAsSingle<NamedDecl>();
15035 break;
15036
15037 case LookupResult::FoundOverloaded:
15038 PrevDecl = Previous.getRepresentativeDecl();
15039 break;
15040
15041 case LookupResult::NotFound:
15042 case LookupResult::NotFoundInCurrentInstantiation:
15043 case LookupResult::Ambiguous:
15044 break;
15045 }
15046
15047 if (PrevDecl && PrevDecl->isTemplateParameter()) {
15048 // Maybe we will complain about the shadowed template parameter.
15049 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15050 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000015051 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000015052 }
15053
15054 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Craig Topperc3ec1492014-05-26 06:22:03 +000015055 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000015056
15057 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000015058 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000015059 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
15060 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000015061 ProcessDeclAttributes(TUScope, NewPD, D);
15062 NewPD->setAccess(AS);
15063
15064 if (NewPD->isInvalidDecl())
15065 Record->setInvalidDecl();
15066
15067 if (D.getDeclSpec().isModulePrivateSpecified())
15068 NewPD->setModulePrivate();
15069
15070 if (NewPD->isInvalidDecl() && PrevDecl) {
15071 // Don't introduce NewFD into scope; there's already something
15072 // with the same name in the same scope.
15073 } else if (II) {
15074 PushOnScopeChains(NewPD, S);
15075 } else
15076 Record->addDecl(NewPD);
15077
15078 return NewPD;
15079}