blob: 21bdd945f06c509ee587210911f92b5557f30164 [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
David Majnemer502b0ed2013-06-25 23:09:30 +0000650 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumi3e7db842013-07-17 17:57:52 +0000651 // argument expression, that declaration shall be a definition and shall be
David Majnemer502b0ed2013-06-25 23:09:30 +0000652 // the only declaration of the function or function template in the
653 // translation unit.
654 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
655 functionDeclHasDefaultArgument(Old)) {
656 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
657 Diag(Old->getLocation(), diag::note_previous_declaration);
658 Invalid = true;
659 }
660
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000661 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000662}
663
Richard Smith7873de02016-08-11 22:25:46 +0000664NamedDecl *
665Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
666 MultiTemplateParamsArg TemplateParamLists) {
667 assert(D.isDecompositionDeclarator());
668 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
669
670 // The syntax only allows a decomposition declarator as a simple-declaration
671 // or a for-range-declaration, but we parse it in more cases than that.
672 if (!D.mayHaveDecompositionDeclarator()) {
673 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
674 << Decomp.getSourceRange();
675 return nullptr;
676 }
677
678 if (!TemplateParamLists.empty()) {
679 // FIXME: There's no rule against this, but there are also no rules that
680 // would actually make it usable, so we reject it for now.
681 Diag(TemplateParamLists.front()->getTemplateLoc(),
682 diag::err_decomp_decl_template);
683 return nullptr;
684 }
685
686 Diag(Decomp.getLSquareLoc(), getLangOpts().CPlusPlus1z
687 ? diag::warn_cxx14_compat_decomp_decl
688 : diag::ext_decomp_decl)
689 << Decomp.getSourceRange();
690
691 // The semantic context is always just the current context.
692 DeclContext *const DC = CurContext;
693
694 // C++1z [dcl.dcl]/8:
695 // The decl-specifier-seq shall contain only the type-specifier auto
696 // and cv-qualifiers.
697 auto &DS = D.getDeclSpec();
698 {
699 SmallVector<StringRef, 8> BadSpecifiers;
700 SmallVector<SourceLocation, 8> BadSpecifierLocs;
701 if (auto SCS = DS.getStorageClassSpec()) {
702 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
703 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
704 }
705 if (auto TSCS = DS.getThreadStorageClassSpec()) {
706 BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
707 BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
708 }
709 if (DS.isConstexprSpecified()) {
710 BadSpecifiers.push_back("constexpr");
711 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
712 }
713 if (DS.isInlineSpecified()) {
714 BadSpecifiers.push_back("inline");
715 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
716 }
717 if (!BadSpecifiers.empty()) {
718 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
719 Err << (int)BadSpecifiers.size()
720 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
721 // Don't add FixItHints to remove the specifiers; we do still respect
722 // them when building the underlying variable.
723 for (auto Loc : BadSpecifierLocs)
724 Err << SourceRange(Loc, Loc);
725 }
726 // We can't recover from it being declared as a typedef.
727 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
728 return nullptr;
729 }
730
731 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
732 QualType R = TInfo->getType();
733
734 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
735 UPPC_DeclarationType))
736 D.setInvalidType();
737
738 // The syntax only allows a single ref-qualifier prior to the decomposition
739 // declarator. No other declarator chunks are permitted. Also check the type
740 // specifier here.
741 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
742 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
743 (D.getNumTypeObjects() == 1 &&
744 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
745 Diag(Decomp.getLSquareLoc(),
746 (D.hasGroupingParens() ||
747 (D.getNumTypeObjects() &&
748 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
749 ? diag::err_decomp_decl_parens
750 : diag::err_decomp_decl_type)
751 << R;
752
753 // In most cases, there's no actual problem with an explicitly-specified
754 // type, but a function type won't work here, and ActOnVariableDeclarator
755 // shouldn't be called for such a type.
756 if (R->isFunctionType())
757 D.setInvalidType();
758 }
759
760 // Build the BindingDecls.
761 SmallVector<BindingDecl*, 8> Bindings;
762
763 // Build the BindingDecls.
764 for (auto &B : D.getDecompositionDeclarator().bindings()) {
765 // Check for name conflicts.
766 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
767 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
768 ForRedeclaration);
769 LookupName(Previous, S,
770 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
771
772 // It's not permitted to shadow a template parameter name.
773 if (Previous.isSingleResult() &&
774 Previous.getFoundDecl()->isTemplateParameter()) {
775 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
776 Previous.getFoundDecl());
777 Previous.clear();
778 }
779
780 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
781 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
782 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
783 /*AllowInlineNamespace*/false);
784 if (!Previous.empty()) {
785 auto *Old = Previous.getRepresentativeDecl();
786 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
787 Diag(Old->getLocation(), diag::note_previous_definition);
788 }
789
Richard Smith32cb8c92016-08-12 00:53:41 +0000790 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
Richard Smith7873de02016-08-11 22:25:46 +0000791 PushOnScopeChains(BD, S, true);
792 Bindings.push_back(BD);
793 ParsingInitForAutoVars.insert(BD);
794 }
795
796 // There are no prior lookup results for the variable itself, because it
797 // is unnamed.
798 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
799 Decomp.getLSquareLoc());
800 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
801
802 // Build the variable that holds the non-decomposed object.
803 bool AddToScope = true;
804 NamedDecl *New =
805 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
806 MultiTemplateParamsArg(), AddToScope, Bindings);
807 CurContext->addHiddenDecl(New);
808
809 if (isInOpenMPDeclareTargetContext())
810 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
811
812 return New;
813}
814
815static bool checkSimpleDecomposition(
816 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
Benjamin Kramer6ca15b62016-11-24 15:36:17 +0000817 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
Richard Smith7873de02016-08-11 22:25:46 +0000818 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
819 if ((int64_t)Bindings.size() != NumElems) {
820 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
821 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
822 << (NumElems < Bindings.size());
823 return true;
824 }
825
826 unsigned I = 0;
827 for (auto *B : Bindings) {
828 SourceLocation Loc = B->getLocation();
829 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
830 if (E.isInvalid())
831 return true;
832 E = GetInit(Loc, E.get(), I++);
833 if (E.isInvalid())
834 return true;
835 B->setBinding(ElemType, E.get());
836 }
837
838 return false;
839}
840
841static bool checkArrayLikeDecomposition(Sema &S,
842 ArrayRef<BindingDecl *> Bindings,
843 ValueDecl *Src, QualType DecompType,
Benjamin Kramer6ca15b62016-11-24 15:36:17 +0000844 const llvm::APSInt &NumElems,
Richard Smith7873de02016-08-11 22:25:46 +0000845 QualType ElemType) {
846 return checkSimpleDecomposition(
847 S, Bindings, Src, DecompType, NumElems, ElemType,
848 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
849 ExprResult E = S.ActOnIntegerConstant(Loc, I);
850 if (E.isInvalid())
851 return ExprError();
852 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
853 });
854}
855
856static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
857 ValueDecl *Src, QualType DecompType,
858 const ConstantArrayType *CAT) {
859 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
860 llvm::APSInt(CAT->getSize()),
861 CAT->getElementType());
862}
863
864static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
865 ValueDecl *Src, QualType DecompType,
866 const VectorType *VT) {
867 return checkArrayLikeDecomposition(
868 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
869 S.Context.getQualifiedType(VT->getElementType(),
870 DecompType.getQualifiers()));
871}
872
873static bool checkComplexDecomposition(Sema &S,
874 ArrayRef<BindingDecl *> Bindings,
875 ValueDecl *Src, QualType DecompType,
876 const ComplexType *CT) {
877 return checkSimpleDecomposition(
878 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
879 S.Context.getQualifiedType(CT->getElementType(),
880 DecompType.getQualifiers()),
881 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
882 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
883 });
884}
885
886static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
887 TemplateArgumentListInfo &Args) {
888 SmallString<128> SS;
889 llvm::raw_svector_ostream OS(SS);
890 bool First = true;
891 for (auto &Arg : Args.arguments()) {
892 if (!First)
893 OS << ", ";
894 Arg.getArgument().print(PrintingPolicy, OS);
895 First = false;
896 }
897 return OS.str();
898}
899
900static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
901 SourceLocation Loc, StringRef Trait,
902 TemplateArgumentListInfo &Args,
903 unsigned DiagID) {
904 auto DiagnoseMissing = [&] {
905 if (DiagID)
906 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
907 Args);
908 return true;
909 };
910
911 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
912 NamespaceDecl *Std = S.getStdNamespace();
913 if (!Std)
914 return DiagnoseMissing();
915
916 // Look up the trait itself, within namespace std. We can diagnose various
917 // problems with this lookup even if we've been asked to not diagnose a
918 // missing specialization, because this can only fail if the user has been
919 // declaring their own names in namespace std or we don't support the
920 // standard library implementation in use.
921 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
922 Loc, Sema::LookupOrdinaryName);
923 if (!S.LookupQualifiedName(Result, Std))
924 return DiagnoseMissing();
925 if (Result.isAmbiguous())
926 return true;
927
928 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
929 if (!TraitTD) {
930 Result.suppressDiagnostics();
931 NamedDecl *Found = *Result.begin();
932 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
933 S.Diag(Found->getLocation(), diag::note_declared_at);
934 return true;
935 }
936
937 // Build the template-id.
938 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
939 if (TraitTy.isNull())
940 return true;
941 if (!S.isCompleteType(Loc, TraitTy)) {
942 if (DiagID)
943 S.RequireCompleteType(
944 Loc, TraitTy, DiagID,
945 printTemplateArgs(S.Context.getPrintingPolicy(), Args));
946 return true;
947 }
948
949 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
950 assert(RD && "specialization of class template is not a class?");
951
952 // Look up the member of the trait type.
953 S.LookupQualifiedName(TraitMemberLookup, RD);
954 return TraitMemberLookup.isAmbiguous();
955}
956
957static TemplateArgumentLoc
958getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
959 uint64_t I) {
960 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
961 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
962}
963
964static TemplateArgumentLoc
965getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
966 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
967}
968
969namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
970
971static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
972 llvm::APSInt &Size) {
973 EnterExpressionEvaluationContext ContextRAII(S, Sema::ConstantEvaluated);
974
975 DeclarationName Value = S.PP.getIdentifierInfo("value");
976 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
977
978 // Form template argument list for tuple_size<T>.
979 TemplateArgumentListInfo Args(Loc, Loc);
980 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
981
982 // If there's no tuple_size specialization, it's not tuple-like.
983 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
984 return IsTupleLike::NotTupleLike;
985
Richard Smith208732e2016-12-08 03:24:55 +0000986 // If we get this far, we've committed to the tuple interpretation, but
987 // we can still fail if there actually isn't a usable ::value.
Richard Smith7873de02016-08-11 22:25:46 +0000988
989 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
990 LookupResult &R;
991 TemplateArgumentListInfo &Args;
992 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
993 : R(R), Args(Args) {}
994 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
995 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
996 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
997 }
998 } Diagnoser(R, Args);
999
1000 if (R.empty()) {
1001 Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1002 return IsTupleLike::Error;
1003 }
1004
1005 ExprResult E =
1006 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1007 if (E.isInvalid())
1008 return IsTupleLike::Error;
1009
1010 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1011 if (E.isInvalid())
1012 return IsTupleLike::Error;
1013
1014 return IsTupleLike::TupleLike;
1015}
1016
1017/// \return std::tuple_element<I, T>::type.
1018static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1019 unsigned I, QualType T) {
1020 // Form template argument list for tuple_element<I, T>.
1021 TemplateArgumentListInfo Args(Loc, Loc);
1022 Args.addArgument(
1023 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1024 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1025
1026 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1027 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1028 if (lookupStdTypeTraitMember(
1029 S, R, Loc, "tuple_element", Args,
1030 diag::err_decomp_decl_std_tuple_element_not_specialized))
1031 return QualType();
1032
1033 auto *TD = R.getAsSingle<TypeDecl>();
1034 if (!TD) {
1035 R.suppressDiagnostics();
1036 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1037 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1038 if (!R.empty())
1039 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1040 return QualType();
1041 }
1042
1043 return S.Context.getTypeDeclType(TD);
1044}
1045
1046namespace {
1047struct BindingDiagnosticTrap {
1048 Sema &S;
1049 DiagnosticErrorTrap Trap;
1050 BindingDecl *BD;
1051
1052 BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1053 : S(S), Trap(S.Diags), BD(BD) {}
1054 ~BindingDiagnosticTrap() {
1055 if (Trap.hasErrorOccurred())
1056 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1057 }
1058};
1059}
1060
Richard Smith3997b1b2016-08-12 01:55:21 +00001061static bool checkTupleLikeDecomposition(Sema &S,
1062 ArrayRef<BindingDecl *> Bindings,
Richard Smith97fcf4b2016-08-14 23:15:52 +00001063 VarDecl *Src, QualType DecompType,
Benjamin Kramer6ca15b62016-11-24 15:36:17 +00001064 const llvm::APSInt &TupleSize) {
Richard Smith7873de02016-08-11 22:25:46 +00001065 if ((int64_t)Bindings.size() != TupleSize) {
1066 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1067 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1068 << (TupleSize < Bindings.size());
1069 return true;
1070 }
1071
1072 if (Bindings.empty())
1073 return false;
1074
1075 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1076
1077 // [dcl.decomp]p3:
1078 // The unqualified-id get is looked up in the scope of E by class member
1079 // access lookup
1080 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1081 bool UseMemberGet = false;
1082 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1083 if (auto *RD = DecompType->getAsCXXRecordDecl())
1084 S.LookupQualifiedName(MemberGet, RD);
1085 if (MemberGet.isAmbiguous())
1086 return true;
1087 UseMemberGet = !MemberGet.empty();
1088 S.FilterAcceptableTemplateNames(MemberGet);
1089 }
1090
1091 unsigned I = 0;
1092 for (auto *B : Bindings) {
1093 BindingDiagnosticTrap Trap(S, B);
1094 SourceLocation Loc = B->getLocation();
1095
1096 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1097 if (E.isInvalid())
1098 return true;
1099
1100 // e is an lvalue if the type of the entity is an lvalue reference and
1101 // an xvalue otherwise
1102 if (!Src->getType()->isLValueReferenceType())
1103 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1104 E.get(), nullptr, VK_XValue);
1105
1106 TemplateArgumentListInfo Args(Loc, Loc);
1107 Args.addArgument(
1108 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1109
1110 if (UseMemberGet) {
1111 // if [lookup of member get] finds at least one declaration, the
1112 // initializer is e.get<i-1>().
1113 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1114 CXXScopeSpec(), SourceLocation(), nullptr,
1115 MemberGet, &Args, nullptr);
1116 if (E.isInvalid())
1117 return true;
1118
1119 E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
1120 } else {
1121 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1122 // in the associated namespaces.
1123 Expr *Get = UnresolvedLookupExpr::Create(
1124 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1125 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1126 UnresolvedSetIterator(), UnresolvedSetIterator());
1127
1128 Expr *Arg = E.get();
1129 E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
1130 }
1131 if (E.isInvalid())
1132 return true;
1133 Expr *Init = E.get();
1134
1135 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1136 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1137 if (T.isNull())
1138 return true;
1139
1140 // each vi is a variable of type "reference to T" initialized with the
1141 // initializer, where the reference is an lvalue reference if the
1142 // initializer is an lvalue and an rvalue reference otherwise
1143 QualType RefType =
1144 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1145 if (RefType.isNull())
1146 return true;
Richard Smith97fcf4b2016-08-14 23:15:52 +00001147 auto *RefVD = VarDecl::Create(
1148 S.Context, Src->getDeclContext(), Loc, Loc,
1149 B->getDeclName().getAsIdentifierInfo(), RefType,
1150 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1151 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1152 RefVD->setTSCSpec(Src->getTSCSpec());
1153 RefVD->setImplicit();
1154 if (Src->isInlineSpecified())
1155 RefVD->setInlineSpecified();
Richard Smithda383632016-08-15 01:33:41 +00001156 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
Richard Smith7873de02016-08-11 22:25:46 +00001157
Richard Smith97fcf4b2016-08-14 23:15:52 +00001158 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
Richard Smith7873de02016-08-11 22:25:46 +00001159 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1160 InitializationSequence Seq(S, Entity, Kind, Init);
1161 E = Seq.Perform(S, Entity, Kind, Init);
1162 if (E.isInvalid())
1163 return true;
Richard Smithda383632016-08-15 01:33:41 +00001164 E = S.ActOnFinishFullExpr(E.get(), Loc);
1165 if (E.isInvalid())
1166 return true;
Richard Smith97fcf4b2016-08-14 23:15:52 +00001167 RefVD->setInit(E.get());
1168 RefVD->checkInitIsICE();
1169
Richard Smith97fcf4b2016-08-14 23:15:52 +00001170 E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1171 DeclarationNameInfo(B->getDeclName(), Loc),
1172 RefVD);
1173 if (E.isInvalid())
1174 return true;
Richard Smith7873de02016-08-11 22:25:46 +00001175
1176 B->setBinding(T, E.get());
1177 I++;
1178 }
1179
1180 return false;
1181}
1182
1183/// Find the base class to decompose in a built-in decomposition of a class type.
1184/// This base class search is, unfortunately, not quite like any other that we
1185/// perform anywhere else in C++.
1186static const CXXRecordDecl *findDecomposableBaseClass(Sema &S,
1187 SourceLocation Loc,
1188 const CXXRecordDecl *RD,
1189 CXXCastPath &BasePath) {
1190 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1191 CXXBasePath &Path) {
1192 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1193 };
1194
1195 const CXXRecordDecl *ClassWithFields = nullptr;
1196 if (RD->hasDirectFields())
1197 // [dcl.decomp]p4:
1198 // Otherwise, all of E's non-static data members shall be public direct
1199 // members of E ...
1200 ClassWithFields = RD;
1201 else {
1202 // ... or of ...
1203 CXXBasePaths Paths;
1204 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1205 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1206 // If no classes have fields, just decompose RD itself. (This will work
1207 // if and only if zero bindings were provided.)
1208 return RD;
1209 }
1210
1211 CXXBasePath *BestPath = nullptr;
1212 for (auto &P : Paths) {
1213 if (!BestPath)
1214 BestPath = &P;
1215 else if (!S.Context.hasSameType(P.back().Base->getType(),
1216 BestPath->back().Base->getType())) {
1217 // ... the same ...
1218 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1219 << false << RD << BestPath->back().Base->getType()
1220 << P.back().Base->getType();
1221 return nullptr;
1222 } else if (P.Access < BestPath->Access) {
1223 BestPath = &P;
1224 }
1225 }
1226
1227 // ... unambiguous ...
1228 QualType BaseType = BestPath->back().Base->getType();
1229 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1230 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1231 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1232 return nullptr;
1233 }
1234
1235 // ... public base class of E.
1236 if (BestPath->Access != AS_public) {
1237 S.Diag(Loc, diag::err_decomp_decl_non_public_base)
1238 << RD << BaseType;
1239 for (auto &BS : *BestPath) {
1240 if (BS.Base->getAccessSpecifier() != AS_public) {
1241 S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path)
1242 << (BS.Base->getAccessSpecifier() == AS_protected)
1243 << (BS.Base->getAccessSpecifierAsWritten() == AS_none);
1244 break;
1245 }
1246 }
1247 return nullptr;
1248 }
1249
1250 ClassWithFields = BaseType->getAsCXXRecordDecl();
1251 S.BuildBasePathArray(Paths, BasePath);
1252 }
1253
1254 // The above search did not check whether the selected class itself has base
1255 // classes with fields, so check that now.
1256 CXXBasePaths Paths;
1257 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1258 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1259 << (ClassWithFields == RD) << RD << ClassWithFields
1260 << Paths.front().back().Base->getType();
1261 return nullptr;
1262 }
1263
1264 return ClassWithFields;
1265}
1266
1267static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1268 ValueDecl *Src, QualType DecompType,
1269 const CXXRecordDecl *RD) {
1270 CXXCastPath BasePath;
1271 RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath);
1272 if (!RD)
1273 return true;
1274 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1275 DecompType.getQualifiers());
1276
1277 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
Richard Smithf70a9062016-10-20 18:29:25 +00001278 unsigned NumFields =
1279 std::count_if(RD->field_begin(), RD->field_end(),
1280 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
Richard Smith7873de02016-08-11 22:25:46 +00001281 assert(Bindings.size() != NumFields);
1282 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1283 << DecompType << (unsigned)Bindings.size() << NumFields
1284 << (NumFields < Bindings.size());
1285 return true;
1286 };
1287
1288 // all of E's non-static data members shall be public [...] members,
1289 // E shall not have an anonymous union member, ...
1290 unsigned I = 0;
1291 for (auto *FD : RD->fields()) {
1292 if (FD->isUnnamedBitfield())
1293 continue;
1294
1295 if (FD->isAnonymousStructOrUnion()) {
1296 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1297 << DecompType << FD->getType()->isUnionType();
1298 S.Diag(FD->getLocation(), diag::note_declared_at);
1299 return true;
1300 }
1301
1302 // We have a real field to bind.
1303 if (I >= Bindings.size())
1304 return DiagnoseBadNumberOfBindings();
1305 auto *B = Bindings[I++];
1306
1307 SourceLocation Loc = B->getLocation();
1308 if (FD->getAccess() != AS_public) {
1309 S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType;
1310
1311 // Determine whether the access specifier was explicit.
1312 bool Implicit = true;
1313 for (const auto *D : RD->decls()) {
1314 if (declaresSameEntity(D, FD))
1315 break;
1316 if (isa<AccessSpecDecl>(D)) {
1317 Implicit = false;
1318 break;
1319 }
1320 }
1321
1322 S.Diag(FD->getLocation(), diag::note_access_natural)
1323 << (FD->getAccess() == AS_protected) << Implicit;
1324 return true;
1325 }
1326
1327 // Initialize the binding to Src.FD.
1328 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1329 if (E.isInvalid())
1330 return true;
1331 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1332 VK_LValue, &BasePath);
1333 if (E.isInvalid())
1334 return true;
1335 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1336 CXXScopeSpec(), FD,
1337 DeclAccessPair::make(FD, FD->getAccess()),
1338 DeclarationNameInfo(FD->getDeclName(), Loc));
1339 if (E.isInvalid())
1340 return true;
1341
1342 // If the type of the member is T, the referenced type is cv T, where cv is
1343 // the cv-qualification of the decomposition expression.
1344 //
1345 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1346 // 'const' to the type of the field.
1347 Qualifiers Q = DecompType.getQualifiers();
1348 if (FD->isMutable())
1349 Q.removeConst();
1350 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1351 }
1352
1353 if (I != Bindings.size())
1354 return DiagnoseBadNumberOfBindings();
1355
1356 return false;
1357}
1358
Richard Smith3997b1b2016-08-12 01:55:21 +00001359void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
Richard Smith7873de02016-08-11 22:25:46 +00001360 QualType DecompType = DD->getType();
1361
1362 // If the type of the decomposition is dependent, then so is the type of
1363 // each binding.
1364 if (DecompType->isDependentType()) {
1365 for (auto *B : DD->bindings())
1366 B->setType(Context.DependentTy);
1367 return;
1368 }
1369
1370 DecompType = DecompType.getNonReferenceType();
1371 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1372
1373 // C++1z [dcl.decomp]/2:
1374 // If E is an array type [...]
1375 // As an extension, we also support decomposition of built-in complex and
1376 // vector types.
1377 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1378 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1379 DD->setInvalidDecl();
1380 return;
1381 }
1382 if (auto *VT = DecompType->getAs<VectorType>()) {
1383 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1384 DD->setInvalidDecl();
1385 return;
1386 }
1387 if (auto *CT = DecompType->getAs<ComplexType>()) {
1388 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1389 DD->setInvalidDecl();
1390 return;
1391 }
1392
1393 // C++1z [dcl.decomp]/3:
1394 // if the expression std::tuple_size<E>::value is a well-formed integral
1395 // constant expression, [...]
1396 llvm::APSInt TupleSize(32);
1397 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1398 case IsTupleLike::Error:
1399 DD->setInvalidDecl();
1400 return;
1401
1402 case IsTupleLike::TupleLike:
Richard Smith3997b1b2016-08-12 01:55:21 +00001403 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
Richard Smith7873de02016-08-11 22:25:46 +00001404 DD->setInvalidDecl();
1405 return;
1406
1407 case IsTupleLike::NotTupleLike:
1408 break;
1409 }
1410
1411 // C++1z [dcl.dcl]/8:
1412 // [E shall be of array or non-union class type]
1413 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1414 if (!RD || RD->isUnion()) {
1415 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1416 << DD << !RD << DecompType;
1417 DD->setInvalidDecl();
1418 return;
1419 }
1420
1421 // C++1z [dcl.decomp]/4:
1422 // all of E's non-static data members shall be [...] direct members of
1423 // E or of the same unambiguous public base class of E, ...
1424 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1425 DD->setInvalidDecl();
1426}
1427
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001428/// \brief Merge the exception specifications of two variable declarations.
1429///
1430/// This is called when there's a redeclaration of a VarDecl. The function
1431/// checks if the redeclaration might have an exception specification and
1432/// validates compatibility and merges the specs if necessary.
1433void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1434 // Shortcut if exceptions are disabled.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001435 if (!getLangOpts().CXXExceptions)
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001436 return;
1437
1438 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1439 "Should only be called if types are otherwise the same.");
1440
1441 QualType NewType = New->getType();
1442 QualType OldType = Old->getType();
1443
1444 // We're only interested in pointers and references to functions, as well
1445 // as pointers to member functions.
1446 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1447 NewType = R->getPointeeType();
1448 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1449 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1450 NewType = P->getPointeeType();
1451 OldType = OldType->getAs<PointerType>()->getPointeeType();
1452 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1453 NewType = M->getPointeeType();
1454 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1455 }
1456
1457 if (!NewType->isFunctionProtoType())
1458 return;
1459
1460 // There's lots of special cases for functions. For function pointers, system
1461 // libraries are hopefully not as broken so that we don't need these
1462 // workarounds.
1463 if (CheckEquivalentExceptionSpec(
1464 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1465 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1466 New->setInvalidDecl();
1467 }
1468}
1469
Chris Lattner199abbc2008-04-08 05:04:30 +00001470/// CheckCXXDefaultArguments - Verify that the default arguments for a
1471/// function declaration are well-formed according to C++
1472/// [dcl.fct.default].
1473void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1474 unsigned NumParams = FD->getNumParams();
1475 unsigned p;
1476
1477 // Find first parameter with a default argument
1478 for (p = 0; p < NumParams; ++p) {
1479 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith3cb4c632013-04-17 16:25:20 +00001480 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +00001481 break;
1482 }
1483
Benjamin Kramerfe257592015-03-27 13:58:41 +00001484 // C++11 [dcl.fct.default]p4:
1485 // In a given function declaration, each parameter subsequent to a parameter
1486 // with a default argument shall have a default argument supplied in this or
1487 // a previous declaration or shall be a function parameter pack. A default
1488 // argument shall not be redefined by a later declaration (not even to the
1489 // same value).
Chris Lattner199abbc2008-04-08 05:04:30 +00001490 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001491 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +00001492 ParmVarDecl *Param = FD->getParamDecl(p);
Benjamin Kramerfe257592015-03-27 13:58:41 +00001493 if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00001494 if (Param->isInvalidDecl())
1495 /* We already complained about this parameter. */;
1496 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +00001497 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +00001498 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +00001499 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +00001500 else
Mike Stump11289f42009-09-09 15:08:12 +00001501 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +00001502 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +00001503
Chris Lattner199abbc2008-04-08 05:04:30 +00001504 LastMissingDefaultArg = p;
1505 }
1506 }
1507
1508 if (LastMissingDefaultArg > 0) {
1509 // Some default arguments were missing. Clear out all of the
1510 // default arguments up to (and including) the last missing
1511 // default argument, so that we leave the function parameters
1512 // in a semantically valid state.
1513 for (p = 0; p <= LastMissingDefaultArg; ++p) {
1514 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +00001515 if (Param->hasDefaultArg()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001516 Param->setDefaultArg(nullptr);
Chris Lattner199abbc2008-04-08 05:04:30 +00001517 }
1518 }
1519 }
1520}
Douglas Gregor556877c2008-04-13 21:30:24 +00001521
Richard Smitheb3c10c2011-10-01 02:31:28 +00001522// CheckConstexprParameterTypes - Check whether a function's parameter types
1523// are all literal types. If so, return true. If not, produce a suitable
Richard Smith3607ffe2012-02-13 03:54:03 +00001524// diagnostic and return false.
1525static bool CheckConstexprParameterTypes(Sema &SemaRef,
1526 const FunctionDecl *FD) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001527 unsigned ArgIndex = 0;
1528 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001529 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1530 e = FT->param_type_end();
1531 i != e; ++i, ++ArgIndex) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001532 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1533 SourceLocation ParamLoc = PD->getLocation();
1534 if (!(*i)->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +00001535 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregora6c5abb2012-05-04 16:48:41 +00001536 diag::err_constexpr_non_literal_param,
1537 ArgIndex+1, PD->getSourceRange(),
1538 isa<CXXConstructorDecl>(FD)))
Richard Smitheb3c10c2011-10-01 02:31:28 +00001539 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001540 }
Joao Matose9a3ed42012-08-31 22:18:20 +00001541 return true;
1542}
1543
1544/// \brief Get diagnostic %select index for tag kind for
1545/// record diagnostic message.
1546/// WARNING: Indexes apply to particular diagnostics only!
1547///
1548/// \returns diagnostic %select index.
Joao Matosa5c42e92012-09-01 00:13:24 +00001549static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matose9a3ed42012-08-31 22:18:20 +00001550 switch (Tag) {
Joao Matosa5c42e92012-09-01 00:13:24 +00001551 case TTK_Struct: return 0;
1552 case TTK_Interface: return 1;
1553 case TTK_Class: return 2;
1554 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matose9a3ed42012-08-31 22:18:20 +00001555 }
Joao Matose9a3ed42012-08-31 22:18:20 +00001556}
1557
1558// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1559// the requirements of a constexpr function definition or a constexpr
1560// constructor definition. If so, return true. If not, produce appropriate
Richard Smith3607ffe2012-02-13 03:54:03 +00001561// diagnostics and return false.
Richard Smitheb3c10c2011-10-01 02:31:28 +00001562//
Richard Smith3607ffe2012-02-13 03:54:03 +00001563// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1564bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith7971b692012-01-13 04:54:00 +00001565 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1566 if (MD && MD->isInstance()) {
Richard Smith3607ffe2012-02-13 03:54:03 +00001567 // C++11 [dcl.constexpr]p4:
1568 // The definition of a constexpr constructor shall satisfy the following
1569 // constraints:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001570 // - the class shall not have any virtual base classes;
Joao Matose9a3ed42012-08-31 22:18:20 +00001571 const CXXRecordDecl *RD = MD->getParent();
1572 if (RD->getNumVBases()) {
1573 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1574 << isa<CXXConstructorDecl>(NewFD)
1575 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Aaron Ballman445a9392014-03-13 16:15:17 +00001576 for (const auto &I : RD->vbases())
1577 Diag(I.getLocStart(),
1578 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smitheb3c10c2011-10-01 02:31:28 +00001579 return false;
1580 }
Richard Smith7971b692012-01-13 04:54:00 +00001581 }
1582
1583 if (!isa<CXXConstructorDecl>(NewFD)) {
1584 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001585 // The definition of a constexpr function shall satisfy the following
1586 // constraints:
1587 // - it shall not be virtual;
1588 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1589 if (Method && Method->isVirtual()) {
David Majnemerab6607a2015-05-22 05:49:41 +00001590 Method = Method->getCanonicalDecl();
1591 Diag(Method->getLocation(), diag::err_constexpr_virtual);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001592
Richard Smith3607ffe2012-02-13 03:54:03 +00001593 // If it's not obvious why this function is virtual, find an overridden
1594 // function which uses the 'virtual' keyword.
1595 const CXXMethodDecl *WrittenVirtual = Method;
1596 while (!WrittenVirtual->isVirtualAsWritten())
1597 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1598 if (WrittenVirtual != Method)
1599 Diag(WrittenVirtual->getLocation(),
1600 diag::note_overridden_virtual_function);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001601 return false;
1602 }
1603
1604 // - its return type shall be a literal type;
Alp Toker314cc812014-01-25 16:55:45 +00001605 QualType RT = NewFD->getReturnType();
Richard Smitheb3c10c2011-10-01 02:31:28 +00001606 if (!RT->isDependentType() &&
Richard Smith3607ffe2012-02-13 03:54:03 +00001607 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregora6c5abb2012-05-04 16:48:41 +00001608 diag::err_constexpr_non_literal_return))
Richard Smitheb3c10c2011-10-01 02:31:28 +00001609 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001610 }
1611
Richard Smith7971b692012-01-13 04:54:00 +00001612 // - each of its parameter types shall be a literal type;
Richard Smith3607ffe2012-02-13 03:54:03 +00001613 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith7971b692012-01-13 04:54:00 +00001614 return false;
1615
Richard Smitheb3c10c2011-10-01 02:31:28 +00001616 return true;
1617}
1618
1619/// Check the given declaration statement is legal within a constexpr function
Richard Smithd9f663b2013-04-22 15:31:51 +00001620/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smitheb3c10c2011-10-01 02:31:28 +00001621///
Richard Smithd9f663b2013-04-22 15:31:51 +00001622/// \return true if the body is OK (maybe only as an extension), false if we
1623/// have diagnosed a problem.
Richard Smitheb3c10c2011-10-01 02:31:28 +00001624static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smithd9f663b2013-04-22 15:31:51 +00001625 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1626 // C++11 [dcl.constexpr]p3 and p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001627 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1628 // contain only
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001629 for (const auto *DclIt : DS->decls()) {
1630 switch (DclIt->getKind()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001631 case Decl::StaticAssert:
1632 case Decl::Using:
1633 case Decl::UsingShadow:
1634 case Decl::UsingDirective:
1635 case Decl::UnresolvedUsingTypename:
Richard Smithd9f663b2013-04-22 15:31:51 +00001636 case Decl::UnresolvedUsingValue:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001637 // - static_assert-declarations
1638 // - using-declarations,
1639 // - using-directives,
1640 continue;
1641
1642 case Decl::Typedef:
1643 case Decl::TypeAlias: {
1644 // - typedef declarations and alias-declarations that do not define
1645 // classes or enumerations,
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001646 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001647 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1648 // Don't allow variably-modified types in constexpr functions.
1649 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1650 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1651 << TL.getSourceRange() << TL.getType()
1652 << isa<CXXConstructorDecl>(Dcl);
1653 return false;
1654 }
1655 continue;
1656 }
1657
1658 case Decl::Enum:
1659 case Decl::CXXRecord:
Richard Smithd9f663b2013-04-22 15:31:51 +00001660 // C++1y allows types to be defined, not just declared.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001661 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smithd9f663b2013-04-22 15:31:51 +00001662 SemaRef.Diag(DS->getLocStart(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001663 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001664 ? diag::warn_cxx11_compat_constexpr_type_definition
1665 : diag::ext_constexpr_type_definition)
Richard Smitheb3c10c2011-10-01 02:31:28 +00001666 << isa<CXXConstructorDecl>(Dcl);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001667 continue;
1668
Richard Smithd9f663b2013-04-22 15:31:51 +00001669 case Decl::EnumConstant:
1670 case Decl::IndirectField:
1671 case Decl::ParmVar:
1672 // These can only appear with other declarations which are banned in
1673 // C++11 and permitted in C++1y, so ignore them.
1674 continue;
1675
Richard Smithdca60b42016-08-12 00:39:32 +00001676 case Decl::Var:
1677 case Decl::Decomposition: {
Richard Smithd9f663b2013-04-22 15:31:51 +00001678 // C++1y [dcl.constexpr]p3 allows anything except:
1679 // a definition of a variable of non-literal type or of static or
1680 // thread storage duration or for which no initialization is performed.
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001681 const auto *VD = cast<VarDecl>(DclIt);
Richard Smithd9f663b2013-04-22 15:31:51 +00001682 if (VD->isThisDeclarationADefinition()) {
1683 if (VD->isStaticLocal()) {
1684 SemaRef.Diag(VD->getLocation(),
1685 diag::err_constexpr_local_var_static)
1686 << isa<CXXConstructorDecl>(Dcl)
1687 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1688 return false;
1689 }
Richard Smith3da88fa2013-04-26 14:36:30 +00001690 if (!VD->getType()->isDependentType() &&
1691 SemaRef.RequireLiteralType(
Richard Smithd9f663b2013-04-22 15:31:51 +00001692 VD->getLocation(), VD->getType(),
1693 diag::err_constexpr_local_var_non_literal_type,
1694 isa<CXXConstructorDecl>(Dcl)))
1695 return false;
Richard Smithab44d5b2013-12-10 08:25:00 +00001696 if (!VD->getType()->isDependentType() &&
1697 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001698 SemaRef.Diag(VD->getLocation(),
1699 diag::err_constexpr_local_var_no_init)
1700 << isa<CXXConstructorDecl>(Dcl);
1701 return false;
1702 }
1703 }
1704 SemaRef.Diag(VD->getLocation(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001705 SemaRef.getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001706 ? diag::warn_cxx11_compat_constexpr_local_var
1707 : diag::ext_constexpr_local_var)
Richard Smitheb3c10c2011-10-01 02:31:28 +00001708 << isa<CXXConstructorDecl>(Dcl);
Richard Smithd9f663b2013-04-22 15:31:51 +00001709 continue;
1710 }
1711
1712 case Decl::NamespaceAlias:
1713 case Decl::Function:
1714 // These are disallowed in C++11 and permitted in C++1y. Allow them
1715 // everywhere as an extension.
1716 if (!Cxx1yLoc.isValid())
1717 Cxx1yLoc = DS->getLocStart();
1718 continue;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001719
1720 default:
1721 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1722 << isa<CXXConstructorDecl>(Dcl);
1723 return false;
1724 }
1725 }
1726
1727 return true;
1728}
1729
1730/// Check that the given field is initialized within a constexpr constructor.
1731///
1732/// \param Dcl The constexpr constructor being checked.
1733/// \param Field The field being checked. This may be a member of an anonymous
1734/// struct or union nested within the class being checked.
1735/// \param Inits All declarations, including anonymous struct/union members and
1736/// indirect members, for which any initialization was provided.
1737/// \param Diagnosed Set to true if an error is produced.
1738static void CheckConstexprCtorInitializer(Sema &SemaRef,
1739 const FunctionDecl *Dcl,
1740 FieldDecl *Field,
1741 llvm::SmallSet<Decl*, 16> &Inits,
1742 bool &Diagnosed) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00001743 if (Field->isInvalidDecl())
1744 return;
1745
Douglas Gregor556e5862011-10-10 17:22:13 +00001746 if (Field->isUnnamedBitfield())
1747 return;
Richard Smith4d59eeb2012-02-09 06:40:58 +00001748
Richard Smithab44d5b2013-12-10 08:25:00 +00001749 // Anonymous unions with no variant members and empty anonymous structs do not
1750 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1751 // indirect fields don't need initializing.
Richard Smith4d59eeb2012-02-09 06:40:58 +00001752 if (Field->isAnonymousStructOrUnion() &&
Richard Smithab44d5b2013-12-10 08:25:00 +00001753 (Field->getType()->isUnionType()
1754 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1755 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith4d59eeb2012-02-09 06:40:58 +00001756 return;
1757
Richard Smitheb3c10c2011-10-01 02:31:28 +00001758 if (!Inits.count(Field)) {
1759 if (!Diagnosed) {
1760 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1761 Diagnosed = true;
1762 }
1763 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1764 } else if (Field->isAnonymousStructOrUnion()) {
1765 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001766 for (auto *I : RD->fields())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001767 // If an anonymous union contains an anonymous struct of which any member
1768 // is initialized, all members must be initialized.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001769 if (!RD->isUnion() || Inits.count(I))
1770 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001771 }
1772}
1773
Richard Smithd9f663b2013-04-22 15:31:51 +00001774/// Check the provided statement is allowed in a constexpr function
1775/// definition.
1776static bool
1777CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00001778 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001779 SourceLocation &Cxx1yLoc) {
1780 // - its function-body shall be [...] a compound-statement that contains only
1781 switch (S->getStmtClass()) {
1782 case Stmt::NullStmtClass:
1783 // - null statements,
1784 return true;
1785
1786 case Stmt::DeclStmtClass:
1787 // - static_assert-declarations
1788 // - using-declarations,
1789 // - using-directives,
1790 // - typedef declarations and alias-declarations that do not define
1791 // classes or enumerations,
1792 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1793 return false;
1794 return true;
1795
1796 case Stmt::ReturnStmtClass:
1797 // - and exactly one return statement;
1798 if (isa<CXXConstructorDecl>(Dcl)) {
1799 // C++1y allows return statements in constexpr constructors.
1800 if (!Cxx1yLoc.isValid())
1801 Cxx1yLoc = S->getLocStart();
1802 return true;
1803 }
1804
1805 ReturnStmts.push_back(S->getLocStart());
1806 return true;
1807
1808 case Stmt::CompoundStmtClass: {
1809 // C++1y allows compound-statements.
1810 if (!Cxx1yLoc.isValid())
1811 Cxx1yLoc = S->getLocStart();
1812
1813 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001814 for (auto *BodyIt : CompStmt->body()) {
1815 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001816 Cxx1yLoc))
1817 return false;
1818 }
1819 return true;
1820 }
1821
1822 case Stmt::AttributedStmtClass:
1823 if (!Cxx1yLoc.isValid())
1824 Cxx1yLoc = S->getLocStart();
1825 return true;
1826
1827 case Stmt::IfStmtClass: {
1828 // C++1y allows if-statements.
1829 if (!Cxx1yLoc.isValid())
1830 Cxx1yLoc = S->getLocStart();
1831
1832 IfStmt *If = cast<IfStmt>(S);
1833 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1834 Cxx1yLoc))
1835 return false;
1836 if (If->getElse() &&
1837 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1838 Cxx1yLoc))
1839 return false;
1840 return true;
1841 }
1842
1843 case Stmt::WhileStmtClass:
1844 case Stmt::DoStmtClass:
1845 case Stmt::ForStmtClass:
1846 case Stmt::CXXForRangeStmtClass:
1847 case Stmt::ContinueStmtClass:
1848 // C++1y allows all of these. We don't allow them as extensions in C++11,
1849 // because they don't make sense without variable mutation.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001850 if (!SemaRef.getLangOpts().CPlusPlus14)
Richard Smithd9f663b2013-04-22 15:31:51 +00001851 break;
1852 if (!Cxx1yLoc.isValid())
1853 Cxx1yLoc = S->getLocStart();
Benjamin Kramer642f1732015-07-02 21:03:14 +00001854 for (Stmt *SubStmt : S->children())
1855 if (SubStmt &&
1856 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001857 Cxx1yLoc))
1858 return false;
1859 return true;
1860
1861 case Stmt::SwitchStmtClass:
1862 case Stmt::CaseStmtClass:
1863 case Stmt::DefaultStmtClass:
1864 case Stmt::BreakStmtClass:
1865 // C++1y allows switch-statements, and since they don't need variable
1866 // mutation, we can reasonably allow them in C++11 as an extension.
1867 if (!Cxx1yLoc.isValid())
1868 Cxx1yLoc = S->getLocStart();
Benjamin Kramer642f1732015-07-02 21:03:14 +00001869 for (Stmt *SubStmt : S->children())
1870 if (SubStmt &&
1871 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
Richard Smithd9f663b2013-04-22 15:31:51 +00001872 Cxx1yLoc))
1873 return false;
1874 return true;
1875
1876 default:
1877 if (!isa<Expr>(S))
1878 break;
1879
1880 // C++1y allows expression-statements.
1881 if (!Cxx1yLoc.isValid())
1882 Cxx1yLoc = S->getLocStart();
1883 return true;
1884 }
1885
1886 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1887 << isa<CXXConstructorDecl>(Dcl);
1888 return false;
1889}
1890
Richard Smitheb3c10c2011-10-01 02:31:28 +00001891/// Check the body for the given constexpr function declaration only contains
1892/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1893///
1894/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith3607ffe2012-02-13 03:54:03 +00001895bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001896 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +00001897 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001898 // The definition of a constexpr function shall satisfy the following
1899 // constraints: [...]
1900 // - its function-body shall be = delete, = default, or a
1901 // compound-statement
1902 //
Richard Smith74388b42012-02-04 00:33:54 +00001903 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +00001904 // In the definition of a constexpr constructor, [...]
1905 // - its function-body shall not be a function-try-block;
1906 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1907 << isa<CXXConstructorDecl>(Dcl);
1908 return false;
1909 }
1910
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001911 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smithd9f663b2013-04-22 15:31:51 +00001912
1913 // - its function-body shall be [...] a compound-statement that contains only
1914 // [... list of cases ...]
1915 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1916 SourceLocation Cxx1yLoc;
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001917 for (auto *BodyIt : CompBody->body()) {
1918 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smithd9f663b2013-04-22 15:31:51 +00001919 return false;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001920 }
1921
Richard Smithd9f663b2013-04-22 15:31:51 +00001922 if (Cxx1yLoc.isValid())
1923 Diag(Cxx1yLoc,
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001924 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00001925 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1926 : diag::ext_constexpr_body_invalid_stmt)
1927 << isa<CXXConstructorDecl>(Dcl);
1928
Richard Smitheb3c10c2011-10-01 02:31:28 +00001929 if (const CXXConstructorDecl *Constructor
1930 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1931 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith4d59eeb2012-02-09 06:40:58 +00001932 // DR1359:
1933 // - every non-variant non-static data member and base class sub-object
1934 // shall be initialized;
Richard Smithab44d5b2013-12-10 08:25:00 +00001935 // DR1460:
1936 // - if the class is a union having variant members, exactly one of them
Richard Smith4d59eeb2012-02-09 06:40:58 +00001937 // shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001938 if (RD->isUnion()) {
Richard Smithab44d5b2013-12-10 08:25:00 +00001939 if (Constructor->getNumCtorInitializers() == 0 &&
1940 RD->hasVariantMembers()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001941 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1942 return false;
1943 }
Richard Smithf368fb42011-10-10 16:38:04 +00001944 } else if (!Constructor->isDependentContext() &&
1945 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001946 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1947
1948 // Skip detailed checking if we have enough initializers, and we would
1949 // allow at most one initializer per member.
1950 bool AnyAnonStructUnionMembers = false;
1951 unsigned Fields = 0;
1952 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1953 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001954 if (I->isAnonymousStructOrUnion()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00001955 AnyAnonStructUnionMembers = true;
1956 break;
1957 }
1958 }
Richard Smithab44d5b2013-12-10 08:25:00 +00001959 // DR1460:
1960 // - if the class is a union-like class, but is not a union, for each of
1961 // its anonymous union members having variant members, exactly one of
1962 // them shall be initialized;
Richard Smitheb3c10c2011-10-01 02:31:28 +00001963 if (AnyAnonStructUnionMembers ||
1964 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1965 // Check initialization of non-static data members. Base classes are
1966 // always initialized so do not need to be checked. Dependent bases
1967 // might not have initializers in the member initializer list.
1968 llvm::SmallSet<Decl*, 16> Inits;
Aaron Ballman0ad78302014-03-13 17:34:31 +00001969 for (const auto *I: Constructor->inits()) {
1970 if (FieldDecl *FD = I->getMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001971 Inits.insert(FD);
Aaron Ballman0ad78302014-03-13 17:34:31 +00001972 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smitheb3c10c2011-10-01 02:31:28 +00001973 Inits.insert(ID->chain_begin(), ID->chain_end());
1974 }
1975
1976 bool Diagnosed = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001977 for (auto *I : RD->fields())
1978 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smitheb3c10c2011-10-01 02:31:28 +00001979 if (Diagnosed)
1980 return false;
1981 }
1982 }
Richard Smitheb3c10c2011-10-01 02:31:28 +00001983 } else {
1984 if (ReturnStmts.empty()) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001985 // C++1y doesn't require constexpr functions to contain a 'return'
Richard Smith06ffb452014-04-22 23:14:23 +00001986 // statement. We still do, unless the return type might be void, because
Richard Smithd9f663b2013-04-22 15:31:51 +00001987 // otherwise if there's no return statement, the function cannot
1988 // be used in a core constant expression.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001989 bool OK = getLangOpts().CPlusPlus14 &&
Richard Smith06ffb452014-04-22 23:14:23 +00001990 (Dcl->getReturnType()->isVoidType() ||
1991 Dcl->getReturnType()->isDependentType());
Richard Smithd9f663b2013-04-22 15:31:51 +00001992 Diag(Dcl->getLocation(),
Richard Smith3da88fa2013-04-26 14:36:30 +00001993 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1994 : diag::err_constexpr_body_no_return);
Richard Smithd35cb052015-08-28 22:33:53 +00001995 if (!OK)
1996 return false;
1997 } else if (ReturnStmts.size() > 1) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001998 Diag(ReturnStmts.back(),
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001999 getLangOpts().CPlusPlus14
Richard Smithd9f663b2013-04-22 15:31:51 +00002000 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2001 : diag::ext_constexpr_body_multiple_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00002002 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2003 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smitheb3c10c2011-10-01 02:31:28 +00002004 }
2005 }
2006
Richard Smith74388b42012-02-04 00:33:54 +00002007 // C++11 [dcl.constexpr]p5:
2008 // if no function argument values exist such that the function invocation
2009 // substitution would produce a constant expression, the program is
2010 // ill-formed; no diagnostic required.
2011 // C++11 [dcl.constexpr]p3:
2012 // - every constructor call and implicit conversion used in initializing the
2013 // return value shall be one of those allowed in a constant expression.
2014 // C++11 [dcl.constexpr]p4:
2015 // - every constructor involved in initializing non-static data members and
2016 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002017 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith3607ffe2012-02-13 03:54:03 +00002018 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithf86b5dc2012-12-09 05:55:43 +00002019 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith253c2a32012-01-27 01:14:48 +00002020 << isa<CXXConstructorDecl>(Dcl);
2021 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2022 Diag(Diags[I].first, Diags[I].second);
Richard Smithf86b5dc2012-12-09 05:55:43 +00002023 // Don't return false here: we allow this for compatibility in
2024 // system headers.
Richard Smith253c2a32012-01-27 01:14:48 +00002025 }
2026
Richard Smitheb3c10c2011-10-01 02:31:28 +00002027 return true;
2028}
2029
Douglas Gregor61956c42008-10-31 09:07:45 +00002030/// isCurrentClassName - Determine whether the identifier II is the
2031/// name of the class type currently being defined. In the case of
2032/// nested classes, this will only return true if II is the name of
2033/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00002034bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
2035 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002036 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002037
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00002038 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00002039 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00002040 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00002041 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2042 } else
2043 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2044
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00002045 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00002046 return &II == CurDecl->getIdentifier();
Benjamin Kramer8bf44352013-07-24 15:28:33 +00002047 return false;
Douglas Gregor61956c42008-10-31 09:07:45 +00002048}
2049
Richard Smithfb8b7b92013-10-15 00:00:26 +00002050/// \brief Determine whether the identifier II is a typo for the name of
2051/// the class type currently being defined. If so, update it to the identifier
2052/// that should have been used.
2053bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2054 assert(getLangOpts().CPlusPlus && "No class names in C!");
2055
2056 if (!getLangOpts().SpellChecking)
2057 return false;
2058
2059 CXXRecordDecl *CurDecl;
2060 if (SS && SS->isSet() && !SS->isInvalid()) {
2061 DeclContext *DC = computeDeclContext(*SS, true);
2062 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2063 } else
2064 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2065
2066 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2067 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2068 < II->getLength()) {
2069 II = CurDecl->getIdentifier();
2070 return true;
2071 }
2072
2073 return false;
2074}
2075
Douglas Gregordc974572012-11-10 07:24:09 +00002076/// \brief Determine whether the given class is a base class of the given
2077/// class, including looking at dependent bases.
2078static bool findCircularInheritance(const CXXRecordDecl *Class,
2079 const CXXRecordDecl *Current) {
2080 SmallVector<const CXXRecordDecl*, 8> Queue;
2081
2082 Class = Class->getCanonicalDecl();
2083 while (true) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002084 for (const auto &I : Current->bases()) {
2085 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregordc974572012-11-10 07:24:09 +00002086 if (!Base)
2087 continue;
2088
2089 Base = Base->getDefinition();
2090 if (!Base)
2091 continue;
2092
2093 if (Base->getCanonicalDecl() == Class)
2094 return true;
2095
2096 Queue.push_back(Base);
2097 }
2098
2099 if (Queue.empty())
2100 return false;
2101
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002102 Current = Queue.pop_back_val();
Douglas Gregordc974572012-11-10 07:24:09 +00002103 }
2104
2105 return false;
Douglas Gregor62004702012-11-10 01:18:17 +00002106}
2107
Mike Stump11289f42009-09-09 15:08:12 +00002108/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00002109///
2110/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2111/// and returns NULL otherwise.
2112CXXBaseSpecifier *
2113Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2114 SourceRange SpecifierRange,
2115 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00002116 TypeSourceInfo *TInfo,
2117 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00002118 QualType BaseType = TInfo->getType();
2119
Douglas Gregor463421d2009-03-03 04:44:36 +00002120 // C++ [class.union]p1:
2121 // A union shall not have base classes.
2122 if (Class->isUnion()) {
2123 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2124 << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00002125 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00002126 }
2127
Douglas Gregor752a5952011-01-03 22:36:02 +00002128 if (EllipsisLoc.isValid() &&
2129 !TInfo->getType()->containsUnexpandedParameterPack()) {
2130 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2131 << TInfo->getTypeLoc().getSourceRange();
2132 EllipsisLoc = SourceLocation();
2133 }
Douglas Gregor62004702012-11-10 01:18:17 +00002134
2135 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2136
2137 if (BaseType->isDependentType()) {
2138 // Make sure that we don't have circular inheritance among our dependent
2139 // bases. For non-dependent bases, the check for completeness below handles
2140 // this.
2141 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2142 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2143 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregordc974572012-11-10 07:24:09 +00002144 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregor62004702012-11-10 01:18:17 +00002145 Diag(BaseLoc, diag::err_circular_inheritance)
2146 << BaseType << Context.getTypeDeclType(Class);
2147
2148 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2149 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2150 << BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00002151
2152 return nullptr;
Douglas Gregor62004702012-11-10 01:18:17 +00002153 }
2154 }
2155
Mike Stump11289f42009-09-09 15:08:12 +00002156 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00002157 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00002158 Access, TInfo, EllipsisLoc);
Douglas Gregor62004702012-11-10 01:18:17 +00002159 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002160
2161 // Base specifiers must be record types.
2162 if (!BaseType->isRecordType()) {
2163 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00002164 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00002165 }
2166
2167 // C++ [class.union]p1:
2168 // A union shall not be used as a base class.
2169 if (BaseType->isUnionType()) {
2170 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Craig Topperc3ec1492014-05-26 06:22:03 +00002171 return nullptr;
Douglas Gregor463421d2009-03-03 04:44:36 +00002172 }
2173
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00002174 // For the MS ABI, propagate DLL attributes to base class templates.
2175 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2176 if (Attr *ClassAttr = getDLLAttr(Class)) {
2177 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2178 BaseType->getAsCXXRecordDecl())) {
Hans Wennborgfce87ca2015-06-09 00:39:09 +00002179 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2180 BaseLoc);
Hans Wennborg9bea9cc2014-06-25 18:25:57 +00002181 }
2182 }
2183 }
2184
Douglas Gregor463421d2009-03-03 04:44:36 +00002185 // C++ [class.derived]p2:
2186 // The class-name in a base-specifier shall not be an incompletely
2187 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00002188 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002189 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall3696dcb2010-08-17 07:23:57 +00002190 Class->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00002191 return nullptr;
John McCall3696dcb2010-08-17 07:23:57 +00002192 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002193
Eli Friedmanc96d4962009-08-15 21:55:26 +00002194 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002195 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00002196 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002197 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00002198 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer626032f2013-06-22 06:43:58 +00002199 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedmanc96d4962009-08-15 21:55:26 +00002200 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00002201
David Majnemer9b1754d2013-11-02 12:00:36 +00002202 // A class which contains a flexible array member is not suitable for use as a
2203 // base class:
2204 // - If the layout determines that a base comes before another base,
2205 // the flexible array member would index into the subsequent base.
2206 // - If the layout determines that base comes before the derived class,
2207 // the flexible array member would index into the derived class.
2208 if (CXXBaseDecl->hasFlexibleArrayMember()) {
2209 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2210 << CXXBaseDecl->getDeclName();
Craig Topperc3ec1492014-05-26 06:22:03 +00002211 return nullptr;
David Majnemer9b1754d2013-11-02 12:00:36 +00002212 }
2213
Anders Carlsson65c76d32011-03-25 14:55:14 +00002214 // C++ [class]p3:
David Majnemer45897602013-11-02 11:24:41 +00002215 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson65c76d32011-03-25 14:55:14 +00002216 // base-clause, the program is ill-formed.
David Majnemera5433082013-10-18 00:33:31 +00002217 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer45897602013-11-02 11:24:41 +00002218 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemera5433082013-10-18 00:33:31 +00002219 << CXXBaseDecl->getDeclName()
2220 << FA->isSpelledAsSealed();
Alp Toker2afa8782014-05-28 12:20:14 +00002221 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2222 << CXXBaseDecl->getDeclName() << FA->getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00002223 return nullptr;
Anders Carlssonfc1eef42011-01-22 17:51:53 +00002224 }
2225
John McCall3696dcb2010-08-17 07:23:57 +00002226 if (BaseDecl->isInvalidDecl())
2227 Class->setInvalidDecl();
David Majnemer45897602013-11-02 11:24:41 +00002228
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00002229 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00002230 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00002231 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00002232 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00002233}
2234
Douglas Gregor556877c2008-04-13 21:30:24 +00002235/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2236/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00002237/// example:
2238/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00002239/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00002240BaseResult
John McCall48871652010-08-21 09:40:31 +00002241Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith4c96e992013-02-19 23:47:15 +00002242 ParsedAttributes &Attributes,
Douglas Gregor29a92472008-10-22 17:49:05 +00002243 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00002244 ParsedType basetype, SourceLocation BaseLoc,
2245 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002246 if (!classdecl)
2247 return true;
2248
Douglas Gregorc40290e2009-03-09 23:48:35 +00002249 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00002250 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00002251 if (!Class)
2252 return true;
2253
David Majnemer5ef4fe72014-06-13 06:43:46 +00002254 // We haven't yet attached the base specifiers.
2255 Class->setIsParsingBaseSpecifiers();
2256
Richard Smith4c96e992013-02-19 23:47:15 +00002257 // We do not support any C++11 attributes on base-specifiers yet.
2258 // Diagnose any attributes we see.
2259 if (!Attributes.empty()) {
2260 for (AttributeList *Attr = Attributes.getList(); Attr;
2261 Attr = Attr->getNext()) {
2262 if (Attr->isInvalid() ||
2263 Attr->getKind() == AttributeList::IgnoredAttribute)
2264 continue;
2265 Diag(Attr->getLoc(),
2266 Attr->getKind() == AttributeList::UnknownAttribute
2267 ? diag::warn_unknown_attribute_ignored
2268 : diag::err_base_specifier_attribute)
2269 << Attr->getName();
2270 }
2271 }
2272
Craig Topperc3ec1492014-05-26 06:22:03 +00002273 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky19b9f952010-07-26 16:56:01 +00002274 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00002275
Douglas Gregor752a5952011-01-03 22:36:02 +00002276 if (EllipsisLoc.isInvalid() &&
2277 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00002278 UPPC_BaseType))
2279 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00002280
Douglas Gregor463421d2009-03-03 04:44:36 +00002281 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00002282 Virtual, Access, TInfo,
2283 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00002284 return BaseSpec;
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002285 else
2286 Class->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002287
Douglas Gregor463421d2009-03-03 04:44:36 +00002288 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00002289}
Douglas Gregor556877c2008-04-13 21:30:24 +00002290
Nathan Sidwell44b21742015-01-19 01:44:02 +00002291/// Use small set to collect indirect bases. As this is only used
2292/// locally, there's no need to abstract the small size parameter.
2293typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2294
2295/// \brief Recursively add the bases of Type. Don't add Type itself.
2296static void
2297NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2298 const QualType &Type)
2299{
2300 // Even though the incoming type is a base, it might not be
2301 // a class -- it could be a template parm, for instance.
2302 if (auto Rec = Type->getAs<RecordType>()) {
2303 auto Decl = Rec->getAsCXXRecordDecl();
2304
2305 // Iterate over its bases.
2306 for (const auto &BaseSpec : Decl->bases()) {
2307 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2308 .getUnqualifiedType();
2309 if (Set.insert(Base).second)
2310 // If we've not already seen it, recurse.
2311 NoteIndirectBases(Context, Set, Base);
2312 }
2313 }
2314}
2315
Douglas Gregor463421d2009-03-03 04:44:36 +00002316/// \brief Performs the actual work of attaching the given base class
2317/// specifiers to a C++ class.
Craig Topperaa700cb2015-12-27 21:55:19 +00002318bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2319 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2320 if (Bases.empty())
Douglas Gregor463421d2009-03-03 04:44:36 +00002321 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00002322
2323 // Used to keep track of which base types we have already seen, so
2324 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00002325 // that the key is always the unqualified canonical type of the base
2326 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00002327 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2328
Nathan Sidwell44b21742015-01-19 01:44:02 +00002329 // Used to track indirect bases so we can see if a direct base is
2330 // ambiguous.
2331 IndirectBaseSet IndirectBaseTypes;
2332
Douglas Gregor29a92472008-10-22 17:49:05 +00002333 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00002334 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00002335 bool Invalid = false;
Craig Topperaa700cb2015-12-27 21:55:19 +00002336 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00002337 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00002338 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002339 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer73ecd702012-03-05 17:20:04 +00002340
2341 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2342 if (KnownBase) {
Douglas Gregor29a92472008-10-22 17:49:05 +00002343 // C++ [class.mi]p3:
2344 // A class shall not be specified as a direct base class of a
2345 // derived class more than once.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002346 Diag(Bases[idx]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002347 diag::err_duplicate_base_class)
Benjamin Kramer73ecd702012-03-05 17:20:04 +00002348 << KnownBase->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00002349 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00002350
2351 // Delete the duplicate base class specifier; we're going to
2352 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00002353 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00002354
2355 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00002356 } else {
2357 // Okay, add this new base class.
Benjamin Kramer73ecd702012-03-05 17:20:04 +00002358 KnownBase = Bases[idx];
Douglas Gregor463421d2009-03-03 04:44:36 +00002359 Bases[NumGoodBases++] = Bases[idx];
Nathan Sidwell44b21742015-01-19 01:44:02 +00002360
2361 // Note this base's direct & indirect bases, if there could be ambiguity.
Craig Topperaa700cb2015-12-27 21:55:19 +00002362 if (Bases.size() > 1)
Nathan Sidwell44b21742015-01-19 01:44:02 +00002363 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2364
John McCalldb632ac2012-09-25 07:32:39 +00002365 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2366 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2367 if (Class->isInterface() &&
2368 (!RD->isInterface() ||
2369 KnownBase->getAccessSpecifier() != AS_public)) {
2370 // The Microsoft extension __interface does not permit bases that
2371 // are not themselves public interfaces.
2372 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
2373 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
2374 << RD->getSourceRange();
2375 Invalid = true;
2376 }
2377 if (RD->hasAttr<WeakAttr>())
Aaron Ballman36a53502014-01-16 13:03:14 +00002378 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalldb632ac2012-09-25 07:32:39 +00002379 }
Douglas Gregor29a92472008-10-22 17:49:05 +00002380 }
2381 }
2382
2383 // Attach the remaining base class specifiers to the derived class.
Craig Topperaa700cb2015-12-27 21:55:19 +00002384 Class->setBases(Bases.data(), NumGoodBases);
Nathan Sidwell44b21742015-01-19 01:44:02 +00002385
2386 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2387 // Check whether this direct base is inaccessible due to ambiguity.
2388 QualType BaseType = Bases[idx]->getType();
2389 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2390 .getUnqualifiedType();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00002391
Nathan Sidwell44b21742015-01-19 01:44:02 +00002392 if (IndirectBaseTypes.count(CanonicalBase)) {
2393 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2394 /*DetectVirtual=*/true);
2395 bool found
2396 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2397 assert(found);
NAKAMURA Takumi6a1565c2015-01-19 09:49:59 +00002398 (void)found;
Nathan Sidwell44b21742015-01-19 01:44:02 +00002399
2400 if (Paths.isAmbiguous(CanonicalBase))
2401 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
2402 << BaseType << getAmbiguousPathsDisplayString(Paths)
2403 << Bases[idx]->getSourceRange();
2404 else
2405 assert(Bases[idx]->isVirtual());
2406 }
2407
2408 // Delete the base class specifier, since its data has been copied
2409 // into the CXXRecordDecl.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00002410 Context.Deallocate(Bases[idx]);
Nathan Sidwell44b21742015-01-19 01:44:02 +00002411 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002412
2413 return Invalid;
2414}
2415
2416/// ActOnBaseSpecifiers - Attach the given base specifiers to the
2417/// class, after checking whether there are any duplicate base
2418/// classes.
Craig Topperaa700cb2015-12-27 21:55:19 +00002419void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2420 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2421 if (!ClassDecl || Bases.empty())
Douglas Gregor463421d2009-03-03 04:44:36 +00002422 return;
2423
2424 AdjustDeclIfTemplate(ClassDecl);
Craig Topperaa700cb2015-12-27 21:55:19 +00002425 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
Douglas Gregor556877c2008-04-13 21:30:24 +00002426}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00002427
Douglas Gregor36d1b142009-10-06 17:59:45 +00002428/// \brief Determine whether the type \p Derived is a C++ class that is
2429/// derived from the type \p Base.
Richard Smith0f59cb32015-12-18 21:45:41 +00002430bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002431 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002432 return false;
Richard Smith0f59cb32015-12-18 21:45:41 +00002433
Douglas Gregor45bb4832013-03-26 23:36:30 +00002434 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00002435 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002436 return false;
2437
Douglas Gregor45bb4832013-03-26 23:36:30 +00002438 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00002439 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002440 return false;
Douglas Gregor45bb4832013-03-26 23:36:30 +00002441
2442 // If either the base or the derived type is invalid, don't try to
2443 // check whether one is derived from the other.
2444 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2445 return false;
2446
Richard Smithdb0ac552015-12-18 22:40:25 +00002447 // FIXME: In a modules build, do we need the entire path to be visible for us
2448 // to be able to use the inheritance relationship?
2449 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2450 return false;
2451
Richard Smith0f59cb32015-12-18 21:45:41 +00002452 return DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00002453}
2454
2455/// \brief Determine whether the type \p Derived is a C++ class that is
2456/// derived from the type \p Base.
Richard Smith0f59cb32015-12-18 21:45:41 +00002457bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2458 CXXBasePaths &Paths) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002459 if (!getLangOpts().CPlusPlus)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002460 return false;
2461
Douglas Gregor45bb4832013-03-26 23:36:30 +00002462 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00002463 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002464 return false;
2465
Douglas Gregor45bb4832013-03-26 23:36:30 +00002466 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCalle78aac42010-03-10 03:28:59 +00002467 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00002468 return false;
2469
Richard Smithdb0ac552015-12-18 22:40:25 +00002470 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2471 return false;
2472
Douglas Gregor36d1b142009-10-06 17:59:45 +00002473 return DerivedRD->isDerivedFrom(BaseRD, Paths);
2474}
2475
Anders Carlssona70cff62010-04-24 19:06:50 +00002476void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00002477 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00002478 assert(BasePathArray.empty() && "Base path array must be empty!");
2479 assert(Paths.isRecordingPaths() && "Must record paths!");
2480
2481 const CXXBasePath &Path = Paths.front();
2482
2483 // We first go backward and check if we have a virtual base.
2484 // FIXME: It would be better if CXXBasePath had the base specifier for
2485 // the nearest virtual base.
2486 unsigned Start = 0;
2487 for (unsigned I = Path.size(); I != 0; --I) {
2488 if (Path[I - 1].Base->isVirtual()) {
2489 Start = I - 1;
2490 break;
2491 }
2492 }
2493
2494 // Now add all bases.
2495 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00002496 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00002497}
2498
Douglas Gregor36d1b142009-10-06 17:59:45 +00002499/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2500/// conversion (where Derived and Base are class types) is
2501/// well-formed, meaning that the conversion is unambiguous (and
2502/// that all of the base classes are accessible). Returns true
2503/// and emits a diagnostic if the code is ill-formed, returns false
2504/// otherwise. Loc is the location where this routine should point to
2505/// if there is an error, and Range is the source range to highlight
2506/// if there is an error.
George Burgess IV60bc9722016-01-13 23:36:34 +00002507///
2508/// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2509/// diagnostic for the respective type of error will be suppressed, but the
2510/// check for ill-formed code will still be performed.
Douglas Gregor36d1b142009-10-06 17:59:45 +00002511bool
2512Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00002513 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002514 unsigned AmbigiousBaseConvID,
2515 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00002516 DeclarationName Name,
George Burgess IV60bc9722016-01-13 23:36:34 +00002517 CXXCastPath *BasePath,
2518 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00002519 // First, determine whether the path from Derived to Base is
2520 // ambiguous. This is slightly more expensive than checking whether
2521 // the Derived to Base conversion exists, because here we need to
2522 // explore multiple paths to determine if there is an ambiguity.
2523 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2524 /*DetectVirtual=*/false);
Richard Smith0f59cb32015-12-18 21:45:41 +00002525 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
Douglas Gregor36d1b142009-10-06 17:59:45 +00002526 assert(DerivationOkay &&
2527 "Can only be used with a derived-to-base conversion");
2528 (void)DerivationOkay;
2529
2530 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
George Burgess IV60bc9722016-01-13 23:36:34 +00002531 if (!IgnoreAccess) {
Anders Carlssona70cff62010-04-24 19:06:50 +00002532 // Check that the base class can be accessed.
2533 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
2534 InaccessibleBaseID)) {
2535 case AR_inaccessible:
2536 return true;
2537 case AR_accessible:
2538 case AR_dependent:
2539 case AR_delayed:
2540 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00002541 }
John McCall5b0829a2010-02-10 09:31:12 +00002542 }
Anders Carlssona70cff62010-04-24 19:06:50 +00002543
2544 // Build a base path if necessary.
2545 if (BasePath)
2546 BuildBasePathArray(Paths, *BasePath);
2547 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00002548 }
2549
David Majnemer626032f2013-06-22 06:43:58 +00002550 if (AmbigiousBaseConvID) {
2551 // We know that the derived-to-base conversion is ambiguous, and
2552 // we're going to produce a diagnostic. Perform the derived-to-base
2553 // search just one more time to compute all of the possible paths so
2554 // that we can print them out. This is more expensive than any of
2555 // the previous derived-to-base checks we've done, but at this point
2556 // performance isn't as much of an issue.
2557 Paths.clear();
2558 Paths.setRecordingPaths(true);
Richard Smith0f59cb32015-12-18 21:45:41 +00002559 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
David Majnemer626032f2013-06-22 06:43:58 +00002560 assert(StillOkay && "Can only be used with a derived-to-base conversion");
2561 (void)StillOkay;
2562
2563 // Build up a textual representation of the ambiguous paths, e.g.,
2564 // D -> B -> A, that will be used to illustrate the ambiguous
2565 // conversions in the diagnostic. We only print one of the paths
2566 // to each base class subobject.
2567 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2568
2569 Diag(Loc, AmbigiousBaseConvID)
2570 << Derived << Base << PathDisplayStr << Range << Name;
2571 }
Douglas Gregor36d1b142009-10-06 17:59:45 +00002572 return true;
2573}
2574
2575bool
2576Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00002577 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00002578 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002579 bool IgnoreAccess) {
George Burgess IV60bc9722016-01-13 23:36:34 +00002580 return CheckDerivedToBaseConversion(
2581 Derived, Base, diag::err_upcast_to_inaccessible_base,
2582 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2583 BasePath, IgnoreAccess);
Douglas Gregor36d1b142009-10-06 17:59:45 +00002584}
2585
2586
2587/// @brief Builds a string representing ambiguous paths from a
2588/// specific derived class to different subobjects of the same base
2589/// class.
2590///
2591/// This function builds a string that can be used in error messages
2592/// to show the different paths that one can take through the
2593/// inheritance hierarchy to go from the derived class to different
2594/// subobjects of a base class. The result looks something like this:
2595/// @code
2596/// struct D -> struct B -> struct A
2597/// struct D -> struct C -> struct A
2598/// @endcode
2599std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2600 std::string PathDisplayStr;
2601 std::set<unsigned> DisplayedPaths;
2602 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2603 Path != Paths.end(); ++Path) {
2604 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2605 // We haven't displayed a path to this particular base
2606 // class subobject yet.
2607 PathDisplayStr += "\n ";
2608 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2609 for (CXXBasePath::const_iterator Element = Path->begin();
2610 Element != Path->end(); ++Element)
2611 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2612 }
2613 }
2614
2615 return PathDisplayStr;
2616}
2617
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002618//===----------------------------------------------------------------------===//
2619// C++ class member Handling
2620//===----------------------------------------------------------------------===//
2621
Abramo Bagnarad7340582010-06-05 05:09:32 +00002622/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002623bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
2624 SourceLocation ASLoc,
2625 SourceLocation ColonLoc,
2626 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00002627 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00002628 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00002629 ASLoc, ColonLoc);
2630 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00002631 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00002632}
2633
Richard Smith18f07db2012-08-06 03:25:17 +00002634/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002635void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smith09b031f2012-09-06 18:32:18 +00002636 if (D->isInvalidDecl())
2637 return;
2638
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002639 // We only care about "override" and "final" declarations.
2640 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2641 return;
Anders Carlssonfd835532011-01-20 05:57:14 +00002642
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002643 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00002644
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002645 // We can't check dependent instance methods.
2646 if (MD && MD->isInstance() &&
2647 (MD->getParent()->hasAnyDependentBases() ||
2648 MD->getType()->isDependentType()))
2649 return;
2650
2651 if (MD && !MD->isVirtual()) {
2652 // If we have a non-virtual method, check if if hides a virtual method.
2653 // (In that case, it's most likely the method has the wrong type.)
2654 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2655 FindHiddenVirtualMethods(MD, OverloadedMethods);
2656
2657 if (!OverloadedMethods.empty()) {
Richard Smith18f07db2012-08-06 03:25:17 +00002658 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2659 Diag(OA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002660 diag::override_keyword_hides_virtual_member_function)
2661 << "override" << (OverloadedMethods.size() > 1);
2662 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smith18f07db2012-08-06 03:25:17 +00002663 Diag(FA->getLocation(),
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002664 diag::override_keyword_hides_virtual_member_function)
David Majnemera5433082013-10-18 00:33:31 +00002665 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2666 << (OverloadedMethods.size() > 1);
Richard Smith18f07db2012-08-06 03:25:17 +00002667 }
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002668 NoteHiddenVirtualMethods(MD, OverloadedMethods);
2669 MD->setInvalidDecl();
2670 return;
2671 }
2672 // Fall through into the general case diagnostic.
2673 // FIXME: We might want to attempt typo correction here.
2674 }
2675
2676 if (!MD || !MD->isVirtual()) {
2677 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2678 Diag(OA->getLocation(),
2679 diag::override_keyword_only_allowed_on_virtual_member_functions)
2680 << "override" << FixItHint::CreateRemoval(OA->getLocation());
2681 D->dropAttr<OverrideAttr>();
2682 }
2683 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2684 Diag(FA->getLocation(),
2685 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemera5433082013-10-18 00:33:31 +00002686 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2687 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmanaf65120b2013-09-05 23:51:03 +00002688 D->dropAttr<FinalAttr>();
Richard Smith18f07db2012-08-06 03:25:17 +00002689 }
Anders Carlssonfd835532011-01-20 05:57:14 +00002690 return;
2691 }
Richard Smith18f07db2012-08-06 03:25:17 +00002692
Richard Smith18f07db2012-08-06 03:25:17 +00002693 // C++11 [class.virtual]p5:
David Blaikie1cbb9712014-11-14 19:09:44 +00002694 // If a function is marked with the virt-specifier override and
Richard Smith18f07db2012-08-06 03:25:17 +00002695 // does not override a member function of a base class, the program is
2696 // ill-formed.
2697 bool HasOverriddenMethods =
2698 MD->begin_overridden_methods() != MD->end_overridden_methods();
2699 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2700 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2701 << MD->getDeclName();
Anders Carlssonfd835532011-01-20 05:57:14 +00002702}
2703
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00002704void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2705 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2706 return;
2707 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2708 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
2709 isa<CXXDestructorDecl>(MD))
2710 return;
2711
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00002712 SourceLocation Loc = MD->getLocation();
2713 SourceLocation SpellingLoc = Loc;
2714 if (getSourceManager().isMacroArgExpansion(Loc))
2715 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
2716 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2717 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
Fariborz Jahanian6e213382014-10-31 19:56:27 +00002718 return;
Fariborz Jahaniane3db7782014-11-03 19:46:18 +00002719
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00002720 if (MD->size_overridden_methods() > 0) {
2721 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
2722 << MD->getDeclName();
2723 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2724 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2725 }
2726}
2727
Richard Smith18f07db2012-08-06 03:25:17 +00002728/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson3f610c72011-01-20 16:25:36 +00002729/// function overrides a virtual member function marked 'final', according to
Richard Smith18f07db2012-08-06 03:25:17 +00002730/// C++11 [class.virtual]p4.
Anders Carlsson3f610c72011-01-20 16:25:36 +00002731bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2732 const CXXMethodDecl *Old) {
David Majnemera5433082013-10-18 00:33:31 +00002733 FinalAttr *FA = Old->getAttr<FinalAttr>();
2734 if (!FA)
Anders Carlsson19588aa2011-01-23 21:07:30 +00002735 return false;
2736
2737 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemera5433082013-10-18 00:33:31 +00002738 << New->getDeclName()
2739 << FA->isSpelledAsSealed();
Anders Carlsson19588aa2011-01-23 21:07:30 +00002740 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2741 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00002742}
2743
Daniel Jasper0baec5492012-06-06 08:32:04 +00002744static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0a8cfc72012-08-07 21:30:42 +00002745 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2746 // FIXME: Destruction of ObjC lifetime types has side-effects.
2747 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2748 return !RD->isCompleteDefinition() ||
2749 !RD->hasTrivialDefaultConstructor() ||
2750 !RD->hasTrivialDestructor();
Daniel Jasper0baec5492012-06-06 08:32:04 +00002751 return false;
2752}
2753
John McCall5e77d762013-04-16 07:28:30 +00002754static AttributeList *getMSPropertyAttr(AttributeList *list) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002755 for (AttributeList *it = list; it != nullptr; it = it->getNext())
John McCall5e77d762013-04-16 07:28:30 +00002756 if (it->isDeclspecPropertyAttribute())
2757 return it;
Craig Topperc3ec1492014-05-26 06:22:03 +00002758 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +00002759}
2760
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002761/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2762/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00002763/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smith2b013182012-06-10 03:12:00 +00002764/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2765/// present (but parsing it has been deferred).
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002766NamedDecl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002767Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00002768 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00002769 Expr *BW, const VirtSpecifiers &VS,
Richard Smith2b013182012-06-10 03:12:00 +00002770 InClassInitStyle InitStyle) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002771 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002772 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2773 DeclarationName Name = NameInfo.getName();
2774 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00002775
2776 // For anonymous bitfields, the location should point to the type.
2777 if (Loc.isInvalid())
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002778 Loc = D.getLocStart();
Douglas Gregor23ab7452010-11-09 03:31:16 +00002779
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002780 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002781
John McCallb1cd7da2010-06-04 08:34:12 +00002782 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00002783 assert(!DS.isFriendSpecified());
2784
Richard Smithcfcdf3a2011-06-25 02:28:38 +00002785 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00002786
John McCalldb632ac2012-09-25 07:32:39 +00002787 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2788 // The Microsoft extension __interface only permits public member functions
2789 // and prohibits constructors, destructors, operators, non-public member
2790 // functions, static methods and data members.
2791 unsigned InvalidDecl;
2792 bool ShowDeclName = true;
2793 if (!isFunc)
2794 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2795 else if (AS != AS_public)
2796 InvalidDecl = 2;
2797 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2798 InvalidDecl = 3;
2799 else switch (Name.getNameKind()) {
2800 case DeclarationName::CXXConstructorName:
2801 InvalidDecl = 4;
2802 ShowDeclName = false;
2803 break;
2804
2805 case DeclarationName::CXXDestructorName:
2806 InvalidDecl = 5;
2807 ShowDeclName = false;
2808 break;
2809
2810 case DeclarationName::CXXOperatorName:
2811 case DeclarationName::CXXConversionFunctionName:
2812 InvalidDecl = 6;
2813 break;
2814
2815 default:
2816 InvalidDecl = 0;
2817 break;
2818 }
2819
2820 if (InvalidDecl) {
2821 if (ShowDeclName)
2822 Diag(Loc, diag::err_invalid_member_in_interface)
2823 << (InvalidDecl-1) << Name;
2824 else
2825 Diag(Loc, diag::err_invalid_member_in_interface)
2826 << (InvalidDecl-1) << "";
Craig Topperc3ec1492014-05-26 06:22:03 +00002827 return nullptr;
John McCalldb632ac2012-09-25 07:32:39 +00002828 }
2829 }
2830
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002831 // C++ 9.2p6: A member shall not be declared to have automatic storage
2832 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002833 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2834 // data members and cannot be applied to names declared const or static,
2835 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002836 switch (DS.getStorageClassSpec()) {
Richard Smithb4a9e862013-04-12 22:46:28 +00002837 case DeclSpec::SCS_unspecified:
2838 case DeclSpec::SCS_typedef:
2839 case DeclSpec::SCS_static:
2840 break;
2841 case DeclSpec::SCS_mutable:
2842 if (isFunc) {
2843 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00002844
Richard Smithb4a9e862013-04-12 22:46:28 +00002845 // FIXME: It would be nicer if the keyword was ignored only for this
2846 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002847 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithb4a9e862013-04-12 22:46:28 +00002848 }
2849 break;
2850 default:
2851 Diag(DS.getStorageClassSpecLoc(),
2852 diag::err_storageclass_invalid_for_member);
2853 D.getMutableDeclSpec().ClearStorageClassSpecs();
2854 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002855 }
2856
Sebastian Redlccdfaba2008-11-14 23:42:31 +00002857 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2858 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00002859 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002860
David Blaikie35506f82013-01-30 01:22:18 +00002861 if (DS.isConstexprSpecified() && isInstField) {
2862 SemaDiagnosticBuilder B =
2863 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2864 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2865 if (InitStyle == ICIS_NoInit) {
Richard Smith82dce552014-04-14 21:00:40 +00002866 B << 0 << 0;
2867 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2868 B << FixItHint::CreateRemoval(ConstexprLoc);
2869 else {
2870 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2871 D.getMutableDeclSpec().ClearConstexprSpec();
2872 const char *PrevSpec;
2873 unsigned DiagID;
2874 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2875 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2876 (void)Failed;
2877 assert(!Failed && "Making a constexpr member const shouldn't fail");
2878 }
David Blaikie35506f82013-01-30 01:22:18 +00002879 } else {
2880 B << 1;
2881 const char *PrevSpec;
2882 unsigned DiagID;
David Blaikie35506f82013-01-30 01:22:18 +00002883 if (D.getMutableDeclSpec().SetStorageClassSpec(
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002884 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2885 Context.getPrintingPolicy())) {
Matt Beaumont-Gayefc270d2013-01-31 00:08:03 +00002886 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie35506f82013-01-30 01:22:18 +00002887 "This is the only DeclSpec that should fail to be applied");
2888 B << 1;
2889 } else {
2890 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2891 isInstField = false;
2892 }
2893 }
2894 }
2895
Rafael Espindola0a67e2f2013-01-08 20:44:06 +00002896 NamedDecl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00002897 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00002898 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002899
2900 // Data members must have identifiers for names.
Benjamin Kramer365082d2012-05-19 16:34:46 +00002901 if (!Name.isIdentifier()) {
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002902 Diag(Loc, diag::err_bad_variable_name)
2903 << Name;
Craig Topperc3ec1492014-05-26 06:22:03 +00002904 return nullptr;
Douglas Gregorbb64afc2011-10-09 18:55:59 +00002905 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002906
Benjamin Kramer365082d2012-05-19 16:34:46 +00002907 IdentifierInfo *II = Name.getAsIdentifierInfo();
2908
Douglas Gregor7c26c042011-09-21 14:40:46 +00002909 // Member field could not be with "template" keyword.
2910 // So TemplateParameterLists should be empty in this case.
2911 if (TemplateParameterLists.size()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002912 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregor7c26c042011-09-21 14:40:46 +00002913 if (TemplateParams->size()) {
2914 // There is no such thing as a member field template.
2915 Diag(D.getIdentifierLoc(), diag::err_template_member)
2916 << II
2917 << SourceRange(TemplateParams->getTemplateLoc(),
2918 TemplateParams->getRAngleLoc());
2919 } else {
2920 // There is an extraneous 'template<>' for this member.
2921 Diag(TemplateParams->getTemplateLoc(),
2922 diag::err_template_member_noparams)
2923 << II
2924 << SourceRange(TemplateParams->getTemplateLoc(),
2925 TemplateParams->getRAngleLoc());
2926 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002927 return nullptr;
Douglas Gregor7c26c042011-09-21 14:40:46 +00002928 }
2929
Douglas Gregora007d362010-10-13 22:19:53 +00002930 if (SS.isSet() && !SS.isInvalid()) {
2931 // The user provided a superfluous scope specifier inside a class
2932 // definition:
2933 //
2934 // class X {
2935 // int X::member;
2936 // };
Douglas Gregorb7d17dd2012-03-28 16:01:27 +00002937 if (DeclContext *DC = computeDeclContext(SS, false))
2938 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregora007d362010-10-13 22:19:53 +00002939 else
2940 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2941 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00002942
Douglas Gregora007d362010-10-13 22:19:53 +00002943 SS.clear();
2944 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00002945
John McCall5e77d762013-04-16 07:28:30 +00002946 AttributeList *MSPropertyAttr =
2947 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002948 if (MSPropertyAttr) {
2949 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2950 BitWidth, InitStyle, AS, MSPropertyAttr);
2951 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002952 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002953 isInstField = false;
2954 } else {
2955 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2956 BitWidth, InitStyle, AS);
Richard Smithbdb84f32016-07-22 23:36:59 +00002957 if (!Member)
2958 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002959 }
2960 } else {
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002961 Member = HandleDeclarator(S, D, TemplateParameterLists);
2962 if (!Member)
Craig Topperc3ec1492014-05-26 06:22:03 +00002963 return nullptr;
Eli Friedmanc37dbf72013-06-28 20:48:34 +00002964
2965 // Non-instance-fields can't have a bitfield.
2966 if (BitWidth) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002967 if (Member->isInvalidDecl()) {
2968 // don't emit another diagnostic.
David Majnemer380443a2014-12-28 22:51:45 +00002969 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00002970 // C++ 9.6p3: A bit-field shall not be a static member.
2971 // "static member 'A' cannot be a bit-field"
2972 Diag(Loc, diag::err_static_not_bitfield)
2973 << Name << BitWidth->getSourceRange();
2974 } else if (isa<TypedefDecl>(Member)) {
2975 // "typedef member 'x' cannot be a bit-field"
2976 Diag(Loc, diag::err_typedef_not_bitfield)
2977 << Name << BitWidth->getSourceRange();
2978 } else {
2979 // A function typedef ("typedef int f(); f a;").
2980 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2981 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00002982 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00002983 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00002984 }
Mike Stump11289f42009-09-09 15:08:12 +00002985
Craig Topperc3ec1492014-05-26 06:22:03 +00002986 BitWidth = nullptr;
Chris Lattnerd26760a2009-03-05 23:01:03 +00002987 Member->setInvalidDecl();
2988 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00002989
2990 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00002991
Larisse Voufo39a1e502013-08-06 01:03:05 +00002992 // If we have declared a member function template or static data member
2993 // template, set the access of the templated declaration as well.
Douglas Gregor3447e762009-08-20 22:52:58 +00002994 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2995 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002996 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2997 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00002998 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002999
Richard Smith18f07db2012-08-06 03:25:17 +00003000 if (VS.isOverrideSpecified())
Aaron Ballman36a53502014-01-16 13:03:14 +00003001 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smith18f07db2012-08-06 03:25:17 +00003002 if (VS.isFinalSpecified())
David Majnemera5433082013-10-18 00:33:31 +00003003 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3004 VS.isFinalSpelledSealed()));
Anders Carlssonfd835532011-01-20 05:57:14 +00003005
Douglas Gregorf2f08062011-03-08 17:10:18 +00003006 if (VS.getLastLocation().isValid()) {
3007 // Update the end location of a method that has a virt-specifiers.
3008 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3009 MD->setRangeEnd(VS.getLastLocation());
3010 }
Richard Smith18f07db2012-08-06 03:25:17 +00003011
Anders Carlssonc87f8612011-01-20 06:29:02 +00003012 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00003013
Douglas Gregor92751d42008-11-17 22:58:34 +00003014 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003015
Daniel Jasper0baec5492012-06-06 08:32:04 +00003016 if (isInstField) {
3017 FieldDecl *FD = cast<FieldDecl>(Member);
3018 FieldCollector->Add(FD);
3019
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00003020 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
Daniel Jasper0baec5492012-06-06 08:32:04 +00003021 // Remember all explicit private FieldDecls that have a name, no side
3022 // effects and are not part of a dependent type declaration.
3023 if (!FD->isImplicit() && FD->getDeclName() &&
3024 FD->getAccess() == AS_private &&
Daniel Jasper429c1342012-06-13 18:31:09 +00003025 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0a8cfc72012-08-07 21:30:42 +00003026 !FD->getParent()->isDependentContext() &&
Daniel Jasper0baec5492012-06-06 08:32:04 +00003027 !InitializationHasSideEffects(*FD))
3028 UnusedPrivateFields.insert(FD);
3029 }
3030 }
3031
John McCall48871652010-08-21 09:40:31 +00003032 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003033}
3034
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003035namespace {
3036 class UninitializedFieldVisitor
3037 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3038 Sema &S;
Richard Trieuef64e942013-10-25 00:56:00 +00003039 // List of Decls to generate a warning on. Also remove Decls that become
3040 // initialized.
Craig Topper4dd9b432014-08-17 23:49:53 +00003041 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
Richard Trieu3630c392014-11-21 03:10:30 +00003042 // List of base classes of the record. Classes are removed after their
3043 // initializers.
3044 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
Richard Trieu8d08a272014-08-28 03:23:47 +00003045 // Vector of decls to be removed from the Decl set prior to visiting the
3046 // nodes. These Decls may have been initialized in the prior initializer.
3047 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
Richard Trieu406e65c2013-09-20 03:03:06 +00003048 // If non-null, add a note to the warning pointing back to the constructor.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00003049 const CXXConstructorDecl *Constructor;
Nick Lewycky314a4492014-10-17 22:45:44 +00003050 // Variables to hold state when processing an initializer list. When
Richard Trieufa1d0a72014-10-17 20:56:10 +00003051 // InitList is true, special case initialization of FieldDecls matching
3052 // InitListFieldDecl.
NAKAMURA Takumi1af7cd72014-10-17 23:46:34 +00003053 bool InitList;
3054 FieldDecl *InitListFieldDecl;
Richard Trieufa1d0a72014-10-17 20:56:10 +00003055 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3056
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003057 public:
3058 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef64e942013-10-25 00:56:00 +00003059 UninitializedFieldVisitor(Sema &S,
Richard Trieu3630c392014-11-21 03:10:30 +00003060 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3061 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3062 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3063 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003064
Richard Trieufa1d0a72014-10-17 20:56:10 +00003065 // Returns true if the use of ME is not an uninitialized use.
3066 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3067 bool CheckReferenceOnly) {
3068 llvm::SmallVector<FieldDecl*, 4> Fields;
3069 bool ReferenceField = false;
3070 while (ME) {
3071 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3072 if (!FD)
3073 return false;
3074 Fields.push_back(FD);
3075 if (FD->getType()->isReferenceType())
3076 ReferenceField = true;
3077 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3078 }
3079
3080 // Binding a reference to an unintialized field is not an
3081 // uninitialized use.
3082 if (CheckReferenceOnly && !ReferenceField)
3083 return true;
3084
3085 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3086 // Discard the first field since it is the field decl that is being
3087 // initialized.
3088 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3089 UsedFieldIndex.push_back((*I)->getFieldIndex());
3090 }
3091
3092 for (auto UsedIter = UsedFieldIndex.begin(),
3093 UsedEnd = UsedFieldIndex.end(),
3094 OrigIter = InitFieldIndex.begin(),
3095 OrigEnd = InitFieldIndex.end();
3096 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3097 if (*UsedIter < *OrigIter)
3098 return true;
3099 if (*UsedIter > *OrigIter)
3100 break;
3101 }
3102
3103 return false;
3104 }
3105
Richard Trieu2d779b92014-10-01 03:44:58 +00003106 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3107 bool AddressOf) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00003108 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3109 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003110
Richard Trieu1bc22c12013-09-13 03:20:53 +00003111 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3112 // or union.
3113 MemberExpr *FieldME = ME;
3114
Richard Trieu2d779b92014-10-01 03:44:58 +00003115 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3116
Richard Trieu1bc22c12013-09-13 03:20:53 +00003117 Expr *Base = ME;
Richard Trieu3630c392014-11-21 03:10:30 +00003118 while (MemberExpr *SubME =
3119 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
Richard Trieu1bc22c12013-09-13 03:20:53 +00003120
Richard Trieufa1d0a72014-10-17 20:56:10 +00003121 if (isa<VarDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00003122 return;
3123
Richard Trieufa1d0a72014-10-17 20:56:10 +00003124 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
Richard Trieu1bc22c12013-09-13 03:20:53 +00003125 if (!FD->isAnonymousStructOrUnion())
Richard Trieufa1d0a72014-10-17 20:56:10 +00003126 FieldME = SubME;
Richard Trieu1bc22c12013-09-13 03:20:53 +00003127
Richard Trieu2d779b92014-10-01 03:44:58 +00003128 if (!FieldME->getType().isPODType(S.Context))
3129 AllPODFields = false;
3130
Richard Trieu3630c392014-11-21 03:10:30 +00003131 Base = SubME->getBase();
Richard Trieu1bc22c12013-09-13 03:20:53 +00003132 }
3133
Richard Trieu3630c392014-11-21 03:10:30 +00003134 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
Richard Trieufd687772013-09-16 20:46:50 +00003135 return;
3136
Richard Trieu2d779b92014-10-01 03:44:58 +00003137 if (AddressOf && AllPODFields)
3138 return;
3139
Richard Trieu406e65c2013-09-20 03:03:06 +00003140 ValueDecl* FoundVD = FieldME->getMemberDecl();
3141
Richard Trieu3630c392014-11-21 03:10:30 +00003142 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3143 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3144 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3145 }
3146
3147 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3148 QualType T = BaseCast->getType();
3149 if (T->isPointerType() &&
3150 BaseClasses.count(T->getPointeeType())) {
3151 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3152 << T->getPointeeType() << FoundVD;
3153 }
3154 }
3155 }
3156
Richard Trieuef64e942013-10-25 00:56:00 +00003157 if (!Decls.count(FoundVD))
Richard Trieu406e65c2013-09-20 03:03:06 +00003158 return;
3159
Richard Trieuef64e942013-10-25 00:56:00 +00003160 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieu406e65c2013-09-20 03:03:06 +00003161
Richard Trieufa1d0a72014-10-17 20:56:10 +00003162 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3163 // Special checking for initializer lists.
3164 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3165 return;
3166 }
3167 } else {
3168 // Prevent double warnings on use of unbounded references.
3169 if (CheckReferenceOnly && !IsReference)
3170 return;
3171 }
Richard Trieuef64e942013-10-25 00:56:00 +00003172
3173 unsigned diag = IsReference
3174 ? diag::warn_reference_field_is_uninit
3175 : diag::warn_field_is_uninit;
3176 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3177 if (Constructor)
3178 S.Diag(Constructor->getLocation(),
3179 diag::note_uninit_in_this_constructor)
3180 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3181
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003182 }
3183
Richard Trieu2d779b92014-10-01 03:44:58 +00003184 void HandleValue(Expr *E, bool AddressOf) {
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003185 E = E->IgnoreParens();
3186
3187 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003188 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3189 AddressOf /*AddressOf*/);
Nick Lewyckyc363afb2012-11-15 08:19:20 +00003190 return;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003191 }
3192
3193 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003194 Visit(CO->getCond());
3195 HandleValue(CO->getTrueExpr(), AddressOf);
3196 HandleValue(CO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003197 return;
3198 }
3199
3200 if (BinaryConditionalOperator *BCO =
3201 dyn_cast<BinaryConditionalOperator>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003202 Visit(BCO->getCond());
3203 HandleValue(BCO->getFalseExpr(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003204 return;
3205 }
3206
Richard Trieuabf6ec42014-08-27 22:15:10 +00003207 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003208 HandleValue(OVE->getSourceExpr(), AddressOf);
Richard Trieuabf6ec42014-08-27 22:15:10 +00003209 return;
3210 }
3211
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003212 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3213 switch (BO->getOpcode()) {
3214 default:
Richard Trieu2d779b92014-10-01 03:44:58 +00003215 break;
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003216 case(BO_PtrMemD):
3217 case(BO_PtrMemI):
Richard Trieu2d779b92014-10-01 03:44:58 +00003218 HandleValue(BO->getLHS(), AddressOf);
3219 Visit(BO->getRHS());
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003220 return;
3221 case(BO_Comma):
Richard Trieu2d779b92014-10-01 03:44:58 +00003222 Visit(BO->getLHS());
3223 HandleValue(BO->getRHS(), AddressOf);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003224 return;
3225 }
3226 }
Richard Trieu2d779b92014-10-01 03:44:58 +00003227
3228 Visit(E);
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003229 }
3230
Richard Trieufa1d0a72014-10-17 20:56:10 +00003231 void CheckInitListExpr(InitListExpr *ILE) {
3232 InitFieldIndex.push_back(0);
3233 for (auto Child : ILE->children()) {
3234 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3235 CheckInitListExpr(SubList);
3236 } else {
3237 Visit(Child);
3238 }
3239 ++InitFieldIndex.back();
3240 }
3241 InitFieldIndex.pop_back();
3242 }
3243
Richard Trieu8d08a272014-08-28 03:23:47 +00003244 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
Richard Trieu3630c392014-11-21 03:10:30 +00003245 FieldDecl *Field, const Type *BaseClass) {
Richard Trieu8d08a272014-08-28 03:23:47 +00003246 // Remove Decls that may have been initialized in the previous
3247 // initializer.
3248 for (ValueDecl* VD : DeclsToRemove)
3249 Decls.erase(VD);
Richard Trieu8d08a272014-08-28 03:23:47 +00003250 DeclsToRemove.clear();
Richard Trieufa1d0a72014-10-17 20:56:10 +00003251
Richard Trieu8d08a272014-08-28 03:23:47 +00003252 Constructor = FieldConstructor;
Richard Trieufa1d0a72014-10-17 20:56:10 +00003253 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3254
3255 if (ILE && Field) {
3256 InitList = true;
3257 InitListFieldDecl = Field;
3258 InitFieldIndex.clear();
3259 CheckInitListExpr(ILE);
3260 } else {
3261 InitList = false;
3262 Visit(E);
3263 }
3264
Richard Trieu8d08a272014-08-28 03:23:47 +00003265 if (Field)
3266 Decls.erase(Field);
Richard Trieu3630c392014-11-21 03:10:30 +00003267 if (BaseClass)
3268 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
Richard Trieu8d08a272014-08-28 03:23:47 +00003269 }
3270
Richard Trieu1bc22c12013-09-13 03:20:53 +00003271 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieuef64e942013-10-25 00:56:00 +00003272 // All uses of unbounded reference fields will warn.
Richard Trieu2d779b92014-10-01 03:44:58 +00003273 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
Richard Trieu1bc22c12013-09-13 03:20:53 +00003274 }
3275
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003276 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003277 if (E->getCastKind() == CK_LValueToRValue) {
3278 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3279 return;
3280 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003281
3282 Inherited::VisitImplicitCastExpr(E);
3283 }
3284
Richard Trieu1bc22c12013-09-13 03:20:53 +00003285 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieu4834ad22014-08-12 21:05:04 +00003286 if (E->getConstructor()->isCopyConstructor()) {
3287 Expr *ArgExpr = E->getArg(0);
Richard Trieu2d779b92014-10-01 03:44:58 +00003288 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3289 if (ILE->getNumInits() == 1)
3290 ArgExpr = ILE->getInit(0);
3291 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3292 if (ICE->getCastKind() == CK_NoOp)
Richard Trieu4834ad22014-08-12 21:05:04 +00003293 ArgExpr = ICE->getSubExpr();
Richard Trieu2d779b92014-10-01 03:44:58 +00003294 HandleValue(ArgExpr, false /*AddressOf*/);
3295 return;
Richard Trieu4834ad22014-08-12 21:05:04 +00003296 }
Richard Trieu1bc22c12013-09-13 03:20:53 +00003297 Inherited::VisitCXXConstructExpr(E);
3298 }
3299
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003300 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3301 Expr *Callee = E->getCallee();
Richard Trieu2d779b92014-10-01 03:44:58 +00003302 if (isa<MemberExpr>(Callee)) {
3303 HandleValue(Callee, false /*AddressOf*/);
Richard Trieu46847422014-11-01 00:46:54 +00003304 for (auto Arg : E->arguments())
3305 Visit(Arg);
Richard Trieu2d779b92014-10-01 03:44:58 +00003306 return;
3307 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003308
3309 Inherited::VisitCXXMemberCallExpr(E);
3310 }
Richard Trieu406e65c2013-09-20 03:03:06 +00003311
Richard Trieu11fd0792014-08-26 04:30:55 +00003312 void VisitCallExpr(CallExpr *E) {
3313 // Treat std::move as a use.
3314 if (E->getNumArgs() == 1) {
3315 if (FunctionDecl *FD = E->getDirectCallee()) {
Richard Trieuc321b932014-11-27 01:29:32 +00003316 if (FD->isInStdNamespace() && FD->getIdentifier() &&
3317 FD->getIdentifier()->isStr("move")) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003318 HandleValue(E->getArg(0), false /*AddressOf*/);
3319 return;
Richard Trieu11fd0792014-08-26 04:30:55 +00003320 }
3321 }
3322 }
3323
3324 Inherited::VisitCallExpr(E);
3325 }
3326
Richard Trieud4a01362014-10-31 21:10:22 +00003327 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3328 Expr *Callee = E->getCallee();
3329
3330 if (isa<UnresolvedLookupExpr>(Callee))
3331 return Inherited::VisitCXXOperatorCallExpr(E);
3332
3333 Visit(Callee);
3334 for (auto Arg : E->arguments())
3335 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3336 }
3337
Richard Trieu406e65c2013-09-20 03:03:06 +00003338 void VisitBinaryOperator(BinaryOperator *E) {
3339 // If a field assignment is detected, remove the field from the
3340 // uninitiailized field set.
3341 if (E->getOpcode() == BO_Assign)
3342 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3343 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieuef64e942013-10-25 00:56:00 +00003344 if (!FD->getType()->isReferenceType())
Richard Trieu8d08a272014-08-28 03:23:47 +00003345 DeclsToRemove.push_back(FD);
Richard Trieu406e65c2013-09-20 03:03:06 +00003346
Richard Trieu52b8b602014-09-25 01:15:40 +00003347 if (E->isCompoundAssignmentOp()) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003348 HandleValue(E->getLHS(), false /*AddressOf*/);
3349 Visit(E->getRHS());
3350 return;
Richard Trieu52b8b602014-09-25 01:15:40 +00003351 }
3352
Richard Trieu406e65c2013-09-20 03:03:06 +00003353 Inherited::VisitBinaryOperator(E);
3354 }
Richard Trieu52b8b602014-09-25 01:15:40 +00003355
3356 void VisitUnaryOperator(UnaryOperator *E) {
Richard Trieu2d779b92014-10-01 03:44:58 +00003357 if (E->isIncrementDecrementOp()) {
3358 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3359 return;
3360 }
3361 if (E->getOpcode() == UO_AddrOf) {
3362 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3363 HandleValue(ME->getBase(), true /*AddressOf*/);
3364 return;
3365 }
3366 }
Richard Trieu52b8b602014-09-25 01:15:40 +00003367
3368 Inherited::VisitUnaryOperator(E);
3369 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003370 };
Richard Trieuef64e942013-10-25 00:56:00 +00003371
3372 // Diagnose value-uses of fields to initialize themselves, e.g.
3373 // foo(foo)
3374 // where foo is not also a parameter to the constructor.
3375 // Also diagnose across field uninitialized use such as
3376 // x(y), y(x)
3377 // TODO: implement -Wuninitialized and fold this into that framework.
3378 static void DiagnoseUninitializedFields(
3379 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3380
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00003381 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3382 Constructor->getLocation())) {
Richard Trieuef64e942013-10-25 00:56:00 +00003383 return;
3384 }
3385
3386 if (Constructor->isInvalidDecl())
3387 return;
3388
3389 const CXXRecordDecl *RD = Constructor->getParent();
3390
Richard Trieu353a4b42014-10-22 05:21:59 +00003391 if (RD->getDescribedClassTemplate())
Richard Trieu277ace02014-10-22 02:52:00 +00003392 return;
3393
Richard Trieuef64e942013-10-25 00:56:00 +00003394 // Holds fields that are uninitialized.
3395 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3396
3397 // At the beginning, all fields are uninitialized.
Aaron Ballman629afae2014-03-07 19:56:05 +00003398 for (auto *I : RD->decls()) {
3399 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00003400 UninitializedFields.insert(FD);
Aaron Ballman629afae2014-03-07 19:56:05 +00003401 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieuef64e942013-10-25 00:56:00 +00003402 UninitializedFields.insert(IFD->getAnonField());
3403 }
3404 }
3405
Richard Trieu3630c392014-11-21 03:10:30 +00003406 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3407 for (auto I : RD->bases())
3408 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3409
3410 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00003411 return;
3412
3413 UninitializedFieldVisitor UninitializedChecker(SemaRef,
Richard Trieu3630c392014-11-21 03:10:30 +00003414 UninitializedFields,
3415 UninitializedBaseClasses);
Richard Trieu8d08a272014-08-28 03:23:47 +00003416
Aaron Ballman0ad78302014-03-13 17:34:31 +00003417 for (const auto *FieldInit : Constructor->inits()) {
Richard Trieu3630c392014-11-21 03:10:30 +00003418 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
Richard Trieu8d08a272014-08-28 03:23:47 +00003419 break;
3420
Aaron Ballman0ad78302014-03-13 17:34:31 +00003421 Expr *InitExpr = FieldInit->getInit();
Richard Trieu8d08a272014-08-28 03:23:47 +00003422 if (!InitExpr)
3423 continue;
Richard Trieuef64e942013-10-25 00:56:00 +00003424
Richard Trieu8d08a272014-08-28 03:23:47 +00003425 if (CXXDefaultInitExpr *Default =
3426 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3427 InitExpr = Default->getExpr();
3428 if (!InitExpr)
3429 continue;
3430 // In class initializers will point to the constructor.
3431 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
Richard Trieu3630c392014-11-21 03:10:30 +00003432 FieldInit->getAnyMember(),
3433 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00003434 } else {
3435 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
Richard Trieu3630c392014-11-21 03:10:30 +00003436 FieldInit->getAnyMember(),
3437 FieldInit->getBaseClass());
Richard Trieu8d08a272014-08-28 03:23:47 +00003438 }
Richard Trieuef64e942013-10-25 00:56:00 +00003439 }
Hans Wennborg44fd70a2012-09-18 15:58:06 +00003440 }
3441} // namespace
3442
Richard Smith74108172014-01-17 03:11:34 +00003443/// \brief Enter a new C++ default initializer scope. After calling this, the
3444/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3445/// parsing or instantiating the initializer failed.
3446void Sema::ActOnStartCXXInClassMemberInitializer() {
3447 // Create a synthetic function scope to represent the call to the constructor
3448 // that notionally surrounds a use of this initializer.
3449 PushFunctionScope();
3450}
3451
3452/// \brief This is invoked after parsing an in-class initializer for a
3453/// non-static C++ class member, and after instantiating an in-class initializer
3454/// in a class template. Such actions are deferred until the class is complete.
3455void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3456 SourceLocation InitLoc,
3457 Expr *InitExpr) {
3458 // Pop the notional constructor scope we created earlier.
Craig Topperc3ec1492014-05-26 06:22:03 +00003459 PopFunctionScopeInfo(nullptr, D);
Richard Smith74108172014-01-17 03:11:34 +00003460
David Majnemer87ff66c2014-12-13 11:34:16 +00003461 FieldDecl *FD = dyn_cast<FieldDecl>(D);
3462 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
Richard Smith2b013182012-06-10 03:12:00 +00003463 "must set init style when field is created");
Richard Smith938f40b2011-06-11 17:19:42 +00003464
3465 if (!InitExpr) {
David Majnemer87ff66c2014-12-13 11:34:16 +00003466 D->setInvalidDecl();
3467 if (FD)
3468 FD->removeInClassInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00003469 return;
3470 }
3471
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00003472 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3473 FD->setInvalidDecl();
3474 FD->removeInClassInitializer();
3475 return;
3476 }
3477
Richard Smith938f40b2011-06-11 17:19:42 +00003478 ExprResult Init = InitExpr;
Richard Smithd59b8322012-12-19 01:39:02 +00003479 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redleef474c2012-02-22 10:50:08 +00003480 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smith2b013182012-06-10 03:12:00 +00003481 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redleef474c2012-02-22 10:50:08 +00003482 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smith2b013182012-06-10 03:12:00 +00003483 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003484 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3485 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith938f40b2011-06-11 17:19:42 +00003486 if (Init.isInvalid()) {
3487 FD->setInvalidDecl();
3488 return;
3489 }
Richard Smith938f40b2011-06-11 17:19:42 +00003490 }
3491
Richard Smith945f8d32013-01-14 22:39:08 +00003492 // C++11 [class.base.init]p7:
Richard Smith938f40b2011-06-11 17:19:42 +00003493 // The initialization of each base and member constitutes a
3494 // full-expression.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003495 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
Richard Smith938f40b2011-06-11 17:19:42 +00003496 if (Init.isInvalid()) {
3497 FD->setInvalidDecl();
3498 return;
3499 }
3500
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003501 InitExpr = Init.get();
Richard Smith938f40b2011-06-11 17:19:42 +00003502
3503 FD->setInClassInitializer(InitExpr);
3504}
3505
Douglas Gregor15e77a22009-12-31 09:10:24 +00003506/// \brief Find the direct and/or virtual base specifiers that
3507/// correspond to the given base type, for use in base initialization
3508/// within a constructor.
3509static bool FindBaseInitializer(Sema &SemaRef,
3510 CXXRecordDecl *ClassDecl,
3511 QualType BaseType,
3512 const CXXBaseSpecifier *&DirectBaseSpec,
3513 const CXXBaseSpecifier *&VirtualBaseSpec) {
3514 // First, check for a direct base class.
Craig Topperc3ec1492014-05-26 06:22:03 +00003515 DirectBaseSpec = nullptr;
Aaron Ballman574705e2014-03-13 15:41:46 +00003516 for (const auto &Base : ClassDecl->bases()) {
3517 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00003518 // We found a direct base of this type. That's what we're
3519 // initializing.
Aaron Ballman574705e2014-03-13 15:41:46 +00003520 DirectBaseSpec = &Base;
Douglas Gregor15e77a22009-12-31 09:10:24 +00003521 break;
3522 }
3523 }
3524
3525 // Check for a virtual base class.
3526 // FIXME: We might be able to short-circuit this if we know in advance that
3527 // there are no virtual bases.
Craig Topperc3ec1492014-05-26 06:22:03 +00003528 VirtualBaseSpec = nullptr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00003529 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3530 // We haven't found a base yet; search the class hierarchy for a
3531 // virtual base class.
3532 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3533 /*DetectVirtual=*/false);
Richard Smith0f59cb32015-12-18 21:45:41 +00003534 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3535 SemaRef.Context.getTypeDeclType(ClassDecl),
Douglas Gregor15e77a22009-12-31 09:10:24 +00003536 BaseType, Paths)) {
3537 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3538 Path != Paths.end(); ++Path) {
3539 if (Path->back().Base->isVirtual()) {
3540 VirtualBaseSpec = Path->back().Base;
3541 break;
3542 }
3543 }
3544 }
3545 }
3546
3547 return DirectBaseSpec || VirtualBaseSpec;
3548}
3549
Sebastian Redla74948d2011-09-24 17:48:25 +00003550/// \brief Handle a C++ member initializer using braced-init-list syntax.
3551MemInitResult
3552Sema::ActOnMemInitializer(Decl *ConstructorD,
3553 Scope *S,
3554 CXXScopeSpec &SS,
3555 IdentifierInfo *MemberOrBase,
3556 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00003557 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00003558 SourceLocation IdLoc,
3559 Expr *InitList,
3560 SourceLocation EllipsisLoc) {
3561 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00003562 DS, IdLoc, InitList,
David Blaikie186a8892012-01-24 06:03:59 +00003563 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003564}
3565
3566/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00003567MemInitResult
John McCall48871652010-08-21 09:40:31 +00003568Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00003569 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003570 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00003571 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00003572 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00003573 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00003574 SourceLocation IdLoc,
3575 SourceLocation LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00003576 ArrayRef<Expr *> Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00003577 SourceLocation RParenLoc,
3578 SourceLocation EllipsisLoc) {
Benjamin Kramerc215e762012-08-24 11:54:20 +00003579 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenko139474d2013-05-09 23:51:52 +00003580 Args, RParenLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003581 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redla9351792012-02-11 23:51:47 +00003582 DS, IdLoc, List, EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00003583}
3584
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003585namespace {
3586
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00003587// Callback to only accept typo corrections that can be a valid C++ member
3588// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003589class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003590public:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003591 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3592 : ClassDecl(ClassDecl) {}
3593
Craig Toppera798a9d2014-03-02 09:32:10 +00003594 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003595 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3596 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3597 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003598 return isa<TypeDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003599 }
3600 return false;
3601 }
3602
Benjamin Kramer8bf44352013-07-24 15:28:33 +00003603private:
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003604 CXXRecordDecl *ClassDecl;
3605};
3606
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003607}
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003608
Sebastian Redla74948d2011-09-24 17:48:25 +00003609/// \brief Handle a C++ member initializer.
3610MemInitResult
3611Sema::BuildMemInitializer(Decl *ConstructorD,
3612 Scope *S,
3613 CXXScopeSpec &SS,
3614 IdentifierInfo *MemberOrBase,
3615 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00003616 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00003617 SourceLocation IdLoc,
Sebastian Redla9351792012-02-11 23:51:47 +00003618 Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00003619 SourceLocation EllipsisLoc) {
Kaelyn Takataa15a6dc2014-12-08 22:41:42 +00003620 ExprResult Res = CorrectDelayedTyposInExpr(Init);
3621 if (!Res.isUsable())
3622 return true;
3623 Init = Res.get();
3624
Douglas Gregor71a57182009-06-22 23:20:33 +00003625 if (!ConstructorD)
3626 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003627
Douglas Gregorc8c277a2009-08-24 11:57:43 +00003628 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00003629
3630 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003631 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00003632 if (!Constructor) {
3633 // The user wrote a constructor initializer on a function that is
3634 // not a C++ constructor. Ignore the error for now, because we may
3635 // have more member initializers coming; we'll diagnose it just
3636 // once in ActOnMemInitializers.
3637 return true;
3638 }
3639
3640 CXXRecordDecl *ClassDecl = Constructor->getParent();
3641
3642 // C++ [class.base.init]p2:
3643 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00003644 // constructor's class and, if not found in that scope, are looked
3645 // up in the scope containing the constructor's definition.
3646 // [Note: if the constructor's class contains a member with the
3647 // same name as a direct or virtual base class of the class, a
3648 // mem-initializer-id naming the member or base class and composed
3649 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00003650 // mem-initializer-id for the hidden base class may be specified
3651 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00003652 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00003653 // Look for a member, first.
Nico Weberaa0117c2014-11-12 03:44:43 +00003654 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
David Blaikieff7d47a2012-12-19 00:45:41 +00003655 if (!Result.empty()) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00003656 ValueDecl *Member;
David Blaikieff7d47a2012-12-19 00:45:41 +00003657 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3658 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00003659 if (EllipsisLoc.isValid())
3660 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla9351792012-02-11 23:51:47 +00003661 << MemberOrBase
3662 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00003663
Sebastian Redla9351792012-02-11 23:51:47 +00003664 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00003665 }
Francois Pichetd583da02010-12-04 09:14:42 +00003666 }
Douglas Gregore8381c02008-11-05 04:29:56 +00003667 }
Douglas Gregore8381c02008-11-05 04:29:56 +00003668 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00003669 QualType BaseType;
Craig Topperc3ec1492014-05-26 06:22:03 +00003670 TypeSourceInfo *TInfo = nullptr;
John McCallb5a0d312009-12-21 10:41:20 +00003671
3672 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00003673 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00003674 } else if (DS.getTypeSpecType() == TST_decltype) {
3675 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00003676 } else {
3677 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3678 LookupParsedName(R, S, &SS);
3679
3680 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3681 if (!TyD) {
3682 if (R.isAmbiguous()) return true;
3683
John McCallda6841b2010-04-09 19:01:14 +00003684 // We don't want access-control diagnostics here.
3685 R.suppressDiagnostics();
3686
Douglas Gregora3b624a2010-01-19 06:46:48 +00003687 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3688 bool NotUnknownSpecialization = false;
3689 DeclContext *DC = computeDeclContext(SS, false);
3690 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3691 NotUnknownSpecialization = !Record->hasAnyDependentBases();
3692
3693 if (!NotUnknownSpecialization) {
3694 // When the scope specifier can refer to a member of an unknown
3695 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00003696 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3697 SS.getWithLocInContext(Context),
3698 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00003699 if (BaseType.isNull())
3700 return true;
3701
Douglas Gregora3b624a2010-01-19 06:46:48 +00003702 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00003703 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00003704 }
3705 }
3706
Douglas Gregor15e77a22009-12-31 09:10:24 +00003707 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003708 TypoCorrection Corr;
Douglas Gregora3b624a2010-01-19 06:46:48 +00003709 if (R.empty() && BaseType.isNull() &&
Kaelyn Takata89c881b2014-10-27 18:07:29 +00003710 (Corr = CorrectTypo(
3711 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3712 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3713 CTK_ErrorRecovery, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003714 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00003715 // We have found a non-static data member with a similar
3716 // name to what was typed; complain and initialize that
3717 // member.
Richard Smithf9b15102013-08-17 00:46:16 +00003718 diagnoseTypo(Corr,
3719 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3720 << MemberOrBase << true);
Sebastian Redla9351792012-02-11 23:51:47 +00003721 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00003722 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00003723 const CXXBaseSpecifier *DirectBaseSpec;
3724 const CXXBaseSpecifier *VirtualBaseSpec;
3725 if (FindBaseInitializer(*this, ClassDecl,
3726 Context.getTypeDeclType(Type),
3727 DirectBaseSpec, VirtualBaseSpec)) {
3728 // We have found a direct or virtual base class with a
3729 // similar name to what was typed; complain and initialize
3730 // that base class.
Richard Smithf9b15102013-08-17 00:46:16 +00003731 diagnoseTypo(Corr,
3732 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3733 << MemberOrBase << false,
3734 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor43a08572010-01-07 00:26:25 +00003735
Richard Smithf9b15102013-08-17 00:46:16 +00003736 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3737 : VirtualBaseSpec;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003738 Diag(BaseSpec->getLocStart(),
Douglas Gregor43a08572010-01-07 00:26:25 +00003739 diag::note_base_class_specified_here)
3740 << BaseSpec->getType()
3741 << BaseSpec->getSourceRange();
3742
Douglas Gregor15e77a22009-12-31 09:10:24 +00003743 TyD = Type;
3744 }
3745 }
3746 }
3747
Douglas Gregora3b624a2010-01-19 06:46:48 +00003748 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00003749 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla9351792012-02-11 23:51:47 +00003750 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregor15e77a22009-12-31 09:10:24 +00003751 return true;
3752 }
John McCallb5a0d312009-12-21 10:41:20 +00003753 }
3754
Douglas Gregora3b624a2010-01-19 06:46:48 +00003755 if (BaseType.isNull()) {
3756 BaseType = Context.getTypeDeclType(TyD);
Nico Weber28309182014-11-12 03:52:25 +00003757 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
Richard Smith97047d82015-12-12 02:17:54 +00003758 if (SS.isSet()) {
Aaron Ballman4a979672014-01-03 13:56:08 +00003759 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3760 BaseType);
Richard Smith97047d82015-12-12 02:17:54 +00003761 TInfo = Context.CreateTypeSourceInfo(BaseType);
3762 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3763 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3764 TL.setElaboratedKeywordLoc(SourceLocation());
3765 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3766 }
John McCallb5a0d312009-12-21 10:41:20 +00003767 }
3768 }
Mike Stump11289f42009-09-09 15:08:12 +00003769
John McCallbcd03502009-12-07 02:54:59 +00003770 if (!TInfo)
3771 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00003772
Sebastian Redla9351792012-02-11 23:51:47 +00003773 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00003774}
3775
Chandler Carruth599deef2011-09-03 01:14:15 +00003776/// Checks a member initializer expression for cases where reference (or
3777/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00003778static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3779 Expr *Init,
3780 SourceLocation IdLoc) {
3781 QualType MemberTy = Member->getType();
3782
3783 // We only handle pointers and references currently.
3784 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3785 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3786 return;
3787
3788 const bool IsPointer = MemberTy->isPointerType();
3789 if (IsPointer) {
3790 if (const UnaryOperator *Op
3791 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3792 // The only case we're worried about with pointers requires taking the
3793 // address.
3794 if (Op->getOpcode() != UO_AddrOf)
3795 return;
3796
3797 Init = Op->getSubExpr();
3798 } else {
3799 // We only handle address-of expression initializers for pointers.
3800 return;
3801 }
3802 }
3803
Richard Smithe3b28bc2013-06-12 21:51:50 +00003804 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003805 // We only warn when referring to a non-reference parameter declaration.
3806 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3807 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00003808 return;
3809
3810 S.Diag(Init->getExprLoc(),
3811 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3812 : diag::warn_bind_ref_member_to_parameter)
3813 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003814 } else {
3815 // Other initializers are fine.
3816 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00003817 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00003818
3819 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3820 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00003821}
3822
John McCallfaf5fb42010-08-26 23:41:50 +00003823MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003824Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redla74948d2011-09-24 17:48:25 +00003825 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00003826 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3827 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3828 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00003829 "Member must be a FieldDecl or IndirectFieldDecl");
3830
Sebastian Redla9351792012-02-11 23:51:47 +00003831 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00003832 return true;
3833
Douglas Gregor266bb5f2010-11-05 22:21:31 +00003834 if (Member->isInvalidDecl())
3835 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00003836
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003837 MultiExprArg Args;
Sebastian Redla9351792012-02-11 23:51:47 +00003838 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003839 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithd59b8322012-12-19 01:39:02 +00003840 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003841 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithd59b8322012-12-19 01:39:02 +00003842 } else {
3843 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003844 Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00003845 }
Daniel Jasper0baec5492012-06-06 08:32:04 +00003846
Sebastian Redla9351792012-02-11 23:51:47 +00003847 SourceRange InitRange = Init->getSourceRange();
Eli Friedman8e1433b2009-07-29 19:44:27 +00003848
Sebastian Redla9351792012-02-11 23:51:47 +00003849 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003850 // Can't check initialization for a member of dependent type or when
3851 // any of the arguments are type-dependent expressions.
John McCall31168b02011-06-15 23:02:42 +00003852 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00003853 } else {
Sebastian Redl0501c632012-02-12 16:37:36 +00003854 bool InitList = false;
3855 if (isa<InitListExpr>(Init)) {
3856 InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003857 Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003858 }
3859
Chandler Carruthd44c3102010-12-06 09:23:57 +00003860 // Initialize the member.
3861 InitializedEntity MemberEntity =
Craig Topperc3ec1492014-05-26 06:22:03 +00003862 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3863 : InitializedEntity::InitializeMember(IndirectMember,
3864 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003865 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003866 InitList ? InitializationKind::CreateDirectList(IdLoc)
3867 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3868 InitRange.getEnd());
John McCallacf0ee52010-10-08 02:01:28 +00003869
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003870 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00003871 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3872 nullptr);
Chandler Carruthd44c3102010-12-06 09:23:57 +00003873 if (MemberInit.isInvalid())
3874 return true;
3875
Richard Smith736a9472013-06-12 20:42:33 +00003876 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3877
Richard Smith945f8d32013-01-14 22:39:08 +00003878 // C++11 [class.base.init]p7:
Chandler Carruthd44c3102010-12-06 09:23:57 +00003879 // The initialization of each base and member constitutes a
3880 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003881 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003882 if (MemberInit.isInvalid())
3883 return true;
3884
Richard Smithd59b8322012-12-19 01:39:02 +00003885 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003886 }
3887
Chandler Carruthd44c3102010-12-06 09:23:57 +00003888 if (DirectMember) {
Sebastian Redla9351792012-02-11 23:51:47 +00003889 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3890 InitRange.getBegin(), Init,
3891 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003892 } else {
Sebastian Redla9351792012-02-11 23:51:47 +00003893 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3894 InitRange.getBegin(), Init,
3895 InitRange.getEnd());
Chandler Carruthd44c3102010-12-06 09:23:57 +00003896 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00003897}
3898
John McCallfaf5fb42010-08-26 23:41:50 +00003899MemInitResult
Sebastian Redla9351792012-02-11 23:51:47 +00003900Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Alexis Huntc5575cc2011-02-26 19:13:13 +00003901 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003902 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003903 if (!LangOpts.CPlusPlus11)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003904 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003905 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003906 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00003907
Sebastian Redl0501c632012-02-12 16:37:36 +00003908 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003909 MultiExprArg Args = Init;
Sebastian Redl0501c632012-02-12 16:37:36 +00003910 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3911 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003912 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl0501c632012-02-12 16:37:36 +00003913 }
3914
Sebastian Redla9351792012-02-11 23:51:47 +00003915 SourceRange InitRange = Init->getSourceRange();
Alexis Huntc5575cc2011-02-26 19:13:13 +00003916 // Initialize the object.
3917 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3918 QualType(ClassDecl->getTypeForDecl(), 0));
3919 InitializationKind Kind =
Sebastian Redl0501c632012-02-12 16:37:36 +00003920 InitList ? InitializationKind::CreateDirectList(NameLoc)
3921 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3922 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003923 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redla9351792012-02-11 23:51:47 +00003924 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Craig Topperc3ec1492014-05-26 06:22:03 +00003925 Args, nullptr);
Alexis Huntc5575cc2011-02-26 19:13:13 +00003926 if (DelegationInit.isInvalid())
3927 return true;
3928
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00003929 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3930 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00003931
Richard Smith945f8d32013-01-14 22:39:08 +00003932 // C++11 [class.base.init]p7:
Alexis Huntc5575cc2011-02-26 19:13:13 +00003933 // The initialization of each base and member constitutes a
3934 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00003935 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3936 InitRange.getBegin());
Alexis Huntc5575cc2011-02-26 19:13:13 +00003937 if (DelegationInit.isInvalid())
3938 return true;
3939
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00003940 // If we are in a dependent context, template instantiation will
3941 // perform this type-checking again. Just save the arguments that we
3942 // received in a ParenListExpr.
3943 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3944 // of the information that we have about the base
3945 // initializer. However, deconstructing the ASTs is a dicey process,
3946 // and this approach is far more likely to get the corner cases right.
3947 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003948 DelegationInit = Init;
Eli Friedmana9e9ebc2012-05-19 23:35:23 +00003949
Sebastian Redla9351792012-02-11 23:51:47 +00003950 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003951 DelegationInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00003952 InitRange.getEnd());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003953}
3954
3955MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00003956Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla9351792012-02-11 23:51:47 +00003957 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor44e7df62011-01-04 00:32:56 +00003958 SourceLocation EllipsisLoc) {
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003959 SourceLocation BaseLoc
3960 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00003961
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003962 if (!BaseType->isDependentType() && !BaseType->isRecordType())
3963 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3964 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3965
3966 // C++ [class.base.init]p2:
3967 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00003968 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003969 // of that class, the mem-initializer is ill-formed. A
3970 // mem-initializer-list can initialize a base class using any
3971 // name that denotes that base class type.
Sebastian Redla9351792012-02-11 23:51:47 +00003972 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003973
Sebastian Redla9351792012-02-11 23:51:47 +00003974 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor44e7df62011-01-04 00:32:56 +00003975 if (EllipsisLoc.isValid()) {
3976 // This is a pack expansion.
3977 if (!BaseType->containsUnexpandedParameterPack()) {
3978 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla9351792012-02-11 23:51:47 +00003979 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redla74948d2011-09-24 17:48:25 +00003980
Douglas Gregor44e7df62011-01-04 00:32:56 +00003981 EllipsisLoc = SourceLocation();
3982 }
3983 } else {
3984 // Check for any unexpanded parameter packs.
3985 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3986 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00003987
Sebastian Redla9351792012-02-11 23:51:47 +00003988 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redla74948d2011-09-24 17:48:25 +00003989 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00003990 }
Sebastian Redla74948d2011-09-24 17:48:25 +00003991
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003992 // Check for direct and virtual base classes.
Craig Topperc3ec1492014-05-26 06:22:03 +00003993 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3994 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
Douglas Gregor1c69bf02010-06-16 16:03:14 +00003995 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003996 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3997 BaseType))
Sebastian Redla9351792012-02-11 23:51:47 +00003998 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00003999
Douglas Gregor1c69bf02010-06-16 16:03:14 +00004000 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4001 VirtualBaseSpec);
4002
4003 // C++ [base.class.init]p2:
4004 // Unless the mem-initializer-id names a nonstatic data member of the
4005 // constructor's class or a direct or virtual base of that class, the
4006 // mem-initializer is ill-formed.
4007 if (!DirectBaseSpec && !VirtualBaseSpec) {
4008 // If the class has any dependent bases, then it's possible that
4009 // one of those types will resolve to the same type as
4010 // BaseType. Therefore, just treat this as a dependent base
4011 // class initialization. FIXME: Should we try to check the
4012 // initialization anyway? It seems odd.
4013 if (ClassDecl->hasAnyDependentBases())
4014 Dependent = true;
4015 else
4016 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4017 << BaseType << Context.getTypeDeclType(ClassDecl)
4018 << BaseTInfo->getTypeLoc().getLocalSourceRange();
4019 }
4020 }
4021
4022 if (Dependent) {
John McCall31168b02011-06-15 23:02:42 +00004023 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00004024
Sebastian Redla74948d2011-09-24 17:48:25 +00004025 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4026 /*IsVirtual=*/false,
Sebastian Redla9351792012-02-11 23:51:47 +00004027 InitRange.getBegin(), Init,
4028 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00004029 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004030
4031 // C++ [base.class.init]p2:
4032 // If a mem-initializer-id is ambiguous because it designates both
4033 // a direct non-virtual base class and an inherited virtual base
4034 // class, the mem-initializer is ill-formed.
4035 if (DirectBaseSpec && VirtualBaseSpec)
4036 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00004037 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004038
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004039 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004040 if (!BaseSpec)
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004041 BaseSpec = VirtualBaseSpec;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004042
4043 // Initialize the base.
Sebastian Redl0501c632012-02-12 16:37:36 +00004044 bool InitList = true;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004045 MultiExprArg Args = Init;
Sebastian Redla9351792012-02-11 23:51:47 +00004046 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl0501c632012-02-12 16:37:36 +00004047 InitList = false;
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004048 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redla9351792012-02-11 23:51:47 +00004049 }
Sebastian Redl0501c632012-02-12 16:37:36 +00004050
4051 InitializedEntity BaseEntity =
4052 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4053 InitializationKind Kind =
4054 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4055 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4056 InitRange.getEnd());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004057 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
Craig Topperc3ec1492014-05-26 06:22:03 +00004058 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004059 if (BaseInit.isInvalid())
4060 return true;
John McCallacf0ee52010-10-08 02:01:28 +00004061
Richard Smith945f8d32013-01-14 22:39:08 +00004062 // C++11 [class.base.init]p7:
4063 // The initialization of each base and member constitutes a
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004064 // full-expression.
Richard Smith945f8d32013-01-14 22:39:08 +00004065 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004066 if (BaseInit.isInvalid())
4067 return true;
4068
4069 // If we are in a dependent context, template instantiation will
4070 // perform this type-checking again. Just save the arguments that we
4071 // received in a ParenListExpr.
4072 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4073 // of the information that we have about the base
4074 // initializer. However, deconstructing the ASTs is a dicey process,
4075 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00004076 if (CurContext->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004077 BaseInit = Init;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004078
Alexis Hunt1d792652011-01-08 20:30:50 +00004079 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00004080 BaseSpec->isVirtual(),
Sebastian Redla9351792012-02-11 23:51:47 +00004081 InitRange.getBegin(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004082 BaseInit.getAs<Expr>(),
Sebastian Redla9351792012-02-11 23:51:47 +00004083 InitRange.getEnd(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00004084}
4085
Sebastian Redl22653ba2011-08-30 19:58:05 +00004086// Create a static_cast\<T&&>(expr).
Richard Smithc2bc61b2013-03-18 21:12:30 +00004087static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4088 if (T.isNull()) T = E->getType();
4089 QualType TargetType = SemaRef.BuildReferenceType(
4090 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004091 SourceLocation ExprLoc = E->getLocStart();
4092 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4093 TargetType, ExprLoc);
4094
4095 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4096 SourceRange(ExprLoc, ExprLoc),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004097 E->getSourceRange()).get();
Sebastian Redl22653ba2011-08-30 19:58:05 +00004098}
4099
Anders Carlsson1b00e242010-04-23 03:10:23 +00004100/// ImplicitInitializerKind - How an implicit base or member initializer should
4101/// initialize its base or member.
4102enum ImplicitInitializerKind {
4103 IIK_Default,
4104 IIK_Copy,
Richard Smithc2bc61b2013-03-18 21:12:30 +00004105 IIK_Move,
4106 IIK_Inherit
Anders Carlsson1b00e242010-04-23 03:10:23 +00004107};
4108
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004109static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00004110BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00004111 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00004112 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004113 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00004114 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004115 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00004116 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4117 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004118
John McCalldadc5752010-08-24 06:29:42 +00004119 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00004120
4121 switch (ImplicitInitKind) {
Richard Smith5179eb72016-06-28 19:03:57 +00004122 case IIK_Inherit:
Anders Carlsson1b00e242010-04-23 03:10:23 +00004123 case IIK_Default: {
4124 InitializationKind InitKind
4125 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +00004126 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4127 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlsson1b00e242010-04-23 03:10:23 +00004128 break;
4129 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004130
Sebastian Redl22653ba2011-08-30 19:58:05 +00004131 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00004132 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004133 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00004134 ParmVarDecl *Param = Constructor->getParamDecl(0);
4135 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00004136
Anders Carlsson1b00e242010-04-23 03:10:23 +00004137 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00004138 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00004139 SourceLocation(), Param, false,
John McCall7decc9e2010-11-18 06:31:45 +00004140 Constructor->getLocation(), ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00004141 VK_LValue, nullptr);
Sebastian Redl22653ba2011-08-30 19:58:05 +00004142
Eli Friedmanfa0df832012-02-02 03:46:19 +00004143 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4144
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00004145 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00004146 QualType ArgTy =
4147 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4148 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00004149
Sebastian Redl22653ba2011-08-30 19:58:05 +00004150 if (Moving) {
4151 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4152 }
4153
John McCallcf142162010-08-07 06:22:56 +00004154 CXXCastPath BasePath;
4155 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00004156 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4157 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00004158 Moving ? VK_XValue : VK_LValue,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004159 &BasePath).get();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00004160
Anders Carlsson1b00e242010-04-23 03:10:23 +00004161 InitializationKind InitKind
4162 = InitializationKind::CreateDirect(Constructor->getLocation(),
4163 SourceLocation(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004164 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4165 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlsson1b00e242010-04-23 03:10:23 +00004166 break;
4167 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00004168 }
John McCallb268a282010-08-23 23:25:46 +00004169
Douglas Gregora40433a2010-12-07 00:41:46 +00004170 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004171 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004172 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004173
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004174 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00004175 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004176 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4177 SourceLocation()),
4178 BaseSpec->isVirtual(),
4179 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004180 BaseInit.getAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004181 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004182 SourceLocation());
4183
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004184 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004185}
4186
Sebastian Redl22653ba2011-08-30 19:58:05 +00004187static bool RefersToRValueRef(Expr *MemRef) {
4188 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4189 return Referenced->getType()->isRValueReferenceType();
4190}
4191
Anders Carlsson3c1db572010-04-23 02:15:47 +00004192static bool
4193BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00004194 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00004195 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00004196 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00004197 if (Field->isInvalidDecl())
4198 return true;
4199
Chandler Carruth9c9286b2010-06-29 23:50:44 +00004200 SourceLocation Loc = Constructor->getLocation();
4201
Sebastian Redl22653ba2011-08-30 19:58:05 +00004202 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4203 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00004204 ParmVarDecl *Param = Constructor->getParamDecl(0);
4205 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00004206
4207 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00004208 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
4209 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004210
Anders Carlsson423f5d82010-04-23 16:04:08 +00004211 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00004212 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00004213 SourceLocation(), Param, false,
Craig Topperc3ec1492014-05-26 06:22:03 +00004214 Loc, ParamType, VK_LValue, nullptr);
Douglas Gregor94f9a482010-05-05 05:51:00 +00004215
Eli Friedmanfa0df832012-02-02 03:46:19 +00004216 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4217
Sebastian Redl22653ba2011-08-30 19:58:05 +00004218 if (Moving) {
4219 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4220 }
4221
Douglas Gregor94f9a482010-05-05 05:51:00 +00004222 // Build a reference to this field within the parameter.
4223 CXXScopeSpec SS;
4224 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4225 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00004226 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4227 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00004228 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00004229 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00004230 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00004231 ParamType, Loc,
4232 /*IsArrow=*/false,
4233 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00004234 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00004235 /*FirstQualifierInScope=*/nullptr,
Douglas Gregor94f9a482010-05-05 05:51:00 +00004236 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00004237 /*TemplateArgs=*/nullptr,
4238 /*S*/nullptr);
Sebastian Redle9c4e842011-09-04 18:14:28 +00004239 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00004240 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004241
4242 // C++11 [class.copy]p15:
4243 // - if a member m has rvalue reference type T&&, it is direct-initialized
4244 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00004245 if (RefersToRValueRef(CtorArg.get())) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004246 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +00004247 }
4248
Richard Smith30e304e2016-12-14 00:03:17 +00004249 InitializedEntity Entity =
4250 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4251 /*Implicit*/ true)
4252 : InitializedEntity::InitializeMember(Field, nullptr,
4253 /*Implicit*/ true);
Sebastian Redle9c4e842011-09-04 18:14:28 +00004254
Douglas Gregor94f9a482010-05-05 05:51:00 +00004255 // Direct-initialize to use the copy constructor.
4256 InitializationKind InitKind =
4257 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4258
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004259 Expr *CtorArgE = CtorArg.getAs<Expr>();
Richard Smith30e304e2016-12-14 00:03:17 +00004260 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4261 ExprResult MemberInit =
4262 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00004263 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00004264 if (MemberInit.isInvalid())
4265 return true;
4266
Richard Smith30e304e2016-12-14 00:03:17 +00004267 if (Indirect)
4268 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4269 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4270 else
4271 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4272 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
Anders Carlsson1b00e242010-04-23 03:10:23 +00004273 return false;
4274 }
4275
Richard Smithc2bc61b2013-03-18 21:12:30 +00004276 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4277 "Unhandled implicit init kind!");
Anders Carlsson423f5d82010-04-23 16:04:08 +00004278
Anders Carlsson3c1db572010-04-23 02:15:47 +00004279 QualType FieldBaseElementType =
4280 SemaRef.Context.getBaseElementType(Field->getType());
4281
Anders Carlsson3c1db572010-04-23 02:15:47 +00004282 if (FieldBaseElementType->isRecordType()) {
Richard Smith30e304e2016-12-14 00:03:17 +00004283 InitializedEntity InitEntity =
4284 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4285 /*Implicit*/ true)
4286 : InitializedEntity::InitializeMember(Field, nullptr,
4287 /*Implicit*/ true);
Anders Carlsson423f5d82010-04-23 16:04:08 +00004288 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00004289 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00004290
4291 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4292 ExprResult MemberInit =
4293 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCallb268a282010-08-23 23:25:46 +00004294
Douglas Gregora40433a2010-12-07 00:41:46 +00004295 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00004296 if (MemberInit.isInvalid())
4297 return true;
4298
Douglas Gregor493627b2011-08-10 15:22:55 +00004299 if (Indirect)
4300 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4301 Indirect, Loc,
4302 Loc,
4303 MemberInit.get(),
4304 Loc);
4305 else
4306 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4307 Field, Loc, Loc,
4308 MemberInit.get(),
4309 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00004310 return false;
4311 }
Anders Carlssondca6be02010-04-23 03:07:47 +00004312
Alexis Hunt8b455182011-05-17 00:19:05 +00004313 if (!Field->getParent()->isUnion()) {
4314 if (FieldBaseElementType->isReferenceType()) {
4315 SemaRef.Diag(Constructor->getLocation(),
4316 diag::err_uninitialized_member_in_ctor)
4317 << (int)Constructor->isImplicit()
4318 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4319 << 0 << Field->getDeclName();
4320 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4321 return true;
4322 }
Anders Carlssondca6be02010-04-23 03:07:47 +00004323
Alexis Hunt8b455182011-05-17 00:19:05 +00004324 if (FieldBaseElementType.isConstQualified()) {
4325 SemaRef.Diag(Constructor->getLocation(),
4326 diag::err_uninitialized_member_in_ctor)
4327 << (int)Constructor->isImplicit()
4328 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4329 << 1 << Field->getDeclName();
4330 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4331 return true;
4332 }
Anders Carlssondca6be02010-04-23 03:07:47 +00004333 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00004334
David Blaikiebbafb8a2012-03-11 07:00:24 +00004335 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00004336 FieldBaseElementType->isObjCRetainableType() &&
4337 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
4338 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor6fa69422012-07-23 04:23:39 +00004339 // ARC:
John McCall31168b02011-06-15 23:02:42 +00004340 // Default-initialize Objective-C pointers to NULL.
4341 CXXMemberInit
4342 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4343 Loc, Loc,
4344 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4345 Loc);
4346 return false;
4347 }
4348
Anders Carlsson3c1db572010-04-23 02:15:47 +00004349 // Nothing to initialize.
Craig Topperc3ec1492014-05-26 06:22:03 +00004350 CXXMemberInit = nullptr;
Anders Carlsson3c1db572010-04-23 02:15:47 +00004351 return false;
4352}
John McCallbc83b3f2010-05-20 23:23:51 +00004353
4354namespace {
4355struct BaseAndFieldInfo {
4356 Sema &S;
4357 CXXConstructorDecl *Ctor;
4358 bool AnyErrorsInInits;
4359 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00004360 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004361 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Richard Smithab44d5b2013-12-10 08:25:00 +00004362 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallbc83b3f2010-05-20 23:23:51 +00004363
4364 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4365 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004366 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
Richard Smith5179eb72016-06-28 19:03:57 +00004367 if (Ctor->getInheritedConstructor())
4368 IIK = IIK_Inherit;
4369 else if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00004370 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00004371 else if (Generated && Ctor->isMoveConstructor())
4372 IIK = IIK_Move;
John McCallbc83b3f2010-05-20 23:23:51 +00004373 else
4374 IIK = IIK_Default;
4375 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00004376
4377 bool isImplicitCopyOrMove() const {
4378 switch (IIK) {
4379 case IIK_Copy:
4380 case IIK_Move:
4381 return true;
4382
4383 case IIK_Default:
Richard Smithc2bc61b2013-03-18 21:12:30 +00004384 case IIK_Inherit:
Douglas Gregor7db3e952011-11-28 20:03:15 +00004385 return false;
4386 }
David Blaikiee4d798f2012-01-20 21:50:17 +00004387
4388 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00004389 }
Richard Smith0a8cfc72012-08-07 21:30:42 +00004390
4391 bool addFieldInitializer(CXXCtorInitializer *Init) {
4392 AllToInit.push_back(Init);
4393
4394 // Check whether this initializer makes the field "used".
Richard Smith852c9db2013-04-20 22:23:05 +00004395 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0a8cfc72012-08-07 21:30:42 +00004396 S.UnusedPrivateFields.remove(Init->getAnyMember());
4397
4398 return false;
4399 }
John McCallbc83b3f2010-05-20 23:23:51 +00004400
Richard Smithab44d5b2013-12-10 08:25:00 +00004401 bool isInactiveUnionMember(FieldDecl *Field) {
4402 RecordDecl *Record = Field->getParent();
4403 if (!Record->isUnion())
4404 return false;
4405
Richard Smith8d183852013-12-10 20:56:03 +00004406 if (FieldDecl *Active =
4407 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
Richard Smithab44d5b2013-12-10 08:25:00 +00004408 return Active != Field->getCanonicalDecl();
4409
4410 // In an implicit copy or move constructor, ignore any in-class initializer.
4411 if (isImplicitCopyOrMove())
4412 return true;
4413
4414 // If there's no explicit initialization, the field is active only if it
4415 // has an in-class initializer...
4416 if (Field->hasInClassInitializer())
4417 return false;
4418 // ... or it's an anonymous struct or union whose class has an in-class
4419 // initializer.
4420 if (!Field->isAnonymousStructOrUnion())
4421 return true;
4422 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4423 return !FieldRD->hasInClassInitializer();
4424 }
4425
4426 /// \brief Determine whether the given field is, or is within, a union member
4427 /// that is inactive (because there was an initializer given for a different
4428 /// member of the union, or because the union was not initialized at all).
4429 bool isWithinInactiveUnionMember(FieldDecl *Field,
4430 IndirectFieldDecl *Indirect) {
4431 if (!Indirect)
4432 return isInactiveUnionMember(Field);
4433
Aaron Ballman29c94602014-03-07 18:36:15 +00004434 for (auto *C : Indirect->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004435 FieldDecl *Field = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00004436 if (Field && isInactiveUnionMember(Field))
Richard Smithc94ec842011-09-19 13:34:43 +00004437 return true;
Richard Smithab44d5b2013-12-10 08:25:00 +00004438 }
4439 return false;
4440 }
4441};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004442}
Richard Smithc94ec842011-09-19 13:34:43 +00004443
Douglas Gregor10f939c2011-11-02 23:04:16 +00004444/// \brief Determine whether the given type is an incomplete or zero-lenfgth
4445/// array type.
4446static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4447 if (T->isIncompleteArrayType())
4448 return true;
4449
4450 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4451 if (!ArrayT->getSize())
4452 return true;
4453
4454 T = ArrayT->getElementType();
4455 }
4456
4457 return false;
4458}
4459
Richard Smith938f40b2011-06-11 17:19:42 +00004460static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00004461 FieldDecl *Field,
Craig Topperc3ec1492014-05-26 06:22:03 +00004462 IndirectFieldDecl *Indirect = nullptr) {
Eli Friedmanb13e64e2013-06-28 21:07:41 +00004463 if (Field->isInvalidDecl())
4464 return false;
John McCallbc83b3f2010-05-20 23:23:51 +00004465
Chandler Carruth139e9622010-06-30 02:59:29 +00004466 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smithcd45dbc2014-04-19 03:48:30 +00004467 if (CXXCtorInitializer *Init =
4468 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
Richard Smith0a8cfc72012-08-07 21:30:42 +00004469 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00004470
Richard Smithab44d5b2013-12-10 08:25:00 +00004471 // C++11 [class.base.init]p8:
4472 // if the entity is a non-static data member that has a
4473 // brace-or-equal-initializer and either
4474 // -- the constructor's class is a union and no other variant member of that
4475 // union is designated by a mem-initializer-id or
4476 // -- the constructor's class is not a union, and, if the entity is a member
4477 // of an anonymous union, no other member of that union is designated by
4478 // a mem-initializer-id,
4479 // the entity is initialized as specified in [dcl.init].
4480 //
4481 // We also apply the same rules to handle anonymous structs within anonymous
4482 // unions.
4483 if (Info.isWithinInactiveUnionMember(Field, Indirect))
4484 return false;
4485
Douglas Gregor7db3e952011-11-28 20:03:15 +00004486 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Reid Klecknerd60b82f2014-11-17 23:36:45 +00004487 ExprResult DIE =
4488 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4489 if (DIE.isInvalid())
4490 return true;
Douglas Gregor493627b2011-08-10 15:22:55 +00004491 CXXCtorInitializer *Init;
4492 if (Indirect)
Reid Klecknerd60b82f2014-11-17 23:36:45 +00004493 Init = new (SemaRef.Context)
4494 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4495 SourceLocation(), DIE.get(), SourceLocation());
Douglas Gregor493627b2011-08-10 15:22:55 +00004496 else
Reid Klecknerd60b82f2014-11-17 23:36:45 +00004497 Init = new (SemaRef.Context)
4498 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4499 SourceLocation(), DIE.get(), SourceLocation());
Richard Smith0a8cfc72012-08-07 21:30:42 +00004500 return Info.addFieldInitializer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00004501 }
4502
Douglas Gregor10f939c2011-11-02 23:04:16 +00004503 // Don't initialize incomplete or zero-length arrays.
4504 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4505 return false;
4506
John McCallbc83b3f2010-05-20 23:23:51 +00004507 // Don't try to build an implicit initializer if there were semantic
4508 // errors in any of the initializers (and therefore we might be
4509 // missing some that the user actually wrote).
Eli Friedmanb13e64e2013-06-28 21:07:41 +00004510 if (Info.AnyErrorsInInits)
John McCallbc83b3f2010-05-20 23:23:51 +00004511 return false;
4512
Craig Topperc3ec1492014-05-26 06:22:03 +00004513 CXXCtorInitializer *Init = nullptr;
Douglas Gregor493627b2011-08-10 15:22:55 +00004514 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4515 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00004516 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00004517
Richard Smith0a8cfc72012-08-07 21:30:42 +00004518 if (!Init)
4519 return false;
Francois Pichetd583da02010-12-04 09:14:42 +00004520
Richard Smith0a8cfc72012-08-07 21:30:42 +00004521 return Info.addFieldInitializer(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00004522}
Alexis Hunt61bc1732011-05-01 07:04:31 +00004523
4524bool
4525Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4526 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00004527 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00004528 Constructor->setNumCtorInitializers(1);
4529 CXXCtorInitializer **initializer =
4530 new (Context) CXXCtorInitializer*[1];
4531 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4532 Constructor->setCtorInitializers(initializer);
4533
Alexis Hunt9d47faf2011-05-03 23:05:34 +00004534 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00004535 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00004536 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4537 }
4538
Alexis Hunte2622992011-05-05 00:05:47 +00004539 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00004540
Richard Trieu8a0c9e62014-09-12 22:47:58 +00004541 DiagnoseUninitializedFields(*this, Constructor);
4542
Alexis Hunt61bc1732011-05-01 07:04:31 +00004543 return false;
4544}
Douglas Gregor493627b2011-08-10 15:22:55 +00004545
David Blaikie3fc2f912013-01-17 05:26:25 +00004546bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4547 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregor52235292011-09-22 23:04:35 +00004548 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004549 // Just store the initializers as written, they will be checked during
4550 // instantiation.
David Blaikie3fc2f912013-01-17 05:26:25 +00004551 if (!Initializers.empty()) {
4552 Constructor->setNumCtorInitializers(Initializers.size());
Alexis Hunt1d792652011-01-08 20:30:50 +00004553 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie3fc2f912013-01-17 05:26:25 +00004554 new (Context) CXXCtorInitializer*[Initializers.size()];
4555 memcpy(baseOrMemberInitializers, Initializers.data(),
4556 Initializers.size() * sizeof(CXXCtorInitializer*));
Alexis Hunt1d792652011-01-08 20:30:50 +00004557 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00004558 }
Richard Smith60f2e1e2012-09-25 00:23:05 +00004559
4560 // Let template instantiation know whether we had errors.
4561 if (AnyErrors)
4562 Constructor->setInvalidDecl();
4563
Anders Carlssondb0a9652010-04-02 06:26:44 +00004564 return false;
4565 }
4566
John McCallbc83b3f2010-05-20 23:23:51 +00004567 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00004568
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004569 // We need to build the initializer AST according to order of construction
4570 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004571 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00004572 if (!ClassDecl)
4573 return true;
4574
Eli Friedman9cf6b592009-11-09 19:20:36 +00004575 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00004576
David Blaikie3fc2f912013-01-17 05:26:25 +00004577 for (unsigned i = 0; i < Initializers.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004578 CXXCtorInitializer *Member = Initializers[i];
Richard Smithbc46e432013-07-22 02:56:56 +00004579
Anders Carlssondb0a9652010-04-02 06:26:44 +00004580 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00004581 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00004582 else {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004583 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
Richard Smithab44d5b2013-12-10 08:25:00 +00004584
4585 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
Aaron Ballman29c94602014-03-07 18:36:15 +00004586 for (auto *C : F->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004587 FieldDecl *FD = dyn_cast<FieldDecl>(C);
Richard Smithab44d5b2013-12-10 08:25:00 +00004588 if (FD && FD->getParent()->isUnion())
4589 Info.ActiveUnionMember.insert(std::make_pair(
4590 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4591 }
4592 } else if (FieldDecl *FD = Member->getMember()) {
4593 if (FD->getParent()->isUnion())
4594 Info.ActiveUnionMember.insert(std::make_pair(
4595 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4596 }
4597 }
Anders Carlssondb0a9652010-04-02 06:26:44 +00004598 }
4599
Anders Carlsson43c64af2010-04-21 19:52:01 +00004600 // Keep track of the direct virtual bases.
4601 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00004602 for (auto &I : ClassDecl->bases()) {
4603 if (I.isVirtual())
4604 DirectVBases.insert(&I);
Anders Carlsson43c64af2010-04-21 19:52:01 +00004605 }
4606
Anders Carlssondb0a9652010-04-02 06:26:44 +00004607 // Push virtual bases before others.
Aaron Ballman445a9392014-03-13 16:15:17 +00004608 for (auto &VBase : ClassDecl->vbases()) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004609 if (CXXCtorInitializer *Value
Aaron Ballman445a9392014-03-13 16:15:17 +00004610 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithbc46e432013-07-22 02:56:56 +00004611 // [class.base.init]p7, per DR257:
4612 // A mem-initializer where the mem-initializer-id names a virtual base
4613 // class is ignored during execution of a constructor of any class that
4614 // is not the most derived class.
4615 if (ClassDecl->isAbstract()) {
4616 // FIXME: Provide a fixit to remove the base specifier. This requires
4617 // tracking the location of the associated comma for a base specifier.
4618 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Aaron Ballman445a9392014-03-13 16:15:17 +00004619 << VBase.getType() << ClassDecl;
Richard Smithbc46e432013-07-22 02:56:56 +00004620 DiagnoseAbstractType(ClassDecl);
4621 }
4622
John McCallbc83b3f2010-05-20 23:23:51 +00004623 Info.AllToInit.push_back(Value);
Richard Smithbc46e432013-07-22 02:56:56 +00004624 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4625 // [class.base.init]p8, per DR257:
4626 // If a given [...] base class is not named by a mem-initializer-id
4627 // [...] and the entity is not a virtual base class of an abstract
4628 // class, then [...] the entity is default-initialized.
Aaron Ballman445a9392014-03-13 16:15:17 +00004629 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00004630 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00004631 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman445a9392014-03-13 16:15:17 +00004632 &VBase, IsInheritedVirtualBase,
Anders Carlsson1b00e242010-04-23 03:10:23 +00004633 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004634 HadError = true;
4635 continue;
4636 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00004637
John McCallbc83b3f2010-05-20 23:23:51 +00004638 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004639 }
4640 }
Mike Stump11289f42009-09-09 15:08:12 +00004641
John McCallbc83b3f2010-05-20 23:23:51 +00004642 // Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004643 for (auto &Base : ClassDecl->bases()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004644 // Virtuals are in the virtual base list and already constructed.
Aaron Ballman574705e2014-03-13 15:41:46 +00004645 if (Base.isVirtual())
Anders Carlssondb0a9652010-04-02 06:26:44 +00004646 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004647
Alexis Hunt1d792652011-01-08 20:30:50 +00004648 if (CXXCtorInitializer *Value
Aaron Ballman574705e2014-03-13 15:41:46 +00004649 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallbc83b3f2010-05-20 23:23:51 +00004650 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00004651 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004652 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00004653 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Aaron Ballman574705e2014-03-13 15:41:46 +00004654 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00004655 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00004656 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004657 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00004658 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00004659
John McCallbc83b3f2010-05-20 23:23:51 +00004660 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004661 }
4662 }
Mike Stump11289f42009-09-09 15:08:12 +00004663
John McCallbc83b3f2010-05-20 23:23:51 +00004664 // Fields.
Aaron Ballman629afae2014-03-07 19:56:05 +00004665 for (auto *Mem : ClassDecl->decls()) {
4666 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004667 // C++ [class.bit]p2:
4668 // A declaration for a bit-field that omits the identifier declares an
4669 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
4670 // initialized.
4671 if (F->isUnnamedBitfield())
4672 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004673
Sebastian Redl22653ba2011-08-30 19:58:05 +00004674 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00004675 // handle anonymous struct/union fields based on their individual
4676 // indirect fields.
Richard Smithc2bc61b2013-03-18 21:12:30 +00004677 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00004678 continue;
4679
4680 if (CollectFieldInitializer(*this, Info, F))
4681 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004682 continue;
4683 }
Douglas Gregor493627b2011-08-10 15:22:55 +00004684
4685 // Beyond this point, we only consider default initialization.
Richard Smithc2bc61b2013-03-18 21:12:30 +00004686 if (Info.isImplicitCopyOrMove())
Douglas Gregor493627b2011-08-10 15:22:55 +00004687 continue;
4688
Aaron Ballman629afae2014-03-07 19:56:05 +00004689 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor493627b2011-08-10 15:22:55 +00004690 if (F->getType()->isIncompleteArrayType()) {
4691 assert(ClassDecl->hasFlexibleArrayMember() &&
4692 "Incomplete array type is not valid");
4693 continue;
4694 }
4695
Douglas Gregor493627b2011-08-10 15:22:55 +00004696 // Initialize each field of an anonymous struct individually.
4697 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4698 HadError = true;
4699
4700 continue;
4701 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004702 }
Mike Stump11289f42009-09-09 15:08:12 +00004703
David Blaikie3fc2f912013-01-17 05:26:25 +00004704 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004705 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004706 Constructor->setNumCtorInitializers(NumInitializers);
4707 CXXCtorInitializer **baseOrMemberInitializers =
4708 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00004709 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00004710 NumInitializers * sizeof(CXXCtorInitializer*));
4711 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00004712
John McCalla6309952010-03-16 21:39:52 +00004713 // Constructors implicitly reference the base and member
4714 // destructors.
4715 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4716 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004717 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00004718
4719 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00004720}
4721
David Blaikieb61b8152013-01-17 08:49:22 +00004722static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004723 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieb61b8152013-01-17 08:49:22 +00004724 const RecordDecl *RD = RT->getDecl();
4725 if (RD->isAnonymousStructOrUnion()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004726 for (auto *Field : RD->fields())
4727 PopulateKeysForFields(Field, IdealInits);
David Blaikieb61b8152013-01-17 08:49:22 +00004728 return;
4729 }
Eli Friedman952c15d2009-07-21 19:28:10 +00004730 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00004731 IdealInits.push_back(Field->getCanonicalDecl());
Eli Friedman952c15d2009-07-21 19:28:10 +00004732}
4733
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004734static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4735 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00004736}
4737
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004738static const void *GetKeyForMember(ASTContext &Context,
4739 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00004740 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004741 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00004742
Richard Smithcd45dbc2014-04-19 03:48:30 +00004743 return Member->getAnyMember()->getCanonicalDecl();
Eli Friedman952c15d2009-07-21 19:28:10 +00004744}
4745
David Blaikie3fc2f912013-01-17 05:26:25 +00004746static void DiagnoseBaseOrMemInitializerOrder(
4747 Sema &SemaRef, const CXXConstructorDecl *Constructor,
4748 ArrayRef<CXXCtorInitializer *> Inits) {
John McCallbb7b6582010-04-10 07:37:23 +00004749 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00004750 return;
Mike Stump11289f42009-09-09 15:08:12 +00004751
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004752 // Don't check initializers order unless the warning is enabled at the
4753 // location of at least one initializer.
4754 bool ShouldCheckOrder = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004755 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004756 CXXCtorInitializer *Init = Inits[InitIndex];
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004757 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4758 Init->getSourceLocation())) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00004759 ShouldCheckOrder = true;
4760 break;
4761 }
4762 }
4763 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00004764 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004765
John McCallbb7b6582010-04-10 07:37:23 +00004766 // Build the list of bases and members in the order that they'll
4767 // actually be initialized. The explicit initializers should be in
4768 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004769 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00004770
Anders Carlsson96b8fc62010-04-02 03:38:04 +00004771 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4772
John McCallbb7b6582010-04-10 07:37:23 +00004773 // 1. Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00004774 for (const auto &VBase : ClassDecl->vbases())
4775 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump11289f42009-09-09 15:08:12 +00004776
John McCallbb7b6582010-04-10 07:37:23 +00004777 // 2. Non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00004778 for (const auto &Base : ClassDecl->bases()) {
4779 if (Base.isVirtual())
Anders Carlssone0eebb32009-08-27 05:45:01 +00004780 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00004781 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00004782 }
Mike Stump11289f42009-09-09 15:08:12 +00004783
John McCallbb7b6582010-04-10 07:37:23 +00004784 // 3. Direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004785 for (auto *Field : ClassDecl->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004786 if (Field->isUnnamedBitfield())
4787 continue;
4788
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004789 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregor556e5862011-10-10 17:22:13 +00004790 }
4791
John McCallbb7b6582010-04-10 07:37:23 +00004792 unsigned NumIdealInits = IdealInitKeys.size();
4793 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00004794
Craig Topperc3ec1492014-05-26 06:22:03 +00004795 CXXCtorInitializer *PrevInit = nullptr;
David Blaikie3fc2f912013-01-17 05:26:25 +00004796 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004797 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004798 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00004799
4800 // Scan forward to try to find this initializer in the idealized
4801 // initializers list.
4802 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4803 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004804 break;
John McCallbb7b6582010-04-10 07:37:23 +00004805
4806 // If we didn't find this initializer, it must be because we
4807 // scanned past it on a previous iteration. That can only
4808 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00004809 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00004810 Sema::SemaDiagnosticBuilder D =
4811 SemaRef.Diag(PrevInit->getSourceLocation(),
4812 diag::warn_initializer_out_of_order);
4813
Francois Pichetd583da02010-12-04 09:14:42 +00004814 if (PrevInit->isAnyMemberInitializer())
4815 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004816 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004817 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004818
Francois Pichetd583da02010-12-04 09:14:42 +00004819 if (Init->isAnyMemberInitializer())
4820 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00004821 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004822 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00004823
4824 // Move back to the initializer's location in the ideal list.
4825 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4826 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00004827 break;
John McCallbb7b6582010-04-10 07:37:23 +00004828
Aaron Ballmanddd2ece2015-07-20 13:36:07 +00004829 assert(IdealIndex < NumIdealInits &&
John McCallbb7b6582010-04-10 07:37:23 +00004830 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004831 }
John McCallbb7b6582010-04-10 07:37:23 +00004832
4833 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00004834 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00004835}
4836
John McCall23eebd92010-04-10 09:28:51 +00004837namespace {
4838bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004839 CXXCtorInitializer *Init,
4840 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00004841 if (!PrevInit) {
4842 PrevInit = Init;
4843 return false;
4844 }
4845
Douglas Gregorea306a12013-03-25 23:28:23 +00004846 if (FieldDecl *Field = Init->getAnyMember())
John McCall23eebd92010-04-10 09:28:51 +00004847 S.Diag(Init->getSourceLocation(),
4848 diag::err_multiple_mem_initialization)
4849 << Field->getDeclName()
4850 << Init->getSourceRange();
4851 else {
John McCall424cec92011-01-19 06:33:43 +00004852 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00004853 assert(BaseClass && "neither field nor base");
4854 S.Diag(Init->getSourceLocation(),
4855 diag::err_multiple_base_initialization)
4856 << QualType(BaseClass, 0)
4857 << Init->getSourceRange();
4858 }
4859 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4860 << 0 << PrevInit->getSourceRange();
4861
4862 return true;
4863}
4864
Alexis Hunt1d792652011-01-08 20:30:50 +00004865typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00004866typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4867
4868bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00004869 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00004870 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00004871 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00004872 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00004873 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00004874
4875 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00004876 if (Parent->isUnion()) {
4877 UnionEntry &En = Unions[Parent];
4878 if (En.first && En.first != Child) {
4879 S.Diag(Init->getSourceLocation(),
4880 diag::err_multiple_mem_union_initialization)
4881 << Field->getDeclName()
4882 << Init->getSourceRange();
4883 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4884 << 0 << En.second->getSourceRange();
4885 return true;
David Blaikie256ee192011-11-12 20:54:14 +00004886 }
4887 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00004888 En.first = Child;
4889 En.second = Init;
4890 }
David Blaikie0f65d592011-11-17 06:01:57 +00004891 if (!Parent->isAnonymousStructOrUnion())
4892 return false;
John McCall23eebd92010-04-10 09:28:51 +00004893 }
4894
4895 Child = Parent;
4896 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00004897 }
John McCall23eebd92010-04-10 09:28:51 +00004898
4899 return false;
4900}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004901}
John McCall23eebd92010-04-10 09:28:51 +00004902
Anders Carlssone857b292010-04-02 03:37:03 +00004903/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00004904void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00004905 SourceLocation ColonLoc,
David Blaikie3fc2f912013-01-17 05:26:25 +00004906 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00004907 bool AnyErrors) {
4908 if (!ConstructorDecl)
4909 return;
4910
4911 AdjustDeclIfTemplate(ConstructorDecl);
4912
4913 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00004914 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00004915
4916 if (!Constructor) {
4917 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4918 return;
4919 }
4920
John McCall23eebd92010-04-10 09:28:51 +00004921 // Mapping for the duplicate initializers check.
4922 // For member initializers, this is keyed with a FieldDecl*.
4923 // For base initializers, this is keyed with a Type*.
Benjamin Kramer8bf44352013-07-24 15:28:33 +00004924 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00004925
4926 // Mapping for the inconsistent anonymous-union initializers check.
4927 RedundantUnionMap MemberUnions;
4928
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004929 bool HadError = false;
David Blaikie3fc2f912013-01-17 05:26:25 +00004930 for (unsigned i = 0; i < MemInits.size(); i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004931 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00004932
Abramo Bagnara341d7832010-05-26 18:09:23 +00004933 // Set the source order index.
4934 Init->setSourceOrder(i);
4935
Francois Pichetd583da02010-12-04 09:14:42 +00004936 if (Init->isAnyMemberInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004937 const void *Key = GetKeyForMember(Context, Init);
4938 if (CheckRedundantInit(*this, Init, Members[Key]) ||
John McCall23eebd92010-04-10 09:28:51 +00004939 CheckRedundantUnionInit(*this, Init, MemberUnions))
4940 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00004941 } else if (Init->isBaseInitializer()) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00004942 const void *Key = GetKeyForMember(Context, Init);
John McCall23eebd92010-04-10 09:28:51 +00004943 if (CheckRedundantInit(*this, Init, Members[Key]))
4944 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00004945 } else {
4946 assert(Init->isDelegatingInitializer());
4947 // This must be the only initializer
David Blaikie3fc2f912013-01-17 05:26:25 +00004948 if (MemInits.size() != 1) {
Richard Smith21f06f02012-09-14 18:21:10 +00004949 Diag(Init->getSourceLocation(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00004950 diag::err_delegating_initializer_alone)
Richard Smith21f06f02012-09-14 18:21:10 +00004951 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Alexis Hunt61bc1732011-05-01 07:04:31 +00004952 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00004953 }
Alexis Hunt6118d662011-05-04 05:57:24 +00004954 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00004955 // Return immediately as the initializer is set.
4956 return;
Anders Carlssone857b292010-04-02 03:37:03 +00004957 }
Anders Carlssone857b292010-04-02 03:37:03 +00004958 }
4959
Anders Carlsson7b3f2782010-04-02 05:42:15 +00004960 if (HadError)
4961 return;
4962
David Blaikie3fc2f912013-01-17 05:26:25 +00004963 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00004964
David Blaikie3fc2f912013-01-17 05:26:25 +00004965 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu3a446ff2013-09-16 21:54:53 +00004966
Richard Trieuef64e942013-10-25 00:56:00 +00004967 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlssone857b292010-04-02 03:37:03 +00004968}
4969
Fariborz Jahanian37d06562009-09-03 23:18:17 +00004970void
John McCalla6309952010-03-16 21:39:52 +00004971Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4972 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00004973 // Ignore dependent contexts. Also ignore unions, since their members never
4974 // have destructors implicitly called.
4975 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00004976 return;
John McCall1064d7e2010-03-16 05:22:47 +00004977
4978 // FIXME: all the access-control diagnostics are positioned on the
4979 // field/base declaration. That's probably good; that said, the
4980 // user might reasonably want to know why the destructor is being
4981 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00004982
Anders Carlssondee9a302009-11-17 04:44:12 +00004983 // Non-static data members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004984 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00004985 if (Field->isInvalidDecl())
4986 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00004987
4988 // Don't destroy incomplete or zero-length arrays.
4989 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4990 continue;
4991
Anders Carlssondee9a302009-11-17 04:44:12 +00004992 QualType FieldType = Context.getBaseElementType(Field->getType());
4993
4994 const RecordType* RT = FieldType->getAs<RecordType>();
4995 if (!RT)
4996 continue;
4997
4998 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00004999 if (FieldClassDecl->isInvalidDecl())
5000 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00005001 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00005002 continue;
Richard Smith921bd202012-02-26 09:11:52 +00005003 // The destructor for an implicit anonymous union member is never invoked.
5004 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5005 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00005006
Douglas Gregore71edda2010-07-01 22:47:18 +00005007 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005008 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00005009 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00005010 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00005011 << Field->getDeclName()
5012 << FieldType);
5013
Benjamin Kramer8bf44352013-07-24 15:28:33 +00005014 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00005015 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00005016 }
5017
John McCall1064d7e2010-03-16 05:22:47 +00005018 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5019
Anders Carlssondee9a302009-11-17 04:44:12 +00005020 // Bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00005021 for (const auto &Base : ClassDecl->bases()) {
John McCall1064d7e2010-03-16 05:22:47 +00005022 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman574705e2014-03-13 15:41:46 +00005023 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00005024
5025 // Remember direct virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00005026 if (Base.isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00005027 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00005028
John McCall1064d7e2010-03-16 05:22:47 +00005029 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005030 // If our base class is invalid, we probably can't get its dtor anyway.
5031 if (BaseClassDecl->isInvalidDecl())
5032 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00005033 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlssondee9a302009-11-17 04:44:12 +00005034 continue;
John McCall1064d7e2010-03-16 05:22:47 +00005035
Douglas Gregore71edda2010-07-01 22:47:18 +00005036 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005037 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00005038
5039 // FIXME: caret should be on the start of the class name
Aaron Ballman574705e2014-03-13 15:41:46 +00005040 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00005041 PDiag(diag::err_access_dtor_base)
Aaron Ballman574705e2014-03-13 15:41:46 +00005042 << Base.getType()
5043 << Base.getSourceRange(),
John McCall5dadb652012-04-07 03:04:20 +00005044 Context.getTypeDeclType(ClassDecl));
Anders Carlssondee9a302009-11-17 04:44:12 +00005045
Benjamin Kramer8bf44352013-07-24 15:28:33 +00005046 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00005047 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlssondee9a302009-11-17 04:44:12 +00005048 }
5049
5050 // Virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00005051 for (const auto &VBase : ClassDecl->vbases()) {
John McCall1064d7e2010-03-16 05:22:47 +00005052 // Bases are always records in a well-formed non-dependent class.
Aaron Ballman445a9392014-03-13 16:15:17 +00005053 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall1064d7e2010-03-16 05:22:47 +00005054
5055 // Ignore direct virtual bases.
5056 if (DirectVirtualBases.count(RT))
5057 continue;
5058
John McCall1064d7e2010-03-16 05:22:47 +00005059 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005060 // If our base class is invalid, we probably can't get its dtor anyway.
5061 if (BaseClassDecl->isInvalidDecl())
5062 continue;
Richard Smitheec915d62012-02-18 04:13:32 +00005063 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian37d06562009-09-03 23:18:17 +00005064 continue;
John McCall1064d7e2010-03-16 05:22:47 +00005065
Douglas Gregore71edda2010-07-01 22:47:18 +00005066 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00005067 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer626032f2013-06-22 06:43:58 +00005068 if (CheckDestructorAccess(
5069 ClassDecl->getLocation(), Dtor,
5070 PDiag(diag::err_access_dtor_vbase)
Aaron Ballman445a9392014-03-13 16:15:17 +00005071 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00005072 Context.getTypeDeclType(ClassDecl)) ==
5073 AR_accessible) {
5074 CheckDerivedToBaseConversion(
Aaron Ballman445a9392014-03-13 16:15:17 +00005075 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer626032f2013-06-22 06:43:58 +00005076 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005077 SourceRange(), DeclarationName(), nullptr);
David Majnemer626032f2013-06-22 06:43:58 +00005078 }
John McCall1064d7e2010-03-16 05:22:47 +00005079
Benjamin Kramer8bf44352013-07-24 15:28:33 +00005080 MarkFunctionReferenced(Location, Dtor);
Richard Smitheec915d62012-02-18 04:13:32 +00005081 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian37d06562009-09-03 23:18:17 +00005082 }
5083}
5084
John McCall48871652010-08-21 09:40:31 +00005085void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00005086 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00005087 return;
Mike Stump11289f42009-09-09 15:08:12 +00005088
Mike Stump11289f42009-09-09 15:08:12 +00005089 if (CXXConstructorDecl *Constructor
Richard Trieuef64e942013-10-25 00:56:00 +00005090 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie3fc2f912013-01-17 05:26:25 +00005091 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieuef64e942013-10-25 00:56:00 +00005092 DiagnoseUninitializedFields(*this, Constructor);
5093 }
Fariborz Jahanian49c81792009-07-14 18:24:21 +00005094}
5095
Richard Smithdb0ac552015-12-18 22:40:25 +00005096bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005097 if (!getLangOpts().CPlusPlus)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005098 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005099
Richard Smithdb0ac552015-12-18 22:40:25 +00005100 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5101 if (!RD)
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005102 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005103
Richard Smithdb0ac552015-12-18 22:40:25 +00005104 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5105 // class template specialization here, but doing so breaks a lot of code.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005106
John McCall02db245d2010-08-18 09:41:07 +00005107 // We can't answer whether something is abstract until it has a
Richard Smithdb0ac552015-12-18 22:40:25 +00005108 // definition. If it's currently being defined, we'll walk back
John McCall02db245d2010-08-18 09:41:07 +00005109 // over all the declarations when we have a full definition.
5110 const CXXRecordDecl *Def = RD->getDefinition();
5111 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00005112 return false;
5113
Richard Smithdb0ac552015-12-18 22:40:25 +00005114 return RD->isAbstract();
5115}
5116
5117bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5118 TypeDiagnoser &Diagnoser) {
5119 if (!isAbstractType(Loc, T))
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005120 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005121
Richard Smithdb0ac552015-12-18 22:40:25 +00005122 T = Context.getBaseElementType(T);
Douglas Gregorae298422012-05-04 17:09:59 +00005123 Diagnoser.diagnose(*this, Loc, T);
Richard Smithdb0ac552015-12-18 22:40:25 +00005124 DiagnoseAbstractType(T->getAsCXXRecordDecl());
John McCall02db245d2010-08-18 09:41:07 +00005125 return true;
5126}
5127
5128void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5129 // Check if we've already emitted the list of pure virtual functions
5130 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005131 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00005132 return;
Mike Stump11289f42009-09-09 15:08:12 +00005133
Richard Smithbc46e432013-07-22 02:56:56 +00005134 // If the diagnostic is suppressed, don't emit the notes. We're only
5135 // going to emit them once, so try to attach them to a diagnostic we're
5136 // actually going to show.
5137 if (Diags.isLastDiagnosticIgnored())
5138 return;
5139
Douglas Gregor4165bd62010-03-23 23:47:56 +00005140 CXXFinalOverriderMap FinalOverriders;
5141 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00005142
Anders Carlssona2f74f32010-06-03 01:00:02 +00005143 // Keep a set of seen pure methods so we won't diagnose the same method
5144 // more than once.
5145 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5146
Douglas Gregor4165bd62010-03-23 23:47:56 +00005147 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5148 MEnd = FinalOverriders.end();
5149 M != MEnd;
5150 ++M) {
5151 for (OverridingMethods::iterator SO = M->second.begin(),
5152 SOEnd = M->second.end();
5153 SO != SOEnd; ++SO) {
5154 // C++ [class.abstract]p4:
5155 // A class is abstract if it contains or inherits at least one
5156 // pure virtual function for which the final overrider is pure
5157 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00005158
Douglas Gregor4165bd62010-03-23 23:47:56 +00005159 //
5160 if (SO->second.size() != 1)
5161 continue;
5162
5163 if (!SO->second.front().Method->isPure())
5164 continue;
5165
David Blaikie82e95a32014-11-19 07:49:47 +00005166 if (!SeenPureMethods.insert(SO->second.front().Method).second)
Anders Carlssona2f74f32010-06-03 01:00:02 +00005167 continue;
5168
Douglas Gregor4165bd62010-03-23 23:47:56 +00005169 Diag(SO->second.front().Method->getLocation(),
5170 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00005171 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00005172 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005173 }
5174
5175 if (!PureVirtualClassDiagSet)
5176 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5177 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00005178}
5179
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005180namespace {
John McCall02db245d2010-08-18 09:41:07 +00005181struct AbstractUsageInfo {
5182 Sema &S;
5183 CXXRecordDecl *Record;
5184 CanQualType AbstractType;
5185 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00005186
John McCall02db245d2010-08-18 09:41:07 +00005187 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5188 : S(S), Record(Record),
5189 AbstractType(S.Context.getCanonicalType(
5190 S.Context.getTypeDeclType(Record))),
5191 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005192
John McCall02db245d2010-08-18 09:41:07 +00005193 void DiagnoseAbstractType() {
5194 if (Invalid) return;
5195 S.DiagnoseAbstractType(Record);
5196 Invalid = true;
5197 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00005198
John McCall02db245d2010-08-18 09:41:07 +00005199 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5200};
5201
5202struct CheckAbstractUsage {
5203 AbstractUsageInfo &Info;
5204 const NamedDecl *Ctx;
5205
5206 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5207 : Info(Info), Ctx(Ctx) {}
5208
5209 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5210 switch (TL.getTypeLocClass()) {
5211#define ABSTRACT_TYPELOC(CLASS, PARENT)
5212#define TYPELOC(CLASS, PARENT) \
David Blaikie6adc78e2013-02-18 22:06:02 +00005213 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall02db245d2010-08-18 09:41:07 +00005214#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005215 }
John McCall02db245d2010-08-18 09:41:07 +00005216 }
Mike Stump11289f42009-09-09 15:08:12 +00005217
John McCall02db245d2010-08-18 09:41:07 +00005218 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Alp Toker42a16a62014-01-25 23:51:36 +00005219 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005220 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5221 if (!TL.getParam(I))
Douglas Gregor385d3fd2011-02-22 23:21:06 +00005222 continue;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005223
5224 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall02db245d2010-08-18 09:41:07 +00005225 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00005226 }
John McCall02db245d2010-08-18 09:41:07 +00005227 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005228
John McCall02db245d2010-08-18 09:41:07 +00005229 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5230 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5231 }
Mike Stump11289f42009-09-09 15:08:12 +00005232
John McCall02db245d2010-08-18 09:41:07 +00005233 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5234 // Visit the type parameters from a permissive context.
5235 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5236 TemplateArgumentLoc TAL = TL.getArgLoc(I);
5237 if (TAL.getArgument().getKind() == TemplateArgument::Type)
5238 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5239 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5240 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005241 }
John McCall02db245d2010-08-18 09:41:07 +00005242 }
Mike Stump11289f42009-09-09 15:08:12 +00005243
John McCall02db245d2010-08-18 09:41:07 +00005244 // Visit pointee types from a permissive context.
5245#define CheckPolymorphic(Type) \
5246 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5247 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5248 }
5249 CheckPolymorphic(PointerTypeLoc)
5250 CheckPolymorphic(ReferenceTypeLoc)
5251 CheckPolymorphic(MemberPointerTypeLoc)
5252 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00005253 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00005254
John McCall02db245d2010-08-18 09:41:07 +00005255 /// Handle all the types we haven't given a more specific
5256 /// implementation for above.
5257 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5258 // Every other kind of type that we haven't called out already
5259 // that has an inner type is either (1) sugar or (2) contains that
5260 // inner type in some way as a subobject.
5261 if (TypeLoc Next = TL.getNextTypeLoc())
5262 return Visit(Next, Sel);
5263
5264 // If there's no inner type and we're in a permissive context,
5265 // don't diagnose.
5266 if (Sel == Sema::AbstractNone) return;
5267
5268 // Check whether the type matches the abstract type.
5269 QualType T = TL.getType();
5270 if (T->isArrayType()) {
5271 Sel = Sema::AbstractArrayType;
5272 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00005273 }
John McCall02db245d2010-08-18 09:41:07 +00005274 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5275 if (CT != Info.AbstractType) return;
5276
5277 // It matched; do some magic.
5278 if (Sel == Sema::AbstractArrayType) {
5279 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5280 << T << TL.getSourceRange();
5281 } else {
5282 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5283 << Sel << T << TL.getSourceRange();
5284 }
5285 Info.DiagnoseAbstractType();
5286 }
5287};
5288
5289void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5290 Sema::AbstractDiagSelID Sel) {
5291 CheckAbstractUsage(*this, D).Visit(TL, Sel);
5292}
5293
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005294}
John McCall02db245d2010-08-18 09:41:07 +00005295
5296/// Check for invalid uses of an abstract type in a method declaration.
5297static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5298 CXXMethodDecl *MD) {
5299 // No need to do the check on definitions, which require that
5300 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00005301 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00005302 return;
5303
5304 // For safety's sake, just ignore it if we don't have type source
5305 // information. This should never happen for non-implicit methods,
5306 // but...
5307 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5308 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5309}
5310
5311/// Check for invalid uses of an abstract type within a class definition.
5312static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5313 CXXRecordDecl *RD) {
Aaron Ballman629afae2014-03-07 19:56:05 +00005314 for (auto *D : RD->decls()) {
John McCall02db245d2010-08-18 09:41:07 +00005315 if (D->isImplicit()) continue;
5316
5317 // Methods and method templates.
5318 if (isa<CXXMethodDecl>(D)) {
5319 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5320 } else if (isa<FunctionTemplateDecl>(D)) {
5321 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5322 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5323
5324 // Fields and static variables.
5325 } else if (isa<FieldDecl>(D)) {
5326 FieldDecl *FD = cast<FieldDecl>(D);
5327 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5328 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5329 } else if (isa<VarDecl>(D)) {
5330 VarDecl *VD = cast<VarDecl>(D);
5331 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5332 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5333
5334 // Nested classes and class templates.
5335 } else if (isa<CXXRecordDecl>(D)) {
5336 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5337 } else if (isa<ClassTemplateDecl>(D)) {
5338 CheckAbstractClassUsage(Info,
5339 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5340 }
5341 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00005342}
5343
Hans Wennborg99000c22015-08-15 01:18:16 +00005344static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) {
5345 Attr *ClassAttr = getDLLAttr(Class);
5346 if (!ClassAttr)
5347 return;
5348
5349 assert(ClassAttr->getKind() == attr::DLLExport);
5350
5351 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5352
5353 if (TSK == TSK_ExplicitInstantiationDeclaration)
5354 // Don't go any further if this is just an explicit instantiation
5355 // declaration.
5356 return;
5357
5358 for (Decl *Member : Class->decls()) {
5359 auto *MD = dyn_cast<CXXMethodDecl>(Member);
5360 if (!MD)
5361 continue;
5362
5363 if (Member->getAttr<DLLExportAttr>()) {
5364 if (MD->isUserProvided()) {
5365 // Instantiate non-default class member functions ...
5366
5367 // .. except for certain kinds of template specializations.
5368 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5369 continue;
5370
5371 S.MarkFunctionReferenced(Class->getLocation(), MD);
5372
5373 // The function will be passed to the consumer when its definition is
5374 // encountered.
5375 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5376 MD->isCopyAssignmentOperator() ||
5377 MD->isMoveAssignmentOperator()) {
5378 // Synthesize and instantiate non-trivial implicit methods, explicitly
5379 // defaulted methods, and the copy and move assignment operators. The
5380 // latter are exported even if they are trivial, because the address of
5381 // an operator can be taken and should compare equal accross libraries.
5382 DiagnosticErrorTrap Trap(S.Diags);
5383 S.MarkFunctionReferenced(Class->getLocation(), MD);
5384 if (Trap.hasErrorOccurred()) {
5385 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5386 << Class->getName() << !S.getLangOpts().CPlusPlus11;
5387 break;
5388 }
5389
5390 // There is no later point when we will see the definition of this
5391 // function, so pass it to the consumer now.
5392 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5393 }
5394 }
5395 }
5396}
5397
Hans Wennborg853ae942014-05-30 16:59:42 +00005398/// \brief Check class-level dllimport/dllexport attribute.
Hans Wennborg17f9b442015-05-27 00:06:45 +00005399void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
Hans Wennborg853ae942014-05-30 16:59:42 +00005400 Attr *ClassAttr = getDLLAttr(Class);
Hans Wennborg205c39b2014-08-23 22:34:43 +00005401
5402 // MSVC inherits DLL attributes to partial class template specializations.
Hans Wennborg17f9b442015-05-27 00:06:45 +00005403 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
Hans Wennborg205c39b2014-08-23 22:34:43 +00005404 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5405 if (Attr *TemplateAttr =
5406 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
Hans Wennborg17f9b442015-05-27 00:06:45 +00005407 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
Hans Wennborg205c39b2014-08-23 22:34:43 +00005408 A->setInherited(true);
5409 ClassAttr = A;
5410 }
5411 }
5412 }
5413
Hans Wennborg853ae942014-05-30 16:59:42 +00005414 if (!ClassAttr)
5415 return;
5416
Hans Wennborg8313c762014-11-03 16:09:16 +00005417 if (!Class->isExternallyVisible()) {
Hans Wennborg17f9b442015-05-27 00:06:45 +00005418 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
Hans Wennborg8313c762014-11-03 16:09:16 +00005419 << Class << ClassAttr;
5420 return;
5421 }
5422
Hans Wennborg17f9b442015-05-27 00:06:45 +00005423 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00005424 !ClassAttr->isInherited()) {
5425 // Diagnose dll attributes on members of class with dll attribute.
5426 for (Decl *Member : Class->decls()) {
5427 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5428 continue;
5429 InheritableAttr *MemberAttr = getDLLAttr(Member);
5430 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5431 continue;
5432
Hans Wennborg17f9b442015-05-27 00:06:45 +00005433 Diag(MemberAttr->getLocation(),
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00005434 diag::err_attribute_dll_member_of_dll_class)
5435 << MemberAttr << ClassAttr;
Hans Wennborg17f9b442015-05-27 00:06:45 +00005436 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00005437 Member->setInvalidDecl();
5438 }
5439 }
5440
5441 if (Class->getDescribedClassTemplate())
5442 // Don't inherit dll attribute until the template is instantiated.
5443 return;
5444
Hans Wennborg606bd6d2014-11-03 14:24:45 +00005445 // The class is either imported or exported.
5446 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
Hans Wennborg853ae942014-05-30 16:59:42 +00005447
Hans Wennborgfd76d912015-01-15 21:18:30 +00005448 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5449
Hans Wennborgbb1983c2015-06-09 00:39:03 +00005450 // Ignore explicit dllexport on explicit class template instantiation declarations.
5451 if (ClassExported && !ClassAttr->isInherited() &&
5452 TSK == TSK_ExplicitInstantiationDeclaration) {
Hans Wennborgfd76d912015-01-15 21:18:30 +00005453 Class->dropAttr<DLLExportAttr>();
5454 return;
5455 }
5456
Hans Wennborg853ae942014-05-30 16:59:42 +00005457 // Force declaration of implicit members so they can inherit the attribute.
Hans Wennborg17f9b442015-05-27 00:06:45 +00005458 ForceDeclarationOfImplicitMembers(Class);
Hans Wennborg853ae942014-05-30 16:59:42 +00005459
5460 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5461 // seem to be true in practice?
5462
Hans Wennborg853ae942014-05-30 16:59:42 +00005463 for (Decl *Member : Class->decls()) {
Hans Wennborge8ad3832014-06-11 22:44:39 +00005464 VarDecl *VD = dyn_cast<VarDecl>(Member);
5465 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5466
5467 // Only methods and static fields inherit the attributes.
5468 if (!VD && !MD)
Hans Wennborg853ae942014-05-30 16:59:42 +00005469 continue;
Hans Wennborge8ad3832014-06-11 22:44:39 +00005470
Hans Wennborg606bd6d2014-11-03 14:24:45 +00005471 if (MD) {
5472 // Don't process deleted methods.
5473 if (MD->isDeleted())
5474 continue;
Hans Wennborg853ae942014-05-30 16:59:42 +00005475
David Majnemer30f058a2015-05-11 03:00:22 +00005476 if (MD->isInlined()) {
Hans Wennborg97cbed42015-02-19 22:39:24 +00005477 // MinGW does not import or export inline methods.
Saleem Abdulrasool8bbc3152016-10-14 22:25:46 +00005478 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5479 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
David Majnemer30f058a2015-05-11 03:00:22 +00005480 continue;
5481
Dmitry Polukhin41581522016-05-13 09:03:56 +00005482 // MSVC versions before 2015 don't export the move assignment operators
5483 // and move constructor, so don't attempt to import/export them if
5484 // we have a definition.
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005485 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
Dmitry Polukhin41581522016-05-13 09:03:56 +00005486 if ((MD->isMoveAssignmentOperator() ||
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005487 (Ctor && Ctor->isMoveConstructor())) &&
Hans Wennborg17f9b442015-05-27 00:06:45 +00005488 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
David Majnemer30f058a2015-05-11 03:00:22 +00005489 continue;
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005490
5491 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5492 // operator is exported anyway.
5493 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5494 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5495 continue;
Hans Wennborg606bd6d2014-11-03 14:24:45 +00005496 }
Hans Wennborge8ad3832014-06-11 22:44:39 +00005497 }
5498
Hans Wennborg287231c2015-04-22 04:05:17 +00005499 if (!cast<NamedDecl>(Member)->isExternallyVisible())
5500 continue;
5501
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +00005502 if (!getDLLAttr(Member)) {
Hans Wennborg496524b2014-05-31 02:08:49 +00005503 auto *NewAttr =
Hans Wennborg17f9b442015-05-27 00:06:45 +00005504 cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
Hans Wennborg496524b2014-05-31 02:08:49 +00005505 NewAttr->setInherited(true);
5506 Member->addAttr(NewAttr);
5507 }
Hans Wennborg853ae942014-05-30 16:59:42 +00005508 }
Hans Wennborg99000c22015-08-15 01:18:16 +00005509
5510 if (ClassExported)
5511 DelayedDllExportClasses.push_back(Class);
Hans Wennborg853ae942014-05-30 16:59:42 +00005512}
5513
Hans Wennborgfce87ca2015-06-09 00:39:09 +00005514/// \brief Perform propagation of DLL attributes from a derived class to a
5515/// templated base class for MS compatibility.
5516void Sema::propagateDLLAttrToBaseClassTemplate(
5517 CXXRecordDecl *Class, Attr *ClassAttr,
5518 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5519 if (getDLLAttr(
5520 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5521 // If the base class template has a DLL attribute, don't try to change it.
5522 return;
5523 }
5524
5525 auto TSK = BaseTemplateSpec->getSpecializationKind();
5526 if (!getDLLAttr(BaseTemplateSpec) &&
5527 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5528 TSK == TSK_ImplicitInstantiation)) {
5529 // The template hasn't been instantiated yet (or it has, but only as an
5530 // explicit instantiation declaration or implicit instantiation, which means
5531 // we haven't codegenned any members yet), so propagate the attribute.
5532 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5533 NewAttr->setInherited(true);
5534 BaseTemplateSpec->addAttr(NewAttr);
5535
5536 // If the template is already instantiated, checkDLLAttributeRedeclaration()
5537 // needs to be run again to work see the new attribute. Otherwise this will
5538 // get run whenever the template is instantiated.
5539 if (TSK != TSK_Undeclared)
5540 checkClassLevelDLLAttribute(BaseTemplateSpec);
5541
5542 return;
5543 }
5544
5545 if (getDLLAttr(BaseTemplateSpec)) {
5546 // The template has already been specialized or instantiated with an
5547 // attribute, explicitly or through propagation. We should not try to change
5548 // it.
5549 return;
5550 }
5551
5552 // The template was previously instantiated or explicitly specialized without
5553 // a dll attribute, It's too late for us to add an attribute, so warn that
5554 // this is unsupported.
5555 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5556 << BaseTemplateSpec->isExplicitSpecialization();
5557 Diag(ClassAttr->getLocation(), diag::note_attribute);
5558 if (BaseTemplateSpec->isExplicitSpecialization()) {
5559 Diag(BaseTemplateSpec->getLocation(),
5560 diag::note_template_class_explicit_specialization_was_here)
5561 << BaseTemplateSpec;
5562 } else {
5563 Diag(BaseTemplateSpec->getPointOfInstantiation(),
5564 diag::note_template_class_instantiation_was_here)
5565 << BaseTemplateSpec;
5566 }
5567}
5568
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005569static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5570 SourceLocation DefaultLoc) {
5571 switch (S.getSpecialMember(MD)) {
5572 case Sema::CXXDefaultConstructor:
5573 S.DefineImplicitDefaultConstructor(DefaultLoc,
5574 cast<CXXConstructorDecl>(MD));
5575 break;
5576 case Sema::CXXCopyConstructor:
5577 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5578 break;
5579 case Sema::CXXCopyAssignment:
5580 S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5581 break;
5582 case Sema::CXXDestructor:
5583 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5584 break;
5585 case Sema::CXXMoveConstructor:
5586 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5587 break;
5588 case Sema::CXXMoveAssignment:
5589 S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5590 break;
5591 case Sema::CXXInvalid:
5592 llvm_unreachable("Invalid special member.");
5593 }
5594}
5595
Douglas Gregorc99f1552009-12-03 18:33:45 +00005596/// \brief Perform semantic checks on a class definition that has been
5597/// completing, introducing implicitly-declared members, checking for
5598/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00005599void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00005600 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00005601 return;
5602
John McCall02db245d2010-08-18 09:41:07 +00005603 if (Record->isAbstract() && !Record->isInvalidDecl()) {
5604 AbstractUsageInfo Info(*this, Record);
5605 CheckAbstractClassUsage(Info, Record);
5606 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00005607
5608 // If this is not an aggregate type and has no user-declared constructor,
5609 // complain about any non-static data members of reference or const scalar
5610 // type, since they will never get initializers.
5611 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00005612 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
5613 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00005614 bool Complained = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005615 for (const auto *F : Record->fields()) {
Douglas Gregor556e5862011-10-10 17:22:13 +00005616 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00005617 continue;
5618
Douglas Gregor454a5b62010-04-15 00:00:53 +00005619 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00005620 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00005621 if (!Complained) {
5622 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
5623 << Record->getTagKind() << Record;
5624 Complained = true;
5625 }
5626
5627 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
5628 << F->getType()->isReferenceType()
5629 << F->getDeclName();
5630 }
5631 }
5632 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00005633
Douglas Gregor36c22a22010-10-15 13:21:21 +00005634 if (Record->getIdentifier()) {
5635 // C++ [class.mem]p13:
5636 // If T is the name of a class, then each of the following shall have a
5637 // name different from T:
5638 // - every member of every anonymous union that is a member of class T.
5639 //
5640 // C++ [class.mem]p14:
5641 // In addition, if class T has a user-declared constructor (12.1), every
5642 // non-static data member of class T shall have a name different from T.
David Blaikieff7d47a2012-12-19 00:45:41 +00005643 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
5644 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
5645 ++I) {
5646 NamedDecl *D = *I;
Francois Pichet783dd6e2010-11-21 06:08:52 +00005647 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
5648 isa<IndirectFieldDecl>(D)) {
5649 Diag(D->getLocation(), diag::err_member_name_of_class)
5650 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00005651 break;
5652 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00005653 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00005654 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00005655
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00005656 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00005657 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00005658 CXXDestructorDecl *dtor = Record->getDestructor();
David Blaikie04e2e662014-05-09 22:02:28 +00005659 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
5660 !Record->hasAttr<FinalAttr>())
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00005661 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
5662 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
5663 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005664
David Majnemera5433082013-10-18 00:33:31 +00005665 if (Record->isAbstract()) {
5666 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
5667 Diag(Record->getLocation(), diag::warn_abstract_final_class)
5668 << FA->isSpelledAsSealed();
5669 DiagnoseAbstractType(Record);
5670 }
David Blaikie348df502012-09-21 03:21:07 +00005671 }
5672
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00005673 bool HasMethodWithOverrideControl = false,
5674 HasOverridingMethodWithoutOverrideControl = false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005675 if (!Record->isDependentType()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005676 for (auto *M : Record->methods()) {
Richard Smithbd305122012-12-11 01:14:52 +00005677 // See if a method overloads virtual methods in a base
5678 // class without overriding any.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005679 if (!M->isStatic())
Aaron Ballman2b124d12014-03-13 16:36:16 +00005680 DiagnoseHiddenVirtualMethods(M);
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00005681 if (M->hasAttr<OverrideAttr>())
5682 HasMethodWithOverrideControl = true;
5683 else if (M->size_overridden_methods() > 0)
5684 HasOverridingMethodWithoutOverrideControl = true;
Richard Smithbd305122012-12-11 01:14:52 +00005685 // Check whether the explicitly-defaulted special members are valid.
5686 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Aaron Ballman2b124d12014-03-13 16:36:16 +00005687 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00005688
5689 // For an explicitly defaulted or deleted special member, we defer
5690 // determining triviality until the class is complete. That time is now!
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005691 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00005692 if (!M->isImplicit() && !M->isUserProvided()) {
Richard Smithbd305122012-12-11 01:14:52 +00005693 if (CSM != CXXInvalid) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00005694 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smithbd305122012-12-11 01:14:52 +00005695
5696 // Inform the class that we've finished declaring this member.
Aaron Ballman2b124d12014-03-13 16:36:16 +00005697 Record->finishedDefaultedOrDeletedMember(M);
Richard Smithbd305122012-12-11 01:14:52 +00005698 }
5699 }
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +00005700
5701 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
5702 M->hasAttr<DLLExportAttr>()) {
5703 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5704 M->isTrivial() &&
5705 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
5706 CSM == CXXDestructor))
5707 M->dropAttr<DLLExportAttr>();
5708
5709 if (M->hasAttr<DLLExportAttr>()) {
5710 DefineImplicitSpecialMember(*this, M, M->getLocation());
5711 ActOnFinishInlineFunctionDef(M);
5712 }
5713 }
Richard Smithbd305122012-12-11 01:14:52 +00005714 }
5715 }
5716
Fariborz Jahanianf920a0a2014-10-27 19:11:51 +00005717 if (HasMethodWithOverrideControl &&
5718 HasOverridingMethodWithoutOverrideControl) {
5719 // At least one method has the 'override' control declared.
5720 // Diagnose all other overridden methods which do not have 'override' specified on them.
5721 for (auto *M : Record->methods())
5722 DiagnoseAbsenceOfOverrideControl(M);
5723 }
Sebastian Redl08905022011-02-05 19:23:19 +00005724
John McCall95833f32014-02-27 20:30:49 +00005725 // ms_struct is a request to use the same ABI rules as MSVC. Check
5726 // whether this class uses any C++ features that are implemented
5727 // completely differently in MSVC, and if so, emit a diagnostic.
5728 // That diagnostic defaults to an error, but we allow projects to
5729 // map it down to a warning (or ignore it). It's a fairly common
5730 // practice among users of the ms_struct pragma to mass-annotate
5731 // headers, sweeping up a bunch of types that the project doesn't
5732 // really rely on MSVC-compatible layout for. We must therefore
5733 // support "ms_struct except for C++ stuff" as a secondary ABI.
5734 if (Record->isMsStruct(Context) &&
5735 (Record->isPolymorphic() || Record->getNumBases())) {
5736 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Hunt8f8bad72013-10-11 20:19:00 +00005737 }
5738
Hans Wennborg17f9b442015-05-27 00:06:45 +00005739 checkClassLevelDLLAttribute(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00005740}
5741
Richard Smith41c35d62013-11-27 03:39:20 +00005742/// Look up the special member function that would be called by a special
5743/// member function for a subobject of class type.
5744///
5745/// \param Class The class type of the subobject.
5746/// \param CSM The kind of special member function.
5747/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5748/// \param ConstRHS True if this is a copy operation with a const object
5749/// on its RHS, that is, if the argument to the outer special member
5750/// function is 'const' and this is not a field marked 'mutable'.
5751static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
5752 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5753 unsigned FieldQuals, bool ConstRHS) {
5754 unsigned LHSQuals = 0;
5755 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5756 LHSQuals = FieldQuals;
5757
5758 unsigned RHSQuals = FieldQuals;
5759 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5760 RHSQuals = 0;
5761 else if (ConstRHS)
5762 RHSQuals |= Qualifiers::Const;
5763
5764 return S.LookupSpecialMember(Class, CSM,
5765 RHSQuals & Qualifiers::Const,
5766 RHSQuals & Qualifiers::Volatile,
5767 false,
5768 LHSQuals & Qualifiers::Const,
5769 LHSQuals & Qualifiers::Volatile);
5770}
5771
Richard Smith80a47022016-06-29 01:10:27 +00005772class Sema::InheritedConstructorInfo {
Richard Smith5179eb72016-06-28 19:03:57 +00005773 Sema &S;
5774 SourceLocation UseLoc;
Richard Smith5179eb72016-06-28 19:03:57 +00005775
5776 /// A mapping from the base classes through which the constructor was
5777 /// inherited to the using shadow declaration in that base class (or a null
5778 /// pointer if the constructor was declared in that base class).
5779 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
5780 InheritedFromBases;
5781
Richard Smith80a47022016-06-29 01:10:27 +00005782public:
Richard Smith5179eb72016-06-28 19:03:57 +00005783 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
5784 ConstructorUsingShadowDecl *Shadow)
Richard Smith80a47022016-06-29 01:10:27 +00005785 : S(S), UseLoc(UseLoc) {
Richard Smith5179eb72016-06-28 19:03:57 +00005786 bool DiagnosedMultipleConstructedBases = false;
5787 CXXRecordDecl *ConstructedBase = nullptr;
5788 UsingDecl *ConstructedBaseUsing = nullptr;
5789
5790 // Find the set of such base class subobjects and check that there's a
5791 // unique constructed subobject.
5792 for (auto *D : Shadow->redecls()) {
5793 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
5794 auto *DNominatedBase = DShadow->getNominatedBaseClass();
5795 auto *DConstructedBase = DShadow->getConstructedBaseClass();
5796
5797 InheritedFromBases.insert(
5798 std::make_pair(DNominatedBase->getCanonicalDecl(),
5799 DShadow->getNominatedBaseClassShadowDecl()));
5800 if (DShadow->constructsVirtualBase())
5801 InheritedFromBases.insert(
5802 std::make_pair(DConstructedBase->getCanonicalDecl(),
5803 DShadow->getConstructedBaseClassShadowDecl()));
5804 else
5805 assert(DNominatedBase == DConstructedBase);
5806
5807 // [class.inhctor.init]p2:
5808 // If the constructor was inherited from multiple base class subobjects
5809 // of type B, the program is ill-formed.
5810 if (!ConstructedBase) {
5811 ConstructedBase = DConstructedBase;
5812 ConstructedBaseUsing = D->getUsingDecl();
5813 } else if (ConstructedBase != DConstructedBase &&
5814 !Shadow->isInvalidDecl()) {
5815 if (!DiagnosedMultipleConstructedBases) {
5816 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
5817 << Shadow->getTargetDecl();
5818 S.Diag(ConstructedBaseUsing->getLocation(),
5819 diag::note_ambiguous_inherited_constructor_using)
5820 << ConstructedBase;
5821 DiagnosedMultipleConstructedBases = true;
5822 }
5823 S.Diag(D->getUsingDecl()->getLocation(),
5824 diag::note_ambiguous_inherited_constructor_using)
5825 << DConstructedBase;
5826 }
5827 }
5828
5829 if (DiagnosedMultipleConstructedBases)
5830 Shadow->setInvalidDecl();
5831 }
5832
5833 /// Find the constructor to use for inherited construction of a base class,
5834 /// and whether that base class constructor inherits the constructor from a
5835 /// virtual base class (in which case it won't actually invoke it).
5836 std::pair<CXXConstructorDecl *, bool>
5837 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
5838 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
5839 if (It == InheritedFromBases.end())
5840 return std::make_pair(nullptr, false);
5841
5842 // This is an intermediary class.
5843 if (It->second)
5844 return std::make_pair(
5845 S.findInheritingConstructor(UseLoc, Ctor, It->second),
5846 It->second->constructsVirtualBase());
5847
5848 // This is the base class from which the constructor was inherited.
5849 return std::make_pair(Ctor, false);
5850 }
5851};
Richard Smith5179eb72016-06-28 19:03:57 +00005852
Richard Smithb5800092012-06-10 05:43:50 +00005853/// Is the special member function which would be selected to perform the
5854/// specified operation on the specified class type a constexpr constructor?
Richard Smith5179eb72016-06-28 19:03:57 +00005855static bool
5856specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5857 Sema::CXXSpecialMember CSM, unsigned Quals,
5858 bool ConstRHS,
5859 CXXConstructorDecl *InheritedCtor = nullptr,
Richard Smith80a47022016-06-29 01:10:27 +00005860 Sema::InheritedConstructorInfo *Inherited = nullptr) {
Richard Smith5179eb72016-06-28 19:03:57 +00005861 // If we're inheriting a constructor, see if we need to call it for this base
5862 // class.
5863 if (InheritedCtor) {
5864 assert(CSM == Sema::CXXDefaultConstructor);
5865 auto BaseCtor =
5866 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
5867 if (BaseCtor)
5868 return BaseCtor->isConstexpr();
5869 }
5870
5871 if (CSM == Sema::CXXDefaultConstructor)
5872 return ClassDecl->hasConstexprDefaultConstructor();
5873
Richard Smithb5800092012-06-10 05:43:50 +00005874 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00005875 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smithb5800092012-06-10 05:43:50 +00005876 if (!SMOR || !SMOR->getMethod())
5877 // A constructor we wouldn't select can't be "involved in initializing"
5878 // anything.
5879 return true;
5880 return SMOR->getMethod()->isConstexpr();
5881}
5882
5883/// Determine whether the specified special member function would be constexpr
5884/// if it were implicitly defined.
Richard Smith5179eb72016-06-28 19:03:57 +00005885static bool defaultedSpecialMemberIsConstexpr(
5886 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
5887 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
Richard Smith80a47022016-06-29 01:10:27 +00005888 Sema::InheritedConstructorInfo *Inherited = nullptr) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005889 if (!S.getLangOpts().CPlusPlus11)
Richard Smithb5800092012-06-10 05:43:50 +00005890 return false;
5891
5892 // C++11 [dcl.constexpr]p4:
5893 // In the definition of a constexpr constructor [...]
Richard Smith99005e62013-05-07 03:19:20 +00005894 bool Ctor = true;
Richard Smithb5800092012-06-10 05:43:50 +00005895 switch (CSM) {
5896 case Sema::CXXDefaultConstructor:
Richard Smith5179eb72016-06-28 19:03:57 +00005897 if (Inherited)
5898 break;
Richard Smith4086a132012-06-10 07:07:24 +00005899 // Since default constructor lookup is essentially trivial (and cannot
5900 // involve, for instance, template instantiation), we compute whether a
5901 // defaulted default constructor is constexpr directly within CXXRecordDecl.
5902 //
5903 // This is important for performance; we need to know whether the default
5904 // constructor is constexpr to determine whether the type is a literal type.
5905 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
5906
Richard Smithb5800092012-06-10 05:43:50 +00005907 case Sema::CXXCopyConstructor:
5908 case Sema::CXXMoveConstructor:
Richard Smith4086a132012-06-10 07:07:24 +00005909 // For copy or move constructors, we need to perform overload resolution.
Richard Smithb5800092012-06-10 05:43:50 +00005910 break;
5911
5912 case Sema::CXXCopyAssignment:
5913 case Sema::CXXMoveAssignment:
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005914 if (!S.getLangOpts().CPlusPlus14)
Richard Smith99005e62013-05-07 03:19:20 +00005915 return false;
5916 // In C++1y, we need to perform overload resolution.
5917 Ctor = false;
5918 break;
5919
Richard Smithb5800092012-06-10 05:43:50 +00005920 case Sema::CXXDestructor:
5921 case Sema::CXXInvalid:
5922 return false;
5923 }
5924
5925 // -- if the class is a non-empty union, or for each non-empty anonymous
5926 // union member of a non-union class, exactly one non-static data member
5927 // shall be initialized; [DR1359]
Richard Smith4086a132012-06-10 07:07:24 +00005928 //
5929 // If we squint, this is guaranteed, since exactly one non-static data member
5930 // will be initialized (if the constructor isn't deleted), we just don't know
5931 // which one.
Richard Smith99005e62013-05-07 03:19:20 +00005932 if (Ctor && ClassDecl->isUnion())
Richard Smith5179eb72016-06-28 19:03:57 +00005933 return CSM == Sema::CXXDefaultConstructor
5934 ? ClassDecl->hasInClassInitializer() ||
5935 !ClassDecl->hasVariantMembers()
5936 : true;
Richard Smithb5800092012-06-10 05:43:50 +00005937
5938 // -- the class shall not have any virtual base classes;
Richard Smith99005e62013-05-07 03:19:20 +00005939 if (Ctor && ClassDecl->getNumVBases())
5940 return false;
5941
5942 // C++1y [class.copy]p26:
5943 // -- [the class] is a literal type, and
5944 if (!Ctor && !ClassDecl->isLiteral())
Richard Smithb5800092012-06-10 05:43:50 +00005945 return false;
5946
5947 // -- every constructor involved in initializing [...] base class
5948 // sub-objects shall be a constexpr constructor;
Richard Smith99005e62013-05-07 03:19:20 +00005949 // -- the assignment operator selected to copy/move each direct base
5950 // class is a constexpr function, and
Aaron Ballman574705e2014-03-13 15:41:46 +00005951 for (const auto &B : ClassDecl->bases()) {
5952 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smithb5800092012-06-10 05:43:50 +00005953 if (!BaseType) continue;
5954
5955 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith5179eb72016-06-28 19:03:57 +00005956 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
5957 InheritedCtor, Inherited))
Richard Smithb5800092012-06-10 05:43:50 +00005958 return false;
5959 }
5960
5961 // -- every constructor involved in initializing non-static data members
5962 // [...] shall be a constexpr constructor;
5963 // -- every non-static data member and base class sub-object shall be
5964 // initialized
Richard Smith41c35d62013-11-27 03:39:20 +00005965 // -- for each non-static data member of X that is of class type (or array
Richard Smith99005e62013-05-07 03:19:20 +00005966 // thereof), the assignment operator selected to copy/move that member is
5967 // a constexpr function
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005968 for (const auto *F : ClassDecl->fields()) {
Richard Smithb5800092012-06-10 05:43:50 +00005969 if (F->isInvalidDecl())
5970 continue;
Richard Smith5179eb72016-06-28 19:03:57 +00005971 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
5972 continue;
Richard Smith41c35d62013-11-27 03:39:20 +00005973 QualType BaseType = S.Context.getBaseElementType(F->getType());
5974 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smithb5800092012-06-10 05:43:50 +00005975 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith41c35d62013-11-27 03:39:20 +00005976 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
5977 BaseType.getCVRQualifiers(),
5978 ConstArg && !F->isMutable()))
Richard Smithb5800092012-06-10 05:43:50 +00005979 return false;
Richard Smith5179eb72016-06-28 19:03:57 +00005980 } else if (CSM == Sema::CXXDefaultConstructor) {
5981 return false;
Richard Smithb5800092012-06-10 05:43:50 +00005982 }
5983 }
5984
5985 // All OK, it's constexpr!
5986 return true;
5987}
5988
Richard Smithd3b5c9082012-07-27 04:22:15 +00005989static Sema::ImplicitExceptionSpecification
5990computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
5991 switch (S.getSpecialMember(MD)) {
5992 case Sema::CXXDefaultConstructor:
5993 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
5994 case Sema::CXXCopyConstructor:
5995 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
5996 case Sema::CXXCopyAssignment:
5997 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
5998 case Sema::CXXMoveConstructor:
5999 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
6000 case Sema::CXXMoveAssignment:
6001 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
6002 case Sema::CXXDestructor:
6003 return S.ComputeDefaultedDtorExceptionSpec(MD);
6004 case Sema::CXXInvalid:
6005 break;
6006 }
Richard Smithc2bc61b2013-03-18 21:12:30 +00006007 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
6008 "only special members have implicit exception specs");
Richard Smith5179eb72016-06-28 19:03:57 +00006009 return S.ComputeInheritingCtorExceptionSpec(Loc,
6010 cast<CXXConstructorDecl>(MD));
Richard Smithd3b5c9082012-07-27 04:22:15 +00006011}
6012
Reid Kleckner78af0702013-08-27 23:08:25 +00006013static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6014 CXXMethodDecl *MD) {
6015 FunctionProtoType::ExtProtoInfo EPI;
6016
6017 // Build an exception specification pointing back at this member.
Richard Smith8acb4282014-07-31 21:57:55 +00006018 EPI.ExceptionSpec.Type = EST_Unevaluated;
6019 EPI.ExceptionSpec.SourceDecl = MD;
Reid Kleckner78af0702013-08-27 23:08:25 +00006020
6021 // Set the calling convention to the default for C++ instance methods.
6022 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6023 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6024 /*IsCXXMethod=*/true));
6025 return EPI;
6026}
6027
Richard Smithd3b5c9082012-07-27 04:22:15 +00006028void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6029 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6030 if (FPT->getExceptionSpecType() != EST_Unevaluated)
6031 return;
6032
Richard Smith7f782272012-07-30 23:48:14 +00006033 // Evaluate the exception specification.
Vitaly Bukaac10dcc2016-12-05 18:30:22 +00006034 auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6035 auto ESI = IES.getExceptionSpec();
Richard Smith564417a2014-03-20 21:47:22 +00006036
Richard Smith7f782272012-07-30 23:48:14 +00006037 // Update the type of the special member to use it.
Richard Smith8acb4282014-07-31 21:57:55 +00006038 UpdateExceptionSpec(MD, ESI);
Richard Smith7f782272012-07-30 23:48:14 +00006039
6040 // A user-provided destructor can be defined outside the class. When that
6041 // happens, be sure to update the exception specification on both
6042 // declarations.
6043 const FunctionProtoType *CanonicalFPT =
6044 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6045 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Richard Smith8acb4282014-07-31 21:57:55 +00006046 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
Richard Smithd3b5c9082012-07-27 04:22:15 +00006047}
6048
Richard Smithb9e90b12012-05-15 04:39:51 +00006049void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6050 CXXRecordDecl *RD = MD->getParent();
6051 CXXSpecialMember CSM = getSpecialMember(MD);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00006052
Richard Smithb9e90b12012-05-15 04:39:51 +00006053 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6054 "not an explicitly-defaulted special member");
Alexis Hunt913820d2011-05-13 06:10:58 +00006055
6056 // Whether this was the first-declared instance of the constructor.
Richard Smithb9e90b12012-05-15 04:39:51 +00006057 // This affects whether we implicitly add an exception spec and constexpr.
Alexis Huntc9a55732011-05-14 05:23:28 +00006058 bool First = MD == MD->getCanonicalDecl();
6059
6060 bool HadError = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00006061
6062 // C++11 [dcl.fct.def.default]p1:
6063 // A function that is explicitly defaulted shall
6064 // -- be a special member function (checked elsewhere),
6065 // -- have the same type (except for ref-qualifiers, and except that a
6066 // copy operation can take a non-const reference) as an implicit
6067 // declaration, and
6068 // -- not have default arguments.
6069 unsigned ExpectedParams = 1;
6070 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6071 ExpectedParams = 0;
6072 if (MD->getNumParams() != ExpectedParams) {
6073 // This also checks for default arguments: a copy or move constructor with a
6074 // default argument is classified as a default constructor, and assignment
6075 // operations and destructors can't have default arguments.
6076 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6077 << CSM << MD->getSourceRange();
Alexis Huntc9a55732011-05-14 05:23:28 +00006078 HadError = true;
Richard Smith50d705b2012-12-07 02:10:28 +00006079 } else if (MD->isVariadic()) {
6080 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6081 << CSM << MD->getSourceRange();
6082 HadError = true;
Alexis Huntc9a55732011-05-14 05:23:28 +00006083 }
6084
Richard Smithb9e90b12012-05-15 04:39:51 +00006085 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Alexis Huntc9a55732011-05-14 05:23:28 +00006086
Richard Smithb5800092012-06-10 05:43:50 +00006087 bool CanHaveConstParam = false;
Richard Smith92f241f2012-12-08 02:53:02 +00006088 if (CSM == CXXCopyConstructor)
Richard Smith1c33fe82012-11-28 06:23:12 +00006089 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smith92f241f2012-12-08 02:53:02 +00006090 else if (CSM == CXXCopyAssignment)
Richard Smith1c33fe82012-11-28 06:23:12 +00006091 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Alexis Huntc9a55732011-05-14 05:23:28 +00006092
Richard Smithb9e90b12012-05-15 04:39:51 +00006093 QualType ReturnType = Context.VoidTy;
6094 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6095 // Check for return type matching.
Alp Toker314cc812014-01-25 16:55:45 +00006096 ReturnType = Type->getReturnType();
Richard Smithb9e90b12012-05-15 04:39:51 +00006097 QualType ExpectedReturnType =
6098 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
6099 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6100 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6101 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6102 HadError = true;
6103 }
6104
6105 // A defaulted special member cannot have cv-qualifiers.
6106 if (Type->getTypeQuals()) {
6107 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006108 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
Richard Smithb9e90b12012-05-15 04:39:51 +00006109 HadError = true;
6110 }
6111 }
6112
6113 // Check for parameter type matching.
Alp Toker9cacbab2014-01-20 20:26:09 +00006114 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smithb5800092012-06-10 05:43:50 +00006115 bool HasConstParam = false;
Richard Smithb9e90b12012-05-15 04:39:51 +00006116 if (ExpectedParams && ArgType->isReferenceType()) {
6117 // Argument must be reference to possibly-const T.
6118 QualType ReferentType = ArgType->getPointeeType();
Richard Smithb5800092012-06-10 05:43:50 +00006119 HasConstParam = ReferentType.isConstQualified();
Richard Smithb9e90b12012-05-15 04:39:51 +00006120
6121 if (ReferentType.isVolatileQualified()) {
6122 Diag(MD->getLocation(),
6123 diag::err_defaulted_special_member_volatile_param) << CSM;
6124 HadError = true;
6125 }
6126
Richard Smithb5800092012-06-10 05:43:50 +00006127 if (HasConstParam && !CanHaveConstParam) {
Richard Smithb9e90b12012-05-15 04:39:51 +00006128 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6129 Diag(MD->getLocation(),
6130 diag::err_defaulted_special_member_copy_const_param)
6131 << (CSM == CXXCopyAssignment);
6132 // FIXME: Explain why this special member can't be const.
6133 } else {
6134 Diag(MD->getLocation(),
6135 diag::err_defaulted_special_member_move_const_param)
6136 << (CSM == CXXMoveAssignment);
6137 }
6138 HadError = true;
6139 }
Richard Smithb9e90b12012-05-15 04:39:51 +00006140 } else if (ExpectedParams) {
6141 // A copy assignment operator can take its argument by value, but a
6142 // defaulted one cannot.
6143 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Alexis Hunt604aeb32011-05-17 20:44:43 +00006144 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00006145 HadError = true;
6146 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00006147
Richard Smithcc36f692011-12-22 02:22:31 +00006148 // C++11 [dcl.fct.def.default]p2:
6149 // An explicitly-defaulted function may be declared constexpr only if it
6150 // would have been implicitly declared as constexpr,
Richard Smithb9e90b12012-05-15 04:39:51 +00006151 // Do not apply this rule to members of class templates, since core issue 1358
6152 // makes such functions always instantiate to constexpr functions. For
Richard Smith99005e62013-05-07 03:19:20 +00006153 // functions which cannot be constexpr (for non-constructors in C++11 and for
6154 // destructors in C++1y), this is checked elsewhere.
Richard Smithb5800092012-06-10 05:43:50 +00006155 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6156 HasConstParam);
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006157 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
Richard Smith99005e62013-05-07 03:19:20 +00006158 : isa<CXXConstructorDecl>(MD)) &&
6159 MD->isConstexpr() && !Constexpr &&
Richard Smithb9e90b12012-05-15 04:39:51 +00006160 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6161 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith99005e62013-05-07 03:19:20 +00006162 // FIXME: Explain why the special member can't be constexpr.
Richard Smithb9e90b12012-05-15 04:39:51 +00006163 HadError = true;
Richard Smithcc36f692011-12-22 02:22:31 +00006164 }
Richard Smithbd305122012-12-11 01:14:52 +00006165
Richard Smithcc36f692011-12-22 02:22:31 +00006166 // and may have an explicit exception-specification only if it is compatible
6167 // with the exception-specification on the implicit declaration.
Richard Smithbd305122012-12-11 01:14:52 +00006168 if (Type->hasExceptionSpec()) {
6169 // Delay the check if this is the first declaration of the special member,
6170 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith3901dfe2013-03-27 00:22:47 +00006171 if (First) {
6172 // If the exception specification needs to be instantiated, do so now,
6173 // before we clobber it with an EST_Unevaluated specification below.
6174 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6175 InstantiateExceptionSpec(MD->getLocStart(), MD);
6176 Type = MD->getType()->getAs<FunctionProtoType>();
6177 }
Richard Smithbd305122012-12-11 01:14:52 +00006178 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith3901dfe2013-03-27 00:22:47 +00006179 } else
Richard Smithbd305122012-12-11 01:14:52 +00006180 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6181 }
Richard Smithcc36f692011-12-22 02:22:31 +00006182
6183 // If a function is explicitly defaulted on its first declaration,
6184 if (First) {
6185 // -- it is implicitly considered to be constexpr if the implicit
6186 // definition would be,
Richard Smithb9e90b12012-05-15 04:39:51 +00006187 MD->setConstexpr(Constexpr);
Richard Smithcc36f692011-12-22 02:22:31 +00006188
Richard Smithb9e90b12012-05-15 04:39:51 +00006189 // -- it is implicitly considered to have the same exception-specification
6190 // as if it had been implicitly declared,
Richard Smithbd305122012-12-11 01:14:52 +00006191 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00006192 EPI.ExceptionSpec.Type = EST_Unevaluated;
6193 EPI.ExceptionSpec.SourceDecl = MD;
Jordan Rose5c382722013-03-08 21:51:21 +00006194 MD->setType(Context.getFunctionType(ReturnType,
Craig Topper5fc8fc22014-08-27 06:28:36 +00006195 llvm::makeArrayRef(&ArgType,
Jordan Rose5c382722013-03-08 21:51:21 +00006196 ExpectedParams),
6197 EPI));
Sebastian Redl22653ba2011-08-30 19:58:05 +00006198 }
6199
Richard Smithb9e90b12012-05-15 04:39:51 +00006200 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00006201 if (First) {
Richard Smithb4d2a152013-04-02 19:38:47 +00006202 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +00006203 } else {
Richard Smithb9e90b12012-05-15 04:39:51 +00006204 // C++11 [dcl.fct.def.default]p4:
6205 // [For a] user-provided explicitly-defaulted function [...] if such a
6206 // function is implicitly defined as deleted, the program is ill-formed.
6207 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Richard Smith80a47022016-06-29 01:10:27 +00006208 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
Richard Smithb9e90b12012-05-15 04:39:51 +00006209 HadError = true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00006210 }
6211 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00006212
Richard Smithb9e90b12012-05-15 04:39:51 +00006213 if (HadError)
6214 MD->setInvalidDecl();
Alexis Huntf91729462011-05-12 22:46:25 +00006215}
6216
Richard Smithbd305122012-12-11 01:14:52 +00006217/// Check whether the exception specification provided for an
6218/// explicitly-defaulted special member matches the exception specification
6219/// that would have been generated for an implicit special member, per
6220/// C++11 [dcl.fct.def.default]p2.
6221void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6222 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
Richard Smith0b3a4622014-11-13 20:01:57 +00006223 // If the exception specification was explicitly specified but hadn't been
6224 // parsed when the method was defaulted, grab it now.
6225 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6226 SpecifiedType =
6227 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6228
Richard Smithbd305122012-12-11 01:14:52 +00006229 // Compute the implicit exception specification.
Reid Kleckner78af0702013-08-27 23:08:25 +00006230 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6231 /*IsCXXMethod=*/true);
6232 FunctionProtoType::ExtProtoInfo EPI(CC);
Vitaly Buka846b8f72016-12-05 19:25:00 +00006233 auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
6234 EPI.ExceptionSpec = IES.getExceptionSpec();
Richard Smithbd305122012-12-11 01:14:52 +00006235 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006236 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithbd305122012-12-11 01:14:52 +00006237
6238 // Ensure that it matches.
6239 CheckEquivalentExceptionSpec(
6240 PDiag(diag::err_incorrect_defaulted_exception_spec)
6241 << getSpecialMember(MD), PDiag(),
6242 ImplicitType, SourceLocation(),
6243 SpecifiedType, MD->getLocation());
6244}
6245
Alp Tokerae3a9442013-10-18 05:54:19 +00006246void Sema::CheckDelayedMemberExceptionSpecs() {
Richard Smith88f45492014-11-22 03:09:05 +00006247 decltype(DelayedExceptionSpecChecks) Checks;
6248 decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
Richard Smithbd305122012-12-11 01:14:52 +00006249
Richard Smith88f45492014-11-22 03:09:05 +00006250 std::swap(Checks, DelayedExceptionSpecChecks);
Alp Tokerae3a9442013-10-18 05:54:19 +00006251 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
6252
6253 // Perform any deferred checking of exception specifications for virtual
6254 // destructors.
Richard Smith88f45492014-11-22 03:09:05 +00006255 for (auto &Check : Checks)
6256 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
Alp Tokerae3a9442013-10-18 05:54:19 +00006257
6258 // Check that any explicitly-defaulted methods have exception specifications
6259 // compatible with their implicit exception specifications.
Richard Smith88f45492014-11-22 03:09:05 +00006260 for (auto &Spec : Specs)
6261 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
Richard Smithbd305122012-12-11 01:14:52 +00006262}
6263
Richard Smithd951a1d2012-02-18 02:02:13 +00006264namespace {
6265struct SpecialMemberDeletionInfo {
6266 Sema &S;
6267 CXXMethodDecl *MD;
6268 Sema::CXXSpecialMember CSM;
Richard Smith80a47022016-06-29 01:10:27 +00006269 Sema::InheritedConstructorInfo *ICI;
Richard Smith852265f2012-03-30 20:53:28 +00006270 bool Diagnose;
Richard Smithd951a1d2012-02-18 02:02:13 +00006271
6272 // Properties of the special member, computed for convenience.
Richard Smith41c35d62013-11-27 03:39:20 +00006273 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smithd951a1d2012-02-18 02:02:13 +00006274 SourceLocation Loc;
6275
6276 bool AllFieldsAreConst;
6277
6278 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith80a47022016-06-29 01:10:27 +00006279 Sema::CXXSpecialMember CSM,
6280 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6281 : S(S), MD(MD), CSM(CSM), ICI(ICI), Diagnose(Diagnose),
6282 IsConstructor(false), IsAssignment(false), IsMove(false),
6283 ConstArg(false), Loc(MD->getLocation()), AllFieldsAreConst(true) {
Richard Smithd951a1d2012-02-18 02:02:13 +00006284 switch (CSM) {
6285 case Sema::CXXDefaultConstructor:
6286 case Sema::CXXCopyConstructor:
6287 IsConstructor = true;
6288 break;
6289 case Sema::CXXMoveConstructor:
6290 IsConstructor = true;
6291 IsMove = true;
6292 break;
6293 case Sema::CXXCopyAssignment:
6294 IsAssignment = true;
6295 break;
6296 case Sema::CXXMoveAssignment:
6297 IsAssignment = true;
6298 IsMove = true;
6299 break;
6300 case Sema::CXXDestructor:
6301 break;
6302 case Sema::CXXInvalid:
6303 llvm_unreachable("invalid special member kind");
6304 }
6305
6306 if (MD->getNumParams()) {
Richard Smith41c35d62013-11-27 03:39:20 +00006307 if (const ReferenceType *RT =
6308 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6309 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smithd951a1d2012-02-18 02:02:13 +00006310 }
6311 }
6312
6313 bool inUnion() const { return MD->getParent()->isUnion(); }
6314
Richard Smith80a47022016-06-29 01:10:27 +00006315 Sema::CXXSpecialMember getEffectiveCSM() {
6316 return ICI ? Sema::CXXInvalid : CSM;
6317 }
6318
Richard Smithd951a1d2012-02-18 02:02:13 +00006319 /// Look up the corresponding special member in the given class.
Richard Smithaf136f82012-07-18 03:51:16 +00006320 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Richard Smith41c35d62013-11-27 03:39:20 +00006321 unsigned Quals, bool IsMutable) {
6322 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6323 ConstArg && !IsMutable);
Richard Smithd951a1d2012-02-18 02:02:13 +00006324 }
6325
Richard Smith852265f2012-03-30 20:53:28 +00006326 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith921bd202012-02-26 09:11:52 +00006327
Richard Smith852265f2012-03-30 20:53:28 +00006328 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smithd951a1d2012-02-18 02:02:13 +00006329 bool shouldDeleteForField(FieldDecl *FD);
6330 bool shouldDeleteForAllConstMembers();
Richard Smith852265f2012-03-30 20:53:28 +00006331
Richard Smithaf136f82012-07-18 03:51:16 +00006332 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6333 unsigned Quals);
Richard Smith852265f2012-03-30 20:53:28 +00006334 bool shouldDeleteForSubobjectCall(Subobject Subobj,
6335 Sema::SpecialMemberOverloadResult *SMOR,
6336 bool IsDtorCallInCtor);
John McCalld4274212012-04-09 20:53:23 +00006337
6338 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smithd951a1d2012-02-18 02:02:13 +00006339};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006340}
Richard Smithd951a1d2012-02-18 02:02:13 +00006341
John McCalld4274212012-04-09 20:53:23 +00006342/// Is the given special member inaccessible when used on the given
6343/// sub-object.
6344bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6345 CXXMethodDecl *target) {
6346 /// If we're operating on a base class, the object type is the
6347 /// type of this special member.
6348 QualType objectTy;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00006349 AccessSpecifier access = target->getAccess();
John McCalld4274212012-04-09 20:53:23 +00006350 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6351 objectTy = S.Context.getTypeDeclType(MD->getParent());
6352 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6353
6354 // If we're operating on a field, the object type is the type of the field.
6355 } else {
6356 objectTy = S.Context.getTypeDeclType(target->getParent());
6357 }
6358
6359 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6360}
6361
Richard Smith852265f2012-03-30 20:53:28 +00006362/// Check whether we should delete a special member due to the implicit
6363/// definition containing a call to a special member of a subobject.
6364bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6365 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
6366 bool IsDtorCallInCtor) {
6367 CXXMethodDecl *Decl = SMOR->getMethod();
6368 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6369
6370 int DiagKind = -1;
6371
6372 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6373 DiagKind = !Decl ? 0 : 1;
6374 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6375 DiagKind = 2;
John McCalld4274212012-04-09 20:53:23 +00006376 else if (!isAccessible(Subobj, Decl))
Richard Smith852265f2012-03-30 20:53:28 +00006377 DiagKind = 3;
6378 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6379 !Decl->isTrivial()) {
6380 // A member of a union must have a trivial corresponding special member.
6381 // As a weird special case, a destructor call from a union's constructor
6382 // must be accessible and non-deleted, but need not be trivial. Such a
6383 // destructor is never actually called, but is semantically checked as
6384 // if it were.
6385 DiagKind = 4;
6386 }
6387
6388 if (DiagKind == -1)
6389 return false;
6390
6391 if (Diagnose) {
6392 if (Field) {
6393 S.Diag(Field->getLocation(),
6394 diag::note_deleted_special_member_class_subobject)
Richard Smith80a47022016-06-29 01:10:27 +00006395 << getEffectiveCSM() << MD->getParent() << /*IsField*/true
Richard Smith852265f2012-03-30 20:53:28 +00006396 << Field << DiagKind << IsDtorCallInCtor;
6397 } else {
6398 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6399 S.Diag(Base->getLocStart(),
6400 diag::note_deleted_special_member_class_subobject)
Richard Smith80a47022016-06-29 01:10:27 +00006401 << getEffectiveCSM() << MD->getParent() << /*IsField*/false
Richard Smith852265f2012-03-30 20:53:28 +00006402 << Base->getType() << DiagKind << IsDtorCallInCtor;
6403 }
6404
6405 if (DiagKind == 1)
6406 S.NoteDeletedFunction(Decl);
6407 // FIXME: Explain inaccessibility if DiagKind == 3.
6408 }
6409
6410 return true;
6411}
6412
Richard Smith921bd202012-02-26 09:11:52 +00006413/// Check whether we should delete a special member function due to having a
Richard Smithaf136f82012-07-18 03:51:16 +00006414/// direct or virtual base class or non-static data member of class type M.
Richard Smith921bd202012-02-26 09:11:52 +00006415bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smithaf136f82012-07-18 03:51:16 +00006416 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith852265f2012-03-30 20:53:28 +00006417 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith41c35d62013-11-27 03:39:20 +00006418 bool IsMutable = Field && Field->isMutable();
Richard Smithd951a1d2012-02-18 02:02:13 +00006419
6420 // C++11 [class.ctor]p5:
Richard Smith5704fe82012-03-29 19:00:10 +00006421 // -- any direct or virtual base class, or non-static data member with no
6422 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smithd951a1d2012-02-18 02:02:13 +00006423 // either M has no default constructor or overload resolution as applied
6424 // to M's default constructor results in an ambiguity or in a function
6425 // that is deleted or inaccessible
6426 // C++11 [class.copy]p11, C++11 [class.copy]p23:
6427 // -- a direct or virtual base class B that cannot be copied/moved because
6428 // overload resolution, as applied to B's corresponding special member,
6429 // results in an ambiguity or a function that is deleted or inaccessible
6430 // from the defaulted special member
Richard Smith852265f2012-03-30 20:53:28 +00006431 // C++11 [class.dtor]p5:
6432 // -- any direct or virtual base class [...] has a type with a destructor
6433 // that is deleted or inaccessible
6434 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006435 Field && Field->hasInClassInitializer()) &&
Richard Smith41c35d62013-11-27 03:39:20 +00006436 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6437 false))
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006438 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00006439
Richard Smith852265f2012-03-30 20:53:28 +00006440 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6441 // -- any direct or virtual base class or non-static data member has a
6442 // type with a destructor that is deleted or inaccessible
6443 if (IsConstructor) {
6444 Sema::SpecialMemberOverloadResult *SMOR =
6445 S.LookupSpecialMember(Class, Sema::CXXDestructor,
6446 false, false, false, false, false);
6447 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
6448 return true;
6449 }
6450
Richard Smith921bd202012-02-26 09:11:52 +00006451 return false;
6452}
6453
6454/// Check whether we should delete a special member function due to the class
6455/// having a particular direct or virtual base class.
Richard Smith852265f2012-03-30 20:53:28 +00006456bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006457 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Serge Pavlov5c49e1a2015-12-28 19:40:14 +00006458 // If program is correct, BaseClass cannot be null, but if it is, the error
6459 // must be reported elsewhere.
Richard Smith80a47022016-06-29 01:10:27 +00006460 if (!BaseClass)
6461 return false;
6462 // If we have an inheriting constructor, check whether we're calling an
6463 // inherited constructor instead of a default constructor.
6464 if (ICI) {
6465 assert(CSM == Sema::CXXDefaultConstructor);
6466 auto *BaseCtor =
6467 ICI->findConstructorForBase(BaseClass, cast<CXXConstructorDecl>(MD)
6468 ->getInheritedConstructor()
6469 .getConstructor())
6470 .first;
6471 if (BaseCtor) {
6472 if (BaseCtor->isDeleted() && Diagnose) {
6473 S.Diag(Base->getLocStart(),
6474 diag::note_deleted_special_member_class_subobject)
6475 << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6476 << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false;
6477 S.NoteDeletedFunction(BaseCtor);
6478 }
6479 return BaseCtor->isDeleted();
6480 }
6481 }
6482 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smithd951a1d2012-02-18 02:02:13 +00006483}
6484
6485/// Check whether we should delete a special member function due to the class
6486/// having a particular non-static data member.
6487bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
6488 QualType FieldType = S.Context.getBaseElementType(FD->getType());
6489 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
6490
6491 if (CSM == Sema::CXXDefaultConstructor) {
6492 // For a default constructor, all references must be initialized in-class
6493 // and, if a union, it must have a non-const member.
Richard Smith852265f2012-03-30 20:53:28 +00006494 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
6495 if (Diagnose)
6496 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smith80a47022016-06-29 01:10:27 +00006497 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00006498 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006499 }
Richard Smith619ecdc2012-02-27 06:07:25 +00006500 // C++11 [class.ctor]p5: any non-variant non-static data member of
6501 // const-qualified type (or array thereof) with no
6502 // brace-or-equal-initializer does not have a user-provided default
6503 // constructor.
6504 if (!inUnion() && FieldType.isConstQualified() &&
6505 !FD->hasInClassInitializer() &&
Richard Smith852265f2012-03-30 20:53:28 +00006506 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
6507 if (Diagnose)
6508 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smith80a47022016-06-29 01:10:27 +00006509 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith619ecdc2012-02-27 06:07:25 +00006510 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006511 }
6512
6513 if (inUnion() && !FieldType.isConstQualified())
6514 AllFieldsAreConst = false;
Richard Smithd951a1d2012-02-18 02:02:13 +00006515 } else if (CSM == Sema::CXXCopyConstructor) {
6516 // For a copy constructor, data members must not be of rvalue reference
6517 // type.
Richard Smith852265f2012-03-30 20:53:28 +00006518 if (FieldType->isRValueReferenceType()) {
6519 if (Diagnose)
6520 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
6521 << MD->getParent() << FD << FieldType;
Richard Smithd951a1d2012-02-18 02:02:13 +00006522 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006523 }
Richard Smithd951a1d2012-02-18 02:02:13 +00006524 } else if (IsAssignment) {
6525 // For an assignment operator, data members must not be of reference type.
Richard Smith852265f2012-03-30 20:53:28 +00006526 if (FieldType->isReferenceType()) {
6527 if (Diagnose)
6528 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6529 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smithd951a1d2012-02-18 02:02:13 +00006530 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006531 }
6532 if (!FieldRecord && FieldType.isConstQualified()) {
6533 // C++11 [class.copy]p23:
6534 // -- a non-static data member of const non-class type (or array thereof)
6535 if (Diagnose)
6536 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smithc5f98f32012-04-29 06:32:34 +00006537 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith852265f2012-03-30 20:53:28 +00006538 return true;
6539 }
Richard Smithd951a1d2012-02-18 02:02:13 +00006540 }
6541
6542 if (FieldRecord) {
Richard Smithd951a1d2012-02-18 02:02:13 +00006543 // Some additional restrictions exist on the variant members.
6544 if (!inUnion() && FieldRecord->isUnion() &&
6545 FieldRecord->isAnonymousStructOrUnion()) {
6546 bool AllVariantFieldsAreConst = true;
6547
Richard Smith5704fe82012-03-29 19:00:10 +00006548 // FIXME: Handle anonymous unions declared within anonymous unions.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006549 for (auto *UI : FieldRecord->fields()) {
Richard Smithd951a1d2012-02-18 02:02:13 +00006550 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smithd951a1d2012-02-18 02:02:13 +00006551
6552 if (!UnionFieldType.isConstQualified())
6553 AllVariantFieldsAreConst = false;
6554
Richard Smith921bd202012-02-26 09:11:52 +00006555 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
6556 if (UnionFieldRecord &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006557 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smithaf136f82012-07-18 03:51:16 +00006558 UnionFieldType.getCVRQualifiers()))
Richard Smith921bd202012-02-26 09:11:52 +00006559 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00006560 }
6561
6562 // At least one member in each anonymous union must be non-const
Douglas Gregor232ee492012-02-24 21:25:53 +00006563 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006564 !FieldRecord->field_empty()) {
Richard Smith852265f2012-03-30 20:53:28 +00006565 if (Diagnose)
6566 S.Diag(FieldRecord->getLocation(),
6567 diag::note_deleted_default_ctor_all_const)
Richard Smith80a47022016-06-29 01:10:27 +00006568 << !!ICI << MD->getParent() << /*anonymous union*/1;
Richard Smithd951a1d2012-02-18 02:02:13 +00006569 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006570 }
Richard Smithd951a1d2012-02-18 02:02:13 +00006571
Richard Smith5704fe82012-03-29 19:00:10 +00006572 // Don't check the implicit member of the anonymous union type.
Richard Smithd951a1d2012-02-18 02:02:13 +00006573 // This is technically non-conformant, but sanity demands it.
6574 return false;
6575 }
6576
Richard Smithaf136f82012-07-18 03:51:16 +00006577 if (shouldDeleteForClassSubobject(FieldRecord, FD,
6578 FieldType.getCVRQualifiers()))
Richard Smith5704fe82012-03-29 19:00:10 +00006579 return true;
Richard Smithd951a1d2012-02-18 02:02:13 +00006580 }
6581
6582 return false;
6583}
6584
6585/// C++11 [class.ctor] p5:
6586/// A defaulted default constructor for a class X is defined as deleted if
6587/// X is a union and all of its variant members are of const-qualified type.
6588bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor232ee492012-02-24 21:25:53 +00006589 // This is a silly definition, because it gives an empty union a deleted
6590 // default constructor. Don't do that.
Richard Smith5e052982016-11-08 01:07:26 +00006591 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
6592 bool AnyFields = false;
6593 for (auto *F : MD->getParent()->fields())
6594 if ((AnyFields = !F->isUnnamedBitfield()))
6595 break;
6596 if (!AnyFields)
6597 return false;
Richard Smith852265f2012-03-30 20:53:28 +00006598 if (Diagnose)
6599 S.Diag(MD->getParent()->getLocation(),
6600 diag::note_deleted_default_ctor_all_const)
Richard Smith80a47022016-06-29 01:10:27 +00006601 << !!ICI << MD->getParent() << /*not anonymous union*/0;
Richard Smith852265f2012-03-30 20:53:28 +00006602 return true;
6603 }
6604 return false;
Richard Smithd951a1d2012-02-18 02:02:13 +00006605}
6606
6607/// Determine whether a defaulted special member function should be defined as
6608/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
6609/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith852265f2012-03-30 20:53:28 +00006610bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
Richard Smith80a47022016-06-29 01:10:27 +00006611 InheritedConstructorInfo *ICI,
Richard Smith852265f2012-03-30 20:53:28 +00006612 bool Diagnose) {
Richard Smithf716bb82012-08-06 02:25:10 +00006613 if (MD->isInvalidDecl())
6614 return false;
Alexis Huntd6da8762011-10-10 06:18:57 +00006615 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00006616 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006617 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00006618 return false;
6619
Richard Smithd951a1d2012-02-18 02:02:13 +00006620 // C++11 [expr.lambda.prim]p19:
6621 // The closure type associated with a lambda-expression has a
6622 // deleted (8.4.3) default constructor and a deleted copy
6623 // assignment operator.
6624 if (RD->isLambda() &&
Richard Smith852265f2012-03-30 20:53:28 +00006625 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
6626 if (Diagnose)
6627 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smithd951a1d2012-02-18 02:02:13 +00006628 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006629 }
6630
Richard Smith6f1e2c62012-04-02 20:59:25 +00006631 // For an anonymous struct or union, the copy and assignment special members
6632 // will never be used, so skip the check. For an anonymous union declared at
6633 // namespace scope, the constructor and destructor are used.
6634 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
6635 RD->isAnonymousStructOrUnion())
6636 return false;
6637
Richard Smith852265f2012-03-30 20:53:28 +00006638 // C++11 [class.copy]p7, p18:
6639 // If the class definition declares a move constructor or move assignment
6640 // operator, an implicitly declared copy constructor or copy assignment
6641 // operator is defined as deleted.
6642 if (MD->isImplicit() &&
6643 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006644 CXXMethodDecl *UserDeclaredMove = nullptr;
Richard Smith852265f2012-03-30 20:53:28 +00006645
Peter Collingbourne66bfcb32016-11-19 00:30:56 +00006646 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
6647 // deletion of the corresponding copy operation, not both copy operations.
6648 // MSVC 2015 has adopted the standards conforming behavior.
6649 bool DeletesOnlyMatchingCopy =
6650 getLangOpts().MSVCCompat &&
6651 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
6652
Richard Smith852265f2012-03-30 20:53:28 +00006653 if (RD->hasUserDeclaredMoveConstructor() &&
Peter Collingbourne66bfcb32016-11-19 00:30:56 +00006654 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
Richard Smith852265f2012-03-30 20:53:28 +00006655 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00006656
6657 // Find any user-declared move constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006658 for (auto *I : RD->ctors()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00006659 if (I->isMoveConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006660 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00006661 break;
6662 }
6663 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006664 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00006665 } else if (RD->hasUserDeclaredMoveAssignment() &&
Peter Collingbourne66bfcb32016-11-19 00:30:56 +00006666 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
Richard Smith852265f2012-03-30 20:53:28 +00006667 if (!Diagnose) return true;
Richard Smith1a2532b2012-12-08 04:10:18 +00006668
6669 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +00006670 for (auto *I : RD->methods()) {
Richard Smith1a2532b2012-12-08 04:10:18 +00006671 if (I->isMoveAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +00006672 UserDeclaredMove = I;
Richard Smith1a2532b2012-12-08 04:10:18 +00006673 break;
6674 }
6675 }
Richard Smithcf8ec8d2012-04-02 18:40:40 +00006676 assert(UserDeclaredMove);
Richard Smith852265f2012-03-30 20:53:28 +00006677 }
6678
6679 if (UserDeclaredMove) {
6680 Diag(UserDeclaredMove->getLocation(),
6681 diag::note_deleted_copy_user_declared_move)
Richard Smithf989e512012-04-02 21:07:48 +00006682 << (CSM == CXXCopyAssignment) << RD
Richard Smith852265f2012-03-30 20:53:28 +00006683 << UserDeclaredMove->isMoveAssignmentOperator();
6684 return true;
6685 }
6686 }
Alexis Huntd6da8762011-10-10 06:18:57 +00006687
Richard Smith6f1e2c62012-04-02 20:59:25 +00006688 // Do access control from the special member function
6689 ContextRAII MethodContext(*this, MD);
6690
Richard Smith921bd202012-02-26 09:11:52 +00006691 // C++11 [class.dtor]p5:
6692 // -- for a virtual destructor, lookup of the non-array deallocation function
6693 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith852265f2012-03-30 20:53:28 +00006694 if (CSM == CXXDestructor && MD->isVirtual()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006695 FunctionDecl *OperatorDelete = nullptr;
Richard Smith921bd202012-02-26 09:11:52 +00006696 DeclarationName Name =
6697 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6698 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smithb2f0f052016-10-10 18:54:32 +00006699 OperatorDelete, /*Diagnose*/false)) {
Richard Smith852265f2012-03-30 20:53:28 +00006700 if (Diagnose)
6701 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith921bd202012-02-26 09:11:52 +00006702 return true;
Richard Smith852265f2012-03-30 20:53:28 +00006703 }
Richard Smith921bd202012-02-26 09:11:52 +00006704 }
6705
Richard Smith80a47022016-06-29 01:10:27 +00006706 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
Alexis Huntea6f0322011-05-11 22:34:38 +00006707
Aaron Ballman574705e2014-03-13 15:41:46 +00006708 for (auto &BI : RD->bases())
Richard Smith0786d5b2016-08-31 20:37:39 +00006709 if ((SMI.IsAssignment || !BI.isVirtual()) &&
Aaron Ballman574705e2014-03-13 15:41:46 +00006710 SMI.shouldDeleteForBase(&BI))
Richard Smithd951a1d2012-02-18 02:02:13 +00006711 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00006712
Richard Smithd1627032013-07-22 18:06:23 +00006713 // Per DR1611, do not consider virtual bases of constructors of abstract
Richard Smith0786d5b2016-08-31 20:37:39 +00006714 // classes, since we are not going to construct them. For assignment
6715 // operators, we only assign (and thus only consider) direct bases.
6716 if ((!RD->isAbstract() || !SMI.IsConstructor) && !SMI.IsAssignment) {
Aaron Ballman445a9392014-03-13 16:15:17 +00006717 for (auto &BI : RD->vbases())
6718 if (SMI.shouldDeleteForBase(&BI))
Richard Smithbc46e432013-07-22 02:56:56 +00006719 return true;
6720 }
Alexis Huntea6f0322011-05-11 22:34:38 +00006721
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006722 for (auto *FI : RD->fields())
Richard Smithd951a1d2012-02-18 02:02:13 +00006723 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006724 SMI.shouldDeleteForField(FI))
Alexis Hunta671bca2011-05-20 21:43:47 +00006725 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00006726
Richard Smithd951a1d2012-02-18 02:02:13 +00006727 if (SMI.shouldDeleteForAllConstMembers())
Alexis Huntea6f0322011-05-11 22:34:38 +00006728 return true;
6729
Eli Bendersky9a220fc2014-09-29 20:38:29 +00006730 if (getLangOpts().CUDA) {
6731 // We should delete the special member in CUDA mode if target inference
6732 // failed.
6733 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
6734 Diagnose);
6735 }
6736
Alexis Huntea6f0322011-05-11 22:34:38 +00006737 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00006738}
6739
Richard Smith92f241f2012-12-08 02:53:02 +00006740/// Perform lookup for a special member of the specified kind, and determine
6741/// whether it is trivial. If the triviality can be determined without the
6742/// lookup, skip it. This is intended for use when determining whether a
6743/// special member of a containing object is trivial, and thus does not ever
6744/// perform overload resolution for default constructors.
6745///
6746/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
6747/// member that was most likely to be intended to be trivial, if any.
6748static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
6749 Sema::CXXSpecialMember CSM, unsigned Quals,
Richard Smith41c35d62013-11-27 03:39:20 +00006750 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smith92f241f2012-12-08 02:53:02 +00006751 if (Selected)
Craig Topperc3ec1492014-05-26 06:22:03 +00006752 *Selected = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00006753
6754 switch (CSM) {
6755 case Sema::CXXInvalid:
6756 llvm_unreachable("not a special member");
6757
6758 case Sema::CXXDefaultConstructor:
6759 // C++11 [class.ctor]p5:
6760 // A default constructor is trivial if:
6761 // - all the [direct subobjects] have trivial default constructors
6762 //
6763 // Note, no overload resolution is performed in this case.
6764 if (RD->hasTrivialDefaultConstructor())
6765 return true;
6766
6767 if (Selected) {
6768 // If there's a default constructor which could have been trivial, dig it
6769 // out. Otherwise, if there's any user-provided default constructor, point
6770 // to that as an example of why there's not a trivial one.
Craig Topperc3ec1492014-05-26 06:22:03 +00006771 CXXConstructorDecl *DefCtor = nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00006772 if (RD->needsImplicitDefaultConstructor())
6773 S.DeclareImplicitDefaultConstructor(RD);
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006774 for (auto *CI : RD->ctors()) {
Richard Smith92f241f2012-12-08 02:53:02 +00006775 if (!CI->isDefaultConstructor())
6776 continue;
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006777 DefCtor = CI;
Richard Smith92f241f2012-12-08 02:53:02 +00006778 if (!DefCtor->isUserProvided())
6779 break;
6780 }
6781
6782 *Selected = DefCtor;
6783 }
6784
6785 return false;
6786
6787 case Sema::CXXDestructor:
6788 // C++11 [class.dtor]p5:
6789 // A destructor is trivial if:
6790 // - all the direct [subobjects] have trivial destructors
6791 if (RD->hasTrivialDestructor())
6792 return true;
6793
6794 if (Selected) {
6795 if (RD->needsImplicitDestructor())
6796 S.DeclareImplicitDestructor(RD);
6797 *Selected = RD->getDestructor();
6798 }
6799
6800 return false;
6801
6802 case Sema::CXXCopyConstructor:
6803 // C++11 [class.copy]p12:
6804 // A copy constructor is trivial if:
6805 // - the constructor selected to copy each direct [subobject] is trivial
6806 if (RD->hasTrivialCopyConstructor()) {
6807 if (Quals == Qualifiers::Const)
6808 // We must either select the trivial copy constructor or reach an
6809 // ambiguity; no need to actually perform overload resolution.
6810 return true;
6811 } else if (!Selected) {
6812 return false;
6813 }
6814 // In C++98, we are not supposed to perform overload resolution here, but we
6815 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
6816 // cases like B as having a non-trivial copy constructor:
6817 // struct A { template<typename T> A(T&); };
6818 // struct B { mutable A a; };
6819 goto NeedOverloadResolution;
6820
6821 case Sema::CXXCopyAssignment:
6822 // C++11 [class.copy]p25:
6823 // A copy assignment operator is trivial if:
6824 // - the assignment operator selected to copy each direct [subobject] is
6825 // trivial
6826 if (RD->hasTrivialCopyAssignment()) {
6827 if (Quals == Qualifiers::Const)
6828 return true;
6829 } else if (!Selected) {
6830 return false;
6831 }
6832 // In C++98, we are not supposed to perform overload resolution here, but we
6833 // treat that as a language defect.
6834 goto NeedOverloadResolution;
6835
6836 case Sema::CXXMoveConstructor:
6837 case Sema::CXXMoveAssignment:
6838 NeedOverloadResolution:
6839 Sema::SpecialMemberOverloadResult *SMOR =
Richard Smith41c35d62013-11-27 03:39:20 +00006840 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smith92f241f2012-12-08 02:53:02 +00006841
6842 // The standard doesn't describe how to behave if the lookup is ambiguous.
6843 // We treat it as not making the member non-trivial, just like the standard
6844 // mandates for the default constructor. This should rarely matter, because
6845 // the member will also be deleted.
6846 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6847 return true;
6848
6849 if (!SMOR->getMethod()) {
6850 assert(SMOR->getKind() ==
6851 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
6852 return false;
6853 }
6854
6855 // We deliberately don't check if we found a deleted special member. We're
6856 // not supposed to!
6857 if (Selected)
6858 *Selected = SMOR->getMethod();
6859 return SMOR->getMethod()->isTrivial();
6860 }
6861
6862 llvm_unreachable("unknown special method kind");
6863}
6864
Benjamin Kramer3e350262013-02-15 12:30:38 +00006865static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006866 for (auto *CI : RD->ctors())
Richard Smith92f241f2012-12-08 02:53:02 +00006867 if (!CI->isImplicit())
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +00006868 return CI;
Richard Smith92f241f2012-12-08 02:53:02 +00006869
6870 // Look for constructor templates.
6871 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
6872 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
6873 if (CXXConstructorDecl *CD =
6874 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
6875 return CD;
6876 }
6877
Craig Topperc3ec1492014-05-26 06:22:03 +00006878 return nullptr;
Richard Smith92f241f2012-12-08 02:53:02 +00006879}
6880
6881/// The kind of subobject we are checking for triviality. The values of this
6882/// enumeration are used in diagnostics.
6883enum TrivialSubobjectKind {
6884 /// The subobject is a base class.
6885 TSK_BaseClass,
6886 /// The subobject is a non-static data member.
6887 TSK_Field,
6888 /// The object is actually the complete object.
6889 TSK_CompleteObject
6890};
6891
6892/// Check whether the special member selected for a given type would be trivial.
6893static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Richard Smith41c35d62013-11-27 03:39:20 +00006894 QualType SubType, bool ConstRHS,
Richard Smith92f241f2012-12-08 02:53:02 +00006895 Sema::CXXSpecialMember CSM,
6896 TrivialSubobjectKind Kind,
6897 bool Diagnose) {
6898 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
6899 if (!SubRD)
6900 return true;
6901
6902 CXXMethodDecl *Selected;
6903 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006904 ConstRHS, Diagnose ? &Selected : nullptr))
Richard Smith92f241f2012-12-08 02:53:02 +00006905 return true;
6906
6907 if (Diagnose) {
Richard Smith41c35d62013-11-27 03:39:20 +00006908 if (ConstRHS)
6909 SubType.addConst();
6910
Richard Smith92f241f2012-12-08 02:53:02 +00006911 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
6912 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
6913 << Kind << SubType.getUnqualifiedType();
6914 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
6915 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
6916 } else if (!Selected)
6917 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
6918 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
6919 else if (Selected->isUserProvided()) {
6920 if (Kind == TSK_CompleteObject)
6921 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
6922 << Kind << SubType.getUnqualifiedType() << CSM;
6923 else {
6924 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
6925 << Kind << SubType.getUnqualifiedType() << CSM;
6926 S.Diag(Selected->getLocation(), diag::note_declared_at);
6927 }
6928 } else {
6929 if (Kind != TSK_CompleteObject)
6930 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
6931 << Kind << SubType.getUnqualifiedType() << CSM;
6932
6933 // Explain why the defaulted or deleted special member isn't trivial.
6934 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
6935 }
6936 }
6937
6938 return false;
6939}
6940
6941/// Check whether the members of a class type allow a special member to be
6942/// trivial.
6943static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
6944 Sema::CXXSpecialMember CSM,
6945 bool ConstArg, bool Diagnose) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006946 for (const auto *FI : RD->fields()) {
Richard Smith92f241f2012-12-08 02:53:02 +00006947 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
6948 continue;
6949
6950 QualType FieldType = S.Context.getBaseElementType(FI->getType());
6951
6952 // Pretend anonymous struct or union members are members of this class.
6953 if (FI->isAnonymousStructOrUnion()) {
6954 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
6955 CSM, ConstArg, Diagnose))
6956 return false;
6957 continue;
6958 }
6959
6960 // C++11 [class.ctor]p5:
6961 // A default constructor is trivial if [...]
6962 // -- no non-static data member of its class has a
6963 // brace-or-equal-initializer
6964 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
6965 if (Diagnose)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006966 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smith92f241f2012-12-08 02:53:02 +00006967 return false;
6968 }
6969
6970 // Objective C ARC 4.3.5:
6971 // [...] nontrivally ownership-qualified types are [...] not trivially
6972 // default constructible, copy constructible, move constructible, copy
6973 // assignable, move assignable, or destructible [...]
6974 if (S.getLangOpts().ObjCAutoRefCount &&
6975 FieldType.hasNonTrivialObjCLifetime()) {
6976 if (Diagnose)
6977 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
6978 << RD << FieldType.getObjCLifetime();
6979 return false;
6980 }
6981
Richard Smith41c35d62013-11-27 03:39:20 +00006982 bool ConstRHS = ConstArg && !FI->isMutable();
6983 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
6984 CSM, TSK_Field, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00006985 return false;
6986 }
6987
6988 return true;
6989}
6990
6991/// Diagnose why the specified class does not have a trivial special member of
6992/// the given kind.
6993void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
6994 QualType Ty = Context.getRecordType(RD);
Richard Smith92f241f2012-12-08 02:53:02 +00006995
Richard Smith41c35d62013-11-27 03:39:20 +00006996 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
6997 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smith92f241f2012-12-08 02:53:02 +00006998 TSK_CompleteObject, /*Diagnose*/true);
6999}
7000
7001/// Determine whether a defaulted or deleted special member function is trivial,
7002/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7003/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7004bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7005 bool Diagnose) {
Richard Smith92f241f2012-12-08 02:53:02 +00007006 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7007
7008 CXXRecordDecl *RD = MD->getParent();
7009
7010 bool ConstArg = false;
Richard Smith92f241f2012-12-08 02:53:02 +00007011
Richard Smith2002bfe2013-11-04 02:02:27 +00007012 // C++11 [class.copy]p12, p25: [DR1593]
7013 // A [special member] is trivial if [...] its parameter-type-list is
7014 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smith92f241f2012-12-08 02:53:02 +00007015 switch (CSM) {
7016 case CXXDefaultConstructor:
7017 case CXXDestructor:
7018 // Trivial default constructors and destructors cannot have parameters.
7019 break;
7020
7021 case CXXCopyConstructor:
7022 case CXXCopyAssignment: {
7023 // Trivial copy operations always have const, non-volatile parameter types.
7024 ConstArg = true;
Jordan Rosed03d99d2013-03-05 01:27:54 +00007025 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00007026 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7027 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7028 if (Diagnose)
7029 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7030 << Param0->getSourceRange() << Param0->getType()
7031 << Context.getLValueReferenceType(
7032 Context.getRecordType(RD).withConst());
7033 return false;
7034 }
7035 break;
7036 }
7037
7038 case CXXMoveConstructor:
7039 case CXXMoveAssignment: {
7040 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rosed03d99d2013-03-05 01:27:54 +00007041 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smith92f241f2012-12-08 02:53:02 +00007042 const RValueReferenceType *RT =
7043 Param0->getType()->getAs<RValueReferenceType>();
7044 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7045 if (Diagnose)
7046 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7047 << Param0->getSourceRange() << Param0->getType()
7048 << Context.getRValueReferenceType(Context.getRecordType(RD));
7049 return false;
7050 }
7051 break;
7052 }
7053
7054 case CXXInvalid:
7055 llvm_unreachable("not a special member");
7056 }
7057
Richard Smith92f241f2012-12-08 02:53:02 +00007058 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7059 if (Diagnose)
7060 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7061 diag::note_nontrivial_default_arg)
7062 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7063 return false;
7064 }
7065 if (MD->isVariadic()) {
7066 if (Diagnose)
7067 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7068 return false;
7069 }
7070
7071 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7072 // A copy/move [constructor or assignment operator] is trivial if
7073 // -- the [member] selected to copy/move each direct base class subobject
7074 // is trivial
7075 //
7076 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7077 // A [default constructor or destructor] is trivial if
7078 // -- all the direct base classes have trivial [default constructors or
7079 // destructors]
Aaron Ballman574705e2014-03-13 15:41:46 +00007080 for (const auto &BI : RD->bases())
7081 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
Richard Smith41c35d62013-11-27 03:39:20 +00007082 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smith92f241f2012-12-08 02:53:02 +00007083 return false;
7084
7085 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7086 // A copy/move [constructor or assignment operator] for a class X is
7087 // trivial if
7088 // -- for each non-static data member of X that is of class type (or array
7089 // thereof), the constructor selected to copy/move that member is
7090 // trivial
7091 //
7092 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7093 // A [default constructor or destructor] is trivial if
7094 // -- for all of the non-static data members of its class that are of class
7095 // type (or array thereof), each such class has a trivial [default
7096 // constructor or destructor]
7097 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
7098 return false;
7099
7100 // C++11 [class.dtor]p5:
7101 // A destructor is trivial if [...]
7102 // -- the destructor is not virtual
7103 if (CSM == CXXDestructor && MD->isVirtual()) {
7104 if (Diagnose)
7105 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7106 return false;
7107 }
7108
7109 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7110 // A [special member] for class X is trivial if [...]
7111 // -- class X has no virtual functions and no virtual base classes
7112 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7113 if (!Diagnose)
7114 return false;
7115
7116 if (RD->getNumVBases()) {
7117 // Check for virtual bases. We already know that the corresponding
7118 // member in all bases is trivial, so vbases must all be direct.
7119 CXXBaseSpecifier &BS = *RD->vbases_begin();
7120 assert(BS.isVirtual());
7121 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
7122 return false;
7123 }
7124
7125 // Must have a virtual method.
Aaron Ballman2b124d12014-03-13 16:36:16 +00007126 for (const auto *MI : RD->methods()) {
Richard Smith92f241f2012-12-08 02:53:02 +00007127 if (MI->isVirtual()) {
7128 SourceLocation MLoc = MI->getLocStart();
7129 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7130 return false;
7131 }
7132 }
7133
7134 llvm_unreachable("dynamic class with no vbases and no virtual functions");
7135 }
7136
7137 // Looks like it's trivial!
7138 return true;
7139}
7140
Benjamin Kramer024e6192011-03-04 13:12:48 +00007141namespace {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007142struct FindHiddenVirtualMethod {
7143 Sema *S;
7144 CXXMethodDecl *Method;
7145 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7146 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007147
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007148private:
7149 /// Check whether any most overriden method from MD in Methods
7150 static bool CheckMostOverridenMethods(
7151 const CXXMethodDecl *MD,
7152 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7153 if (MD->size_overridden_methods() == 0)
7154 return Methods.count(MD->getCanonicalDecl());
7155 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7156 E = MD->end_overridden_methods();
7157 I != E; ++I)
7158 if (CheckMostOverridenMethods(*I, Methods))
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007159 return true;
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007160 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007161 }
7162
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007163public:
7164 /// Member lookup function that determines whether a given C++
7165 /// method overloads virtual methods in a base class without overriding any,
7166 /// to be used with CXXRecordDecl::lookupInBases().
7167 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7168 RecordDecl *BaseRecord =
7169 Specifier->getType()->getAs<RecordType>()->getDecl();
7170
7171 DeclarationName Name = Method->getDeclName();
7172 assert(Name.getNameKind() == DeclarationName::Identifier);
7173
7174 bool foundSameNameMethod = false;
7175 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7176 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7177 Path.Decls = Path.Decls.slice(1)) {
7178 NamedDecl *D = Path.Decls.front();
7179 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7180 MD = MD->getCanonicalDecl();
7181 foundSameNameMethod = true;
7182 // Interested only in hidden virtual methods.
7183 if (!MD->isVirtual())
7184 continue;
7185 // If the method we are checking overrides a method from its base
7186 // don't warn about the other overloaded methods. Clang deviates from
7187 // GCC by only diagnosing overloads of inherited virtual functions that
7188 // do not override any other virtual functions in the base. GCC's
7189 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7190 // function from a base class. These cases may be better served by a
7191 // warning (not specific to virtual functions) on call sites when the
7192 // call would select a different function from the base class, were it
7193 // visible.
7194 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7195 if (!S->IsOverload(Method, MD, false))
7196 return true;
7197 // Collect the overload only if its hidden.
7198 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7199 overloadedMethods.push_back(MD);
7200 }
7201 }
7202
7203 if (foundSameNameMethod)
7204 OverloadedMethods.append(overloadedMethods.begin(),
7205 overloadedMethods.end());
7206 return foundSameNameMethod;
7207 }
7208};
7209} // end anonymous namespace
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007210
David Blaikie282c92a2012-10-19 00:53:08 +00007211/// \brief Add the most overriden methods from MD to Methods
7212static void AddMostOverridenMethods(const CXXMethodDecl *MD,
Craig Topper4dd9b432014-08-17 23:49:53 +00007213 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie282c92a2012-10-19 00:53:08 +00007214 if (MD->size_overridden_methods() == 0)
7215 Methods.insert(MD->getCanonicalDecl());
7216 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7217 E = MD->end_overridden_methods();
7218 I != E; ++I)
7219 AddMostOverridenMethods(*I, Methods);
7220}
7221
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007222/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007223/// overriding any.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007224void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7225 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00007226 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007227 return;
7228
7229 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7230 /*bool RecordPaths=*/false,
7231 /*bool DetectVirtual=*/false);
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007232 FindHiddenVirtualMethod FHVM;
7233 FHVM.Method = MD;
7234 FHVM.S = this;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007235
7236 // Keep the base methods that were overriden or introduced in the subclass
7237 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007238 CXXRecordDecl *DC = MD->getParent();
David Blaikieff7d47a2012-12-19 00:45:41 +00007239 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7240 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7241 NamedDecl *ND = *I;
7242 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie282c92a2012-10-19 00:53:08 +00007243 ND = shad->getTargetDecl();
7244 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007245 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007246 }
7247
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00007248 if (DC->lookupInBases(FHVM, Paths))
7249 OverloadedMethods = FHVM.OverloadedMethods;
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007250}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007251
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007252void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7253 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7254 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7255 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7256 PartialDiagnostic PD = PDiag(
7257 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7258 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7259 Diag(overloadedMD->getLocation(), PD);
7260 }
7261}
7262
7263/// \brief Diagnose methods which overload virtual methods in a base class
7264/// without overriding any.
7265void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7266 if (MD->isInvalidDecl())
7267 return;
7268
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007269 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
Eli Friedmanaf65120b2013-09-05 23:51:03 +00007270 return;
7271
7272 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7273 FindHiddenVirtualMethods(MD, OverloadedMethods);
7274 if (!OverloadedMethods.empty()) {
7275 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7276 << MD << (OverloadedMethods.size() > 1);
7277
7278 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00007279 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00007280}
7281
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00007282void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00007283 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00007284 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00007285 SourceLocation RBrac,
7286 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00007287 if (!TagDecl)
7288 return;
Mike Stump11289f42009-09-09 15:08:12 +00007289
Douglas Gregorc9f9b862009-05-11 19:58:34 +00007290 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00007291
Rafael Espindola06e1b132012-07-12 04:32:30 +00007292 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
7293 if (l->getKind() != AttributeList::AT_Visibility)
7294 continue;
7295 l->setInvalid();
7296 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
7297 l->getName();
7298 }
7299
David Blaikie751c5582011-09-22 02:58:26 +00007300 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00007301 // strict aliasing violation!
7302 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00007303 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00007304
Douglas Gregor0be31a22010-07-02 17:43:08 +00007305 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00007306 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00007307}
7308
Douglas Gregor05379422008-11-03 17:51:48 +00007309/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7310/// special functions, such as the default constructor, copy
7311/// constructor, or destructor, to the given C++ class (C++
7312/// [special]p1). This routine can only be executed just before the
7313/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00007314void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Richard Smith5179eb72016-06-28 19:03:57 +00007315 if (ClassDecl->needsImplicitDefaultConstructor()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00007316 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00007317
Richard Smith5179eb72016-06-28 19:03:57 +00007318 if (ClassDecl->hasInheritedConstructor())
7319 DeclareImplicitDefaultConstructor(ClassDecl);
7320 }
Richard Smith12e79312016-05-13 06:47:56 +00007321
Richard Smitha87b7662016-05-13 18:48:05 +00007322 if (ClassDecl->needsImplicitCopyConstructor()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00007323 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00007324
Richard Smith6b02d462012-12-08 08:32:28 +00007325 // If the properties or semantics of the copy constructor couldn't be
7326 // determined while the class was being declared, force a declaration
7327 // of it now.
Richard Smith12e79312016-05-13 06:47:56 +00007328 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7329 ClassDecl->hasInheritedConstructor())
Richard Smith6b02d462012-12-08 08:32:28 +00007330 DeclareImplicitCopyConstructor(ClassDecl);
Peter Collingbourne120eb542016-11-22 00:21:43 +00007331 // For the MS ABI we need to know whether the copy ctor is deleted. A
7332 // prerequisite for deleting the implicit copy ctor is that the class has a
7333 // move ctor or move assignment that is either user-declared or whose
7334 // semantics are inherited from a subobject. FIXME: We should provide a more
7335 // direct way for CodeGen to ask whether the constructor was deleted.
7336 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7337 (ClassDecl->hasUserDeclaredMoveConstructor() ||
7338 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7339 ClassDecl->hasUserDeclaredMoveAssignment() ||
7340 ClassDecl->needsOverloadResolutionForMoveAssignment()))
7341 DeclareImplicitCopyConstructor(ClassDecl);
Richard Smith6b02d462012-12-08 08:32:28 +00007342 }
7343
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007344 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00007345 ++ASTContext::NumImplicitMoveConstructors;
7346
Richard Smith12e79312016-05-13 06:47:56 +00007347 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7348 ClassDecl->hasInheritedConstructor())
Richard Smith6b02d462012-12-08 08:32:28 +00007349 DeclareImplicitMoveConstructor(ClassDecl);
7350 }
7351
Richard Smitha87b7662016-05-13 18:48:05 +00007352 if (ClassDecl->needsImplicitCopyAssignment()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007353 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smith6b02d462012-12-08 08:32:28 +00007354
7355 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007356 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smith6b02d462012-12-08 08:32:28 +00007357 // it shows up in the right place in the vtable and that we diagnose
7358 // problems with the implicit exception specification.
7359 if (ClassDecl->isDynamicClass() ||
Richard Smith12e79312016-05-13 06:47:56 +00007360 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7361 ClassDecl->hasInheritedAssignment())
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007362 DeclareImplicitCopyAssignment(ClassDecl);
7363 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00007364
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007365 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smith966c1fb2011-12-24 21:56:24 +00007366 ++ASTContext::NumImplicitMoveAssignmentOperators;
7367
7368 // Likewise for the move assignment operator.
Richard Smith6b02d462012-12-08 08:32:28 +00007369 if (ClassDecl->isDynamicClass() ||
Richard Smith12e79312016-05-13 06:47:56 +00007370 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7371 ClassDecl->hasInheritedAssignment())
Richard Smith966c1fb2011-12-24 21:56:24 +00007372 DeclareImplicitMoveAssignment(ClassDecl);
7373 }
7374
Richard Smitha87b7662016-05-13 18:48:05 +00007375 if (ClassDecl->needsImplicitDestructor()) {
Douglas Gregor7454c562010-07-02 20:37:36 +00007376 ++ASTContext::NumImplicitDestructors;
Richard Smith6b02d462012-12-08 08:32:28 +00007377
7378 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor7454c562010-07-02 20:37:36 +00007379 // have to declare the destructor immediately. This ensures that, e.g., it
7380 // shows up in the right place in the vtable and that we diagnose problems
7381 // with the implicit exception specification.
Richard Smith6b02d462012-12-08 08:32:28 +00007382 if (ClassDecl->isDynamicClass() ||
7383 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor7454c562010-07-02 20:37:36 +00007384 DeclareImplicitDestructor(ClassDecl);
7385 }
Douglas Gregor05379422008-11-03 17:51:48 +00007386}
7387
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00007388unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Francois Pichet1c229c02011-04-22 22:18:13 +00007389 if (!D)
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00007390 return 0;
Francois Pichet1c229c02011-04-22 22:18:13 +00007391
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00007392 // The order of template parameters is not important here. All names
7393 // get added to the same scope.
7394 SmallVector<TemplateParameterList *, 4> ParameterLists;
7395
7396 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7397 D = TD->getTemplatedDecl();
7398
7399 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
7400 ParameterLists.push_back(PSD->getTemplateParameters());
7401
7402 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
7403 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
7404 ParameterLists.push_back(DD->getTemplateParameterList(i));
7405
7406 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7407 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
7408 ParameterLists.push_back(FTD->getTemplateParameters());
7409 }
7410 }
7411
7412 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7413 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
7414 ParameterLists.push_back(TD->getTemplateParameterList(i));
7415
7416 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
7417 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
7418 ParameterLists.push_back(CTD->getTemplateParameters());
7419 }
7420 }
7421
7422 unsigned Count = 0;
7423 for (TemplateParameterList *Params : ParameterLists) {
7424 if (Params->size() > 0)
7425 // Ignore explicit specializations; they don't contribute to the template
7426 // depth.
7427 ++Count;
7428 for (NamedDecl *Param : *Params) {
7429 if (Param->getDeclName()) {
7430 S->AddDecl(Param);
7431 IdResolver.AddDecl(Param);
Francois Pichet1c229c02011-04-22 22:18:13 +00007432 }
7433 }
7434 }
Francois Pichet1c229c02011-04-22 22:18:13 +00007435
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00007436 return Count;
Douglas Gregore44a2ad2009-05-27 23:11:45 +00007437}
7438
John McCall48871652010-08-21 09:40:31 +00007439void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00007440 if (!RecordD) return;
7441 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00007442 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00007443 PushDeclContext(S, Record);
7444}
7445
John McCall48871652010-08-21 09:40:31 +00007446void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00007447 if (!RecordD) return;
7448 PopDeclContext();
7449}
7450
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007451/// This is used to implement the constant expression evaluation part of the
7452/// attribute enable_if extension. There is nothing in standard C++ which would
7453/// require reentering parameters.
7454void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
7455 if (!Param)
7456 return;
7457
7458 S->AddDecl(Param);
7459 if (Param->getDeclName())
7460 IdResolver.AddDecl(Param);
7461}
7462
Douglas Gregor4d87df52008-12-16 21:30:33 +00007463/// ActOnStartDelayedCXXMethodDeclaration - We have completed
7464/// parsing a top-level (non-nested) C++ class, and we are now
7465/// parsing those parts of the given Method declaration that could
7466/// not be parsed earlier (C++ [class.mem]p2), such as default
7467/// arguments. This action should enter the scope of the given
7468/// Method declaration as if we had just parsed the qualified method
7469/// name. However, it should not bring the parameters into scope;
7470/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00007471void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00007472}
7473
7474/// ActOnDelayedCXXMethodParameter - We've already started a delayed
7475/// C++ method declaration. We're (re-)introducing the given
7476/// function parameter into scope for use in parsing later parts of
7477/// the method declaration. For example, we could see an
7478/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00007479void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00007480 if (!ParamD)
7481 return;
Mike Stump11289f42009-09-09 15:08:12 +00007482
John McCall48871652010-08-21 09:40:31 +00007483 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00007484
7485 // If this parameter has an unparsed default argument, clear it out
7486 // to make way for the parsed default argument.
7487 if (Param->hasUnparsedDefaultArg())
Craig Topperc3ec1492014-05-26 06:22:03 +00007488 Param->setDefaultArg(nullptr);
Douglas Gregor58354032008-12-24 00:01:03 +00007489
John McCall48871652010-08-21 09:40:31 +00007490 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00007491 if (Param->getDeclName())
7492 IdResolver.AddDecl(Param);
7493}
7494
7495/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
7496/// processing the delayed method declaration for Method. The method
7497/// declaration is now considered finished. There may be a separate
7498/// ActOnStartOfFunctionDef action later (not necessarily
7499/// immediately!) for this method, if it was also defined inside the
7500/// class body.
John McCall48871652010-08-21 09:40:31 +00007501void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00007502 if (!MethodD)
7503 return;
Mike Stump11289f42009-09-09 15:08:12 +00007504
Douglas Gregorc8c277a2009-08-24 11:57:43 +00007505 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00007506
John McCall48871652010-08-21 09:40:31 +00007507 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00007508
7509 // Now that we have our default arguments, check the constructor
7510 // again. It could produce additional diagnostics or affect whether
7511 // the class has implicitly-declared destructors, among other
7512 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007513 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
7514 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00007515
7516 // Check the default arguments, which we may have added.
7517 if (!Method->isInvalidDecl())
7518 CheckCXXDefaultArguments(Method);
7519}
7520
Douglas Gregor831c93f2008-11-05 20:51:48 +00007521/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00007522/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00007523/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00007524/// emit diagnostics and set the invalid bit to true. In any case, the type
7525/// will be updated to reflect a well-formed type for the constructor and
7526/// returned.
7527QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00007528 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007529 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007530
7531 // C++ [class.ctor]p3:
7532 // A constructor shall not be virtual (10.3) or static (9.4). A
7533 // constructor can be invoked for a const, volatile or const
7534 // volatile object. A constructor shall not be declared const,
7535 // volatile, or const volatile (9.3.2).
7536 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00007537 if (!D.isInvalidType())
7538 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7539 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
7540 << SourceRange(D.getIdentifierLoc());
7541 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007542 }
John McCall8e7d6562010-08-26 03:08:43 +00007543 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00007544 if (!D.isInvalidType())
7545 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7546 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7547 << SourceRange(D.getIdentifierLoc());
7548 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00007549 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00007550 }
Mike Stump11289f42009-09-09 15:08:12 +00007551
David Majnemer03f705f2014-07-08 18:18:04 +00007552 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7553 diagnoseIgnoredQualifiers(
7554 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
7555 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
7556 D.getDeclSpec().getRestrictSpecLoc(),
7557 D.getDeclSpec().getAtomicSpecLoc());
7558 D.setInvalidType();
7559 }
7560
Abramo Bagnara924a8f32010-12-10 16:29:40 +00007561 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00007562 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00007563 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00007564 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7565 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00007566 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00007567 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7568 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00007569 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00007570 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7571 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00007572 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007573 }
Mike Stump11289f42009-09-09 15:08:12 +00007574
Douglas Gregordb9d6642011-01-26 05:01:58 +00007575 // C++0x [class.ctor]p4:
7576 // A constructor shall not be declared with a ref-qualifier.
7577 if (FTI.hasRefQualifier()) {
7578 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
7579 << FTI.RefQualifierIsLValueRef
7580 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7581 D.setInvalidType();
7582 }
7583
Douglas Gregor831c93f2008-11-05 20:51:48 +00007584 // Rebuild the function type "R" without any type qualifiers (in
7585 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00007586 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00007587 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00007588 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalldb40c7f2010-12-14 08:05:40 +00007589 return R;
7590
7591 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7592 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00007593 EPI.RefQualifier = RQ_None;
Alp Toker9cacbab2014-01-20 20:26:09 +00007594
7595 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00007596}
7597
Douglas Gregor4d87df52008-12-16 21:30:33 +00007598/// CheckConstructor - Checks a fully-formed constructor for
7599/// well-formedness, issuing any diagnostics required. Returns true if
7600/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007601void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00007602 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00007603 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
7604 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007605 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00007606
7607 // C++ [class.copy]p3:
7608 // A declaration of a constructor for a class X is ill-formed if
7609 // its first parameter is of type (optionally cv-qualified) X and
7610 // either there are no other parameters or else all other
7611 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00007612 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00007613 ((Constructor->getNumParams() == 1) ||
7614 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00007615 Constructor->getParamDecl(1)->hasDefaultArg())) &&
7616 Constructor->getTemplateSpecializationKind()
7617 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00007618 QualType ParamType = Constructor->getParamDecl(0)->getType();
7619 QualType ClassTy = Context.getTagDeclType(ClassDecl);
7620 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00007621 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00007622 const char *ConstRef
7623 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
7624 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00007625 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00007626 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00007627
7628 // FIXME: Rather that making the constructor invalid, we should endeavor
7629 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007630 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00007631 }
7632 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00007633}
7634
John McCalldeb646e2010-08-04 01:04:25 +00007635/// CheckDestructor - Checks a fully-formed destructor definition for
7636/// well-formedness, issuing any diagnostics required. Returns true
7637/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00007638bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00007639 CXXRecordDecl *RD = Destructor->getParent();
7640
Peter Collingbourneb289fe62013-05-20 14:12:25 +00007641 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00007642 SourceLocation Loc;
7643
7644 if (!Destructor->isImplicit())
7645 Loc = Destructor->getLocation();
7646 else
7647 Loc = RD->getLocation();
7648
7649 // If we have a virtual destructor, look up the deallocation function
Richard Smithb2f0f052016-10-10 18:54:32 +00007650 if (FunctionDecl *OperatorDelete =
7651 FindDeallocationFunctionForDestructor(Loc, RD)) {
7652 MarkFunctionReferenced(Loc, OperatorDelete);
7653 Destructor->setOperatorDelete(OperatorDelete);
7654 }
Anders Carlsson2a50e952009-11-15 22:49:34 +00007655 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00007656
7657 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00007658}
7659
Douglas Gregor831c93f2008-11-05 20:51:48 +00007660/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
7661/// the well-formednes of the destructor declarator @p D with type @p
7662/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00007663/// emit diagnostics and set the declarator to invalid. Even if this happens,
7664/// will be updated to reflect a well-formed type for the destructor and
7665/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00007666QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00007667 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007668 // C++ [class.dtor]p1:
7669 // [...] A typedef-name that names a class is a class-name
7670 // (7.1.3); however, a typedef-name that names a class shall not
7671 // be used as the identifier in the declarator for a destructor
7672 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00007673 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00007674 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00007675 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00007676 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00007677 else if (const TemplateSpecializationType *TST =
7678 DeclaratorType->getAs<TemplateSpecializationType>())
7679 if (TST->isTypeAlias())
7680 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
7681 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00007682
7683 // C++ [class.dtor]p2:
7684 // A destructor is used to destroy objects of its class type. A
7685 // destructor takes no parameters, and no return type can be
7686 // specified for it (not even void). The address of a destructor
7687 // shall not be taken. A destructor shall not be static. A
7688 // destructor can be invoked for a const, volatile or const
7689 // volatile object. A destructor shall not be declared const,
7690 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00007691 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00007692 if (!D.isInvalidType())
7693 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
7694 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00007695 << SourceRange(D.getIdentifierLoc())
7696 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7697
John McCall8e7d6562010-08-26 03:08:43 +00007698 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00007699 }
David Majnemer03f705f2014-07-08 18:18:04 +00007700 if (!D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007701 // Destructors don't have return types, but the parser will
7702 // happily parse something like:
7703 //
7704 // class X {
7705 // float ~X();
7706 // };
7707 //
7708 // The return type will be eliminated later.
David Majnemer03f705f2014-07-08 18:18:04 +00007709 if (D.getDeclSpec().hasTypeSpecifier())
7710 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
7711 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7712 << SourceRange(D.getIdentifierLoc());
7713 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7714 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
7715 SourceLocation(),
7716 D.getDeclSpec().getConstSpecLoc(),
7717 D.getDeclSpec().getVolatileSpecLoc(),
7718 D.getDeclSpec().getRestrictSpecLoc(),
7719 D.getDeclSpec().getAtomicSpecLoc());
7720 D.setInvalidType();
7721 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00007722 }
Mike Stump11289f42009-09-09 15:08:12 +00007723
Abramo Bagnara924a8f32010-12-10 16:29:40 +00007724 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00007725 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00007726 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00007727 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7728 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00007729 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00007730 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7731 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00007732 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00007733 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7734 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00007735 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007736 }
7737
Douglas Gregordb9d6642011-01-26 05:01:58 +00007738 // C++0x [class.dtor]p2:
7739 // A destructor shall not be declared with a ref-qualifier.
7740 if (FTI.hasRefQualifier()) {
7741 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
7742 << FTI.RefQualifierIsLValueRef
7743 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7744 D.setInvalidType();
7745 }
7746
Douglas Gregor831c93f2008-11-05 20:51:48 +00007747 // Make sure we don't have any parameters.
Alp Toker4284c6e2014-05-11 16:05:55 +00007748 if (FTIHasNonVoidParameters(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007749 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
7750
7751 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00007752 FTI.freeParams();
Chris Lattner38378bf2009-04-25 08:28:21 +00007753 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00007754 }
7755
Mike Stump11289f42009-09-09 15:08:12 +00007756 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00007757 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00007758 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00007759 D.setInvalidType();
7760 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00007761
7762 // Rebuild the function type "R" without any type qualifiers or
7763 // parameters (in case any of the errors above fired) and with
7764 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00007765 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00007766 if (!D.isInvalidType())
7767 return R;
7768
Douglas Gregor95755162010-07-01 05:10:53 +00007769 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00007770 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7771 EPI.Variadic = false;
7772 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00007773 EPI.RefQualifier = RQ_None;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00007774 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00007775}
7776
Craig Toppere335f252015-10-04 04:53:55 +00007777static void extendLeft(SourceRange &R, SourceRange Before) {
Richard Smitha865a162014-12-19 02:07:47 +00007778 if (Before.isInvalid())
7779 return;
7780 R.setBegin(Before.getBegin());
7781 if (R.getEnd().isInvalid())
7782 R.setEnd(Before.getEnd());
7783}
7784
Craig Toppere335f252015-10-04 04:53:55 +00007785static void extendRight(SourceRange &R, SourceRange After) {
Richard Smitha865a162014-12-19 02:07:47 +00007786 if (After.isInvalid())
7787 return;
7788 if (R.getBegin().isInvalid())
7789 R.setBegin(After.getBegin());
7790 R.setEnd(After.getEnd());
7791}
7792
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007793/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
7794/// well-formednes of the conversion function declarator @p D with
7795/// type @p R. If there are any errors in the declarator, this routine
7796/// will emit diagnostics and return true. Otherwise, it will return
7797/// false. Either way, the type @p R will be updated to reflect a
7798/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007799void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00007800 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007801 // C++ [class.conv.fct]p1:
7802 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00007803 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00007804 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00007805 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007806 if (!D.isInvalidType())
7807 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman600bc242013-06-20 20:58:02 +00007808 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7809 << D.getName().getSourceRange();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007810 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00007811 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007812 }
John McCall212fa2e2010-04-13 00:04:31 +00007813
Richard Smitha865a162014-12-19 02:07:47 +00007814 TypeSourceInfo *ConvTSI = nullptr;
7815 QualType ConvType =
7816 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
John McCall212fa2e2010-04-13 00:04:31 +00007817
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007818 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007819 // Conversion functions don't have return types, but the parser will
7820 // happily parse something like:
7821 //
7822 // class X {
7823 // float operator bool();
7824 // };
7825 //
7826 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00007827 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
7828 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7829 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00007830 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007831 }
7832
John McCall212fa2e2010-04-13 00:04:31 +00007833 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7834
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007835 // Make sure we don't have any parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00007836 if (Proto->getNumParams() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007837 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
7838
7839 // Delete the parameters.
Alp Tokerc5350722014-02-26 22:27:52 +00007840 D.getFunctionTypeInfo().freeParams();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007841 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00007842 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007843 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007844 D.setInvalidType();
7845 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007846
John McCall212fa2e2010-04-13 00:04:31 +00007847 // Diagnose "&operator bool()" and other such nonsense. This
7848 // is actually a gcc extension which we don't support.
Alp Toker314cc812014-01-25 16:55:45 +00007849 if (Proto->getReturnType() != ConvType) {
Richard Smitha865a162014-12-19 02:07:47 +00007850 bool NeedsTypedef = false;
7851 SourceRange Before, After;
7852
7853 // Walk the chunks and extract information on them for our diagnostic.
7854 bool PastFunctionChunk = false;
7855 for (auto &Chunk : D.type_objects()) {
7856 switch (Chunk.Kind) {
7857 case DeclaratorChunk::Function:
7858 if (!PastFunctionChunk) {
7859 if (Chunk.Fun.HasTrailingReturnType) {
7860 TypeSourceInfo *TRT = nullptr;
7861 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
7862 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
7863 }
7864 PastFunctionChunk = true;
7865 break;
7866 }
7867 // Fall through.
7868 case DeclaratorChunk::Array:
7869 NeedsTypedef = true;
7870 extendRight(After, Chunk.getSourceRange());
7871 break;
7872
7873 case DeclaratorChunk::Pointer:
7874 case DeclaratorChunk::BlockPointer:
7875 case DeclaratorChunk::Reference:
7876 case DeclaratorChunk::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00007877 case DeclaratorChunk::Pipe:
Richard Smitha865a162014-12-19 02:07:47 +00007878 extendLeft(Before, Chunk.getSourceRange());
7879 break;
7880
7881 case DeclaratorChunk::Paren:
7882 extendLeft(Before, Chunk.Loc);
7883 extendRight(After, Chunk.EndLoc);
7884 break;
7885 }
7886 }
7887
7888 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
7889 After.isValid() ? After.getBegin() :
7890 D.getIdentifierLoc();
7891 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
7892 DB << Before << After;
7893
7894 if (!NeedsTypedef) {
7895 DB << /*don't need a typedef*/0;
7896
7897 // If we can provide a correct fix-it hint, do so.
7898 if (After.isInvalid() && ConvTSI) {
7899 SourceLocation InsertLoc =
Craig Topper07fa1762015-11-15 02:31:46 +00007900 getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
Richard Smitha865a162014-12-19 02:07:47 +00007901 DB << FixItHint::CreateInsertion(InsertLoc, " ")
7902 << FixItHint::CreateInsertionFromRange(
7903 InsertLoc, CharSourceRange::getTokenRange(Before))
7904 << FixItHint::CreateRemoval(Before);
7905 }
7906 } else if (!Proto->getReturnType()->isDependentType()) {
7907 DB << /*typedef*/1 << Proto->getReturnType();
7908 } else if (getLangOpts().CPlusPlus11) {
7909 DB << /*alias template*/2 << Proto->getReturnType();
7910 } else {
7911 DB << /*might not be fixable*/3;
7912 }
7913
7914 // Recover by incorporating the other type chunks into the result type.
7915 // Note, this does *not* change the name of the function. This is compatible
7916 // with the GCC extension:
7917 // struct S { &operator int(); } s;
7918 // int &r = s.operator int(); // ok in GCC
7919 // S::operator int&() {} // error in GCC, function name is 'operator int'.
Alp Toker314cc812014-01-25 16:55:45 +00007920 ConvType = Proto->getReturnType();
John McCall212fa2e2010-04-13 00:04:31 +00007921 }
7922
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007923 // C++ [class.conv.fct]p4:
7924 // The conversion-type-id shall not represent a function type nor
7925 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007926 if (ConvType->isArrayType()) {
7927 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
7928 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007929 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007930 } else if (ConvType->isFunctionType()) {
7931 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
7932 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00007933 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007934 }
7935
7936 // Rebuild the function type "R" without any parameters (in case any
7937 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00007938 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00007939 if (D.isInvalidType())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00007940 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007941
Douglas Gregor5fb53972009-01-14 15:45:31 +00007942 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00007943 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00007944 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007945 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00007946 diag::warn_cxx98_compat_explicit_conversion_functions :
7947 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00007948 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007949}
7950
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007951/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
7952/// the declaration of the given C++ conversion function. This routine
7953/// is responsible for recording the conversion function in the C++
7954/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00007955Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007956 assert(Conversion && "Expected to receive a conversion function declaration");
7957
Douglas Gregor4287b372008-12-12 08:25:50 +00007958 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007959
7960 // Make sure we aren't redeclaring the conversion function.
7961 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007962
7963 // C++ [class.conv.fct]p1:
7964 // [...] A conversion function is never used to convert a
7965 // (possibly cv-qualified) object to the (possibly cv-qualified)
7966 // same object type (or a reference to it), to a (possibly
7967 // cv-qualified) base class of that type (or a reference to it),
7968 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00007969 // FIXME: Suppress this warning if the conversion function ends up being a
7970 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00007971 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007972 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007973 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007974 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00007975 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
7976 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00007977 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00007978 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007979 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
7980 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00007981 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007982 << ClassType;
Richard Smith0f59cb32015-12-18 21:45:41 +00007983 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00007984 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007985 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007986 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00007987 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007988 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007989 }
7990
Douglas Gregor457104e2010-09-29 04:25:11 +00007991 if (FunctionTemplateDecl *ConversionTemplate
7992 = Conversion->getDescribedFunctionTemplate())
7993 return ConversionTemplate;
7994
John McCall48871652010-08-21 09:40:31 +00007995 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00007996}
7997
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00007998//===----------------------------------------------------------------------===//
7999// Namespace Handling
8000//===----------------------------------------------------------------------===//
8001
Richard Smith45bb8852012-10-04 22:13:39 +00008002/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
8003/// reopened.
8004static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8005 SourceLocation Loc,
8006 IdentifierInfo *II, bool *IsInline,
8007 NamespaceDecl *PrevNS) {
8008 assert(*IsInline != PrevNS->isInline());
John McCallb1be5232010-08-26 09:15:37 +00008009
Richard Smithf501cc32012-10-05 01:46:25 +00008010 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8011 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8012 // inline namespaces, with the intention of bringing names into namespace std.
8013 //
8014 // We support this just well enough to get that case working; this is not
8015 // sufficient to support reopening namespaces as inline in general.
Richard Smith45bb8852012-10-04 22:13:39 +00008016 if (*IsInline && II && II->getName().startswith("__atomic") &&
8017 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithf501cc32012-10-05 01:46:25 +00008018 // Mark all prior declarations of the namespace as inline.
Richard Smith45bb8852012-10-04 22:13:39 +00008019 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8020 NS = NS->getPreviousDecl())
8021 NS->setInline(*IsInline);
8022 // Patch up the lookup table for the containing namespace. This isn't really
8023 // correct, but it's good enough for this particular case.
Aaron Ballman629afae2014-03-07 19:56:05 +00008024 for (auto *I : PrevNS->decls())
8025 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smith45bb8852012-10-04 22:13:39 +00008026 PrevNS->getParent()->makeDeclVisibleInContext(ND);
8027 return;
8028 }
8029
8030 if (PrevNS->isInline())
8031 // The user probably just forgot the 'inline', so suggest that it
8032 // be added back.
8033 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8034 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8035 else
Richard Smith360cb252016-09-30 23:16:08 +00008036 S.Diag(Loc, diag::err_inline_namespace_mismatch);
Richard Smith45bb8852012-10-04 22:13:39 +00008037
8038 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8039 *IsInline = PrevNS->isInline();
8040}
John McCallb1be5232010-08-26 09:15:37 +00008041
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008042/// ActOnStartNamespaceDef - This is called at the start of a namespace
8043/// definition.
John McCall48871652010-08-21 09:40:31 +00008044Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00008045 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00008046 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00008047 SourceLocation IdentLoc,
8048 IdentifierInfo *II,
8049 SourceLocation LBrace,
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00008050 AttributeList *AttrList,
8051 UsingDirectiveDecl *&UD) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00008052 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8053 // For anonymous namespace, take the location of the left brace.
8054 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00008055 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00008056 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00008057 bool IsStd = false;
8058 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008059 Scope *DeclRegionScope = NamespcScope->getParent();
8060
Craig Topperc3ec1492014-05-26 06:22:03 +00008061 NamespaceDecl *PrevNS = nullptr;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008062 if (II) {
8063 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00008064 // The identifier in an original-namespace-definition shall not
8065 // have been previously defined in the declarative region in
8066 // which the original-namespace-definition appears. The
8067 // identifier in an original-namespace-definition is the name of
8068 // the namespace. Subsequently in that declarative region, it is
8069 // treated as an original-namespace-name.
8070 //
8071 // Since namespace names are unique in their scope, and we don't
Richard Smith97135cc2015-11-12 22:19:45 +00008072 // look through using directives, just look for any ordinary names
8073 // as if by qualified name lookup.
8074 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration);
8075 LookupQualifiedName(R, CurContext->getRedeclContext());
Richard Smithf2005d32015-12-29 23:34:32 +00008076 NamedDecl *PrevDecl =
8077 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
Douglas Gregore57e7522012-01-07 09:11:48 +00008078 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
Richard Smith97135cc2015-11-12 22:19:45 +00008079
Douglas Gregore57e7522012-01-07 09:11:48 +00008080 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00008081 // This is an extended namespace definition.
Richard Smith45bb8852012-10-04 22:13:39 +00008082 if (IsInline != PrevNS->isInline())
8083 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8084 &IsInline, PrevNS);
Douglas Gregor91f84212008-12-11 16:49:14 +00008085 } else if (PrevDecl) {
8086 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00008087 Diag(Loc, diag::err_redefinition_different_kind)
8088 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00008089 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00008090 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00008091 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00008092 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00008093 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00008094 // This is the first "real" definition of the namespace "std", so update
8095 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00008096 PrevNS = getStdNamespace();
8097 IsStd = true;
8098 AddToKnown = !IsInline;
8099 } else {
8100 // We've seen this namespace for the first time.
8101 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00008102 }
Douglas Gregor91f84212008-12-11 16:49:14 +00008103 } else {
John McCall4fa53422009-10-01 00:25:31 +00008104 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00008105
8106 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00008107 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00008108 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00008109 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00008110 } else {
8111 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00008112 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00008113 }
8114
Richard Smith45bb8852012-10-04 22:13:39 +00008115 if (PrevNS && IsInline != PrevNS->isInline())
8116 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8117 &IsInline, PrevNS);
Douglas Gregore57e7522012-01-07 09:11:48 +00008118 }
8119
8120 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8121 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00008122 if (IsInvalid)
8123 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00008124
8125 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00008126
Douglas Gregore57e7522012-01-07 09:11:48 +00008127 // FIXME: Should we be merging attributes?
8128 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00008129 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00008130
8131 if (IsStd)
8132 StdNamespace = Namespc;
8133 if (AddToKnown)
8134 KnownNamespaces[Namespc] = false;
8135
8136 if (II) {
8137 PushOnScopeChains(Namespc, DeclRegionScope);
8138 } else {
8139 // Link the anonymous namespace into its parent.
8140 DeclContext *Parent = CurContext->getRedeclContext();
8141 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8142 TU->setAnonymousNamespace(Namespc);
8143 } else {
8144 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00008145 }
John McCall4fa53422009-10-01 00:25:31 +00008146
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00008147 CurContext->addDecl(Namespc);
8148
John McCall4fa53422009-10-01 00:25:31 +00008149 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
8150 // behaves as if it were replaced by
8151 // namespace unique { /* empty body */ }
8152 // using namespace unique;
8153 // namespace unique { namespace-body }
8154 // where all occurrences of 'unique' in a translation unit are
8155 // replaced by the same identifier and this identifier differs
8156 // from all other identifiers in the entire program.
8157
8158 // We just create the namespace with an empty name and then add an
8159 // implicit using declaration, just like the standard suggests.
8160 //
8161 // CodeGen enforces the "universally unique" aspect by giving all
8162 // declarations semantically contained within an anonymous
8163 // namespace internal linkage.
8164
Douglas Gregore57e7522012-01-07 09:11:48 +00008165 if (!PrevNS) {
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00008166 UD = UsingDirectiveDecl::Create(Context, Parent,
8167 /* 'using' */ LBrace,
8168 /* 'namespace' */ SourceLocation(),
8169 /* qualifier */ NestedNameSpecifierLoc(),
8170 /* identifier */ SourceLocation(),
8171 Namespc,
8172 /* Ancestor */ Parent);
John McCall0db42252009-12-16 02:06:49 +00008173 UD->setImplicit();
Nick Lewycky38115822012-11-04 20:21:54 +00008174 Parent->addDecl(UD);
John McCall0db42252009-12-16 02:06:49 +00008175 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008176 }
8177
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00008178 ActOnDocumentableDecl(Namespc);
8179
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008180 // Although we could have an invalid decl (i.e. the namespace name is a
8181 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00008182 // FIXME: We should be able to push Namespc here, so that the each DeclContext
8183 // for the namespace has the declarations that showed up in that particular
8184 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00008185 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00008186 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008187}
8188
Sebastian Redla6602e92009-11-23 15:34:23 +00008189/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8190/// is a namespace alias, returns the namespace it points to.
8191static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8192 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8193 return AD->getNamespace();
8194 return dyn_cast_or_null<NamespaceDecl>(D);
8195}
8196
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008197/// ActOnFinishNamespaceDef - This callback is called after a namespace is
8198/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00008199void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008200 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8201 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00008202 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008203 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00008204 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00008205 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00008206}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008207
John McCall28a0cf72010-08-25 07:42:41 +00008208CXXRecordDecl *Sema::getStdBadAlloc() const {
8209 return cast_or_null<CXXRecordDecl>(
8210 StdBadAlloc.get(Context.getExternalSource()));
8211}
8212
Richard Smith96269c52016-09-29 22:49:46 +00008213EnumDecl *Sema::getStdAlignValT() const {
8214 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
8215}
8216
John McCall28a0cf72010-08-25 07:42:41 +00008217NamespaceDecl *Sema::getStdNamespace() const {
8218 return cast_or_null<NamespaceDecl>(
8219 StdNamespace.get(Context.getExternalSource()));
8220}
8221
Gor Nishanov3e048bb2016-10-04 00:31:16 +00008222NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
8223 if (!StdExperimentalNamespaceCache) {
8224 if (auto Std = getStdNamespace()) {
8225 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
8226 SourceLocation(), LookupNamespaceName);
8227 if (!LookupQualifiedName(Result, Std) ||
8228 !(StdExperimentalNamespaceCache =
8229 Result.getAsSingle<NamespaceDecl>()))
8230 Result.suppressDiagnostics();
8231 }
8232 }
8233 return StdExperimentalNamespaceCache;
8234}
8235
Douglas Gregorcdf87022010-06-29 17:53:46 +00008236/// \brief Retrieve the special "std" namespace, which may require us to
8237/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00008238NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00008239 if (!StdNamespace) {
8240 // The "std" namespace has not yet been defined, so build one implicitly.
8241 StdNamespace = NamespaceDecl::Create(Context,
8242 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00008243 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00008244 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00008245 &PP.getIdentifierTable().get("std"),
Craig Topperc3ec1492014-05-26 06:22:03 +00008246 /*PrevDecl=*/nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00008247 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00008248 }
Eli Bendersky9a220fc2014-09-29 20:38:29 +00008249
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00008250 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00008251}
8252
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008253bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008254 assert(getLangOpts().CPlusPlus &&
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008255 "Looking for std::initializer_list outside of C++.");
8256
8257 // We're looking for implicit instantiations of
8258 // template <typename E> class std::initializer_list.
8259
8260 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
8261 return false;
8262
Craig Topperc3ec1492014-05-26 06:22:03 +00008263 ClassTemplateDecl *Template = nullptr;
8264 const TemplateArgument *Arguments = nullptr;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008265
Sebastian Redl43144e72012-01-17 22:49:58 +00008266 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008267
Sebastian Redl43144e72012-01-17 22:49:58 +00008268 ClassTemplateSpecializationDecl *Specialization =
8269 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
8270 if (!Specialization)
8271 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008272
Sebastian Redl43144e72012-01-17 22:49:58 +00008273 Template = Specialization->getSpecializedTemplate();
8274 Arguments = Specialization->getTemplateArgs().data();
8275 } else if (const TemplateSpecializationType *TST =
8276 Ty->getAs<TemplateSpecializationType>()) {
8277 Template = dyn_cast_or_null<ClassTemplateDecl>(
8278 TST->getTemplateName().getAsTemplateDecl());
8279 Arguments = TST->getArgs();
8280 }
8281 if (!Template)
8282 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008283
8284 if (!StdInitializerList) {
8285 // Haven't recognized std::initializer_list yet, maybe this is it.
8286 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
8287 if (TemplateClass->getIdentifier() !=
8288 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00008289 !getStdNamespace()->InEnclosingNamespaceSetOf(
8290 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008291 return false;
8292 // This is a template called std::initializer_list, but is it the right
8293 // template?
8294 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00008295 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008296 return false;
8297 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
8298 return false;
8299
8300 // It's the right template.
8301 StdInitializerList = Template;
8302 }
8303
Richard Smith7d7dee72015-02-24 03:30:14 +00008304 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008305 return false;
8306
8307 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00008308 if (Element)
8309 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00008310 return true;
8311}
8312
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008313static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
8314 NamespaceDecl *Std = S.getStdNamespace();
8315 if (!Std) {
8316 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00008317 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008318 }
8319
8320 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
8321 Loc, Sema::LookupOrdinaryName);
8322 if (!S.LookupQualifiedName(Result, Std)) {
8323 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Craig Topperc3ec1492014-05-26 06:22:03 +00008324 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008325 }
8326 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
8327 if (!Template) {
8328 Result.suppressDiagnostics();
8329 // We found something weird. Complain about the first thing we found.
8330 NamedDecl *Found = *Result.begin();
8331 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00008332 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008333 }
8334
8335 // We found some template called std::initializer_list. Now verify that it's
8336 // correct.
8337 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00008338 if (Params->getMinRequiredArguments() != 1 ||
8339 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008340 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
Craig Topperc3ec1492014-05-26 06:22:03 +00008341 return nullptr;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00008342 }
8343
8344 return Template;
8345}
8346
8347QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
8348 if (!StdInitializerList) {
8349 StdInitializerList = LookupStdInitializerList(*this, Loc);
8350 if (!StdInitializerList)
8351 return QualType();
8352 }
8353
8354 TemplateArgumentListInfo Args(Loc, Loc);
8355 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
8356 Context.getTrivialTypeSourceInfo(Element,
8357 Loc)));
8358 return Context.getCanonicalType(
8359 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
8360}
8361
Sebastian Redlbe24ec22012-01-17 22:50:14 +00008362bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
8363 // C++ [dcl.init.list]p2:
8364 // A constructor is an initializer-list constructor if its first parameter
8365 // is of type std::initializer_list<E> or reference to possibly cv-qualified
8366 // std::initializer_list<E> for some type E, and either there are no other
8367 // parameters or else all other parameters have default arguments.
8368 if (Ctor->getNumParams() < 1 ||
8369 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
8370 return false;
8371
8372 QualType ArgType = Ctor->getParamDecl(0)->getType();
8373 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
8374 ArgType = RT->getPointeeType().getUnqualifiedType();
8375
Craig Topperc3ec1492014-05-26 06:22:03 +00008376 return isStdInitializerList(ArgType, nullptr);
Sebastian Redlbe24ec22012-01-17 22:50:14 +00008377}
8378
Douglas Gregora172e082011-03-26 22:25:30 +00008379/// \brief Determine whether a using statement is in a context where it will be
8380/// apply in all contexts.
8381static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
8382 switch (CurContext->getDeclKind()) {
8383 case Decl::TranslationUnit:
8384 return true;
8385 case Decl::LinkageSpec:
8386 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
8387 default:
8388 return false;
8389 }
8390}
8391
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008392namespace {
8393
8394// Callback to only accept typo corrections that are namespaces.
8395class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008396public:
Craig Toppera798a9d2014-03-02 09:32:10 +00008397 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008398 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008399 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008400 return false;
8401 }
8402};
8403
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008404}
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008405
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008406static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
8407 CXXScopeSpec &SS,
8408 SourceLocation IdentLoc,
8409 IdentifierInfo *Ident) {
8410 R.clear();
Kaelyn Takata89c881b2014-10-27 18:07:29 +00008411 if (TypoCorrection Corrected =
8412 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
8413 llvm::make_unique<NamespaceValidatorCCC>(),
8414 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00008415 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smithf9b15102013-08-17 00:46:16 +00008416 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
8417 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00008418 Ident->getName().equals(CorrectedStr);
Richard Smithf9b15102013-08-17 00:46:16 +00008419 S.diagnoseTypo(Corrected,
8420 S.PDiag(diag::err_using_directive_member_suggest)
8421 << Ident << DC << DroppedSpecifier << SS.getRange(),
8422 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00008423 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00008424 S.diagnoseTypo(Corrected,
8425 S.PDiag(diag::err_using_directive_suggest) << Ident,
8426 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrain10413a42013-07-02 23:47:44 +00008427 }
Richard Smithde6d6c42015-12-29 19:43:10 +00008428 R.addDecl(Corrected.getFoundDecl());
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00008429 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008430 }
8431 return false;
8432}
8433
John McCall48871652010-08-21 09:40:31 +00008434Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00008435 SourceLocation UsingLoc,
8436 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00008437 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00008438 SourceLocation IdentLoc,
8439 IdentifierInfo *NamespcName,
8440 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00008441 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8442 assert(NamespcName && "Invalid NamespcName.");
8443 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00008444
8445 // This can only happen along a recovery path.
Davide Italiano5be22332015-11-11 20:06:35 +00008446 while (S->isTemplateParamScope())
John McCall9b72f892010-11-10 02:40:36 +00008447 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00008448 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00008449
Craig Topperc3ec1492014-05-26 06:22:03 +00008450 UsingDirectiveDecl *UDir = nullptr;
8451 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregorcdf87022010-06-29 17:53:46 +00008452 if (SS.isSet())
Aaron Ballman4a979672014-01-03 13:56:08 +00008453 Qualifier = SS.getScopeRep();
Douglas Gregorcdf87022010-06-29 17:53:46 +00008454
Douglas Gregor34074322009-01-14 22:20:51 +00008455 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00008456 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
8457 LookupParsedName(R, S, &SS);
8458 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00008459 return nullptr;
John McCall27b18f82009-11-17 02:14:36 +00008460
Douglas Gregorcdf87022010-06-29 17:53:46 +00008461 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008462 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00008463 // Allow "using namespace std;" or "using namespace ::std;" even if
8464 // "std" hasn't been defined yet, for GCC compatibility.
8465 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
8466 NamespcName->isStr("std")) {
8467 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00008468 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00008469 R.resolveKind();
8470 }
8471 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00008472 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00008473 }
8474
John McCall9f3059a2009-10-09 21:13:30 +00008475 if (!R.empty()) {
Richard Smithf2005d32015-12-29 23:34:32 +00008476 NamedDecl *Named = R.getRepresentativeDecl();
8477 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
8478 assert(NS && "expected namespace decl");
Aaron Ballman43f40102014-11-14 22:34:56 +00008479
Nico Riecke50e59a2014-11-24 17:29:52 +00008480 // The use of a nested name specifier may trigger deprecation warnings.
8481 DiagnoseUseOfDecl(Named, IdentLoc);
Aaron Ballman43f40102014-11-14 22:34:56 +00008482
Douglas Gregor889ceb72009-02-03 19:21:40 +00008483 // C++ [namespace.udir]p1:
8484 // A using-directive specifies that the names in the nominated
8485 // namespace can be used in the scope in which the
8486 // using-directive appears after the using-directive. During
8487 // unqualified name lookup (3.4.1), the names appear as if they
8488 // were declared in the nearest enclosing namespace which
8489 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00008490 // namespace. [Note: in this context, "contains" means "contains
8491 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00008492
8493 // Find enclosing context containing both using-directive and
8494 // nominated namespace.
8495 DeclContext *CommonAncestor = cast<DeclContext>(NS);
8496 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
8497 CommonAncestor = CommonAncestor->getParent();
8498
Sebastian Redla6602e92009-11-23 15:34:23 +00008499 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00008500 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00008501 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00008502
Douglas Gregora172e082011-03-26 22:25:30 +00008503 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman5ba37d52013-08-22 00:27:10 +00008504 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00008505 Diag(IdentLoc, diag::warn_using_directive_in_header);
8506 }
8507
Douglas Gregor889ceb72009-02-03 19:21:40 +00008508 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00008509 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00008510 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00008511 }
8512
Richard Smith54ecd982013-02-20 19:22:51 +00008513 if (UDir)
8514 ProcessDeclAttributeList(S, UDir, AttrList);
8515
John McCall48871652010-08-21 09:40:31 +00008516 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00008517}
8518
8519void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith05afe5e2012-03-13 03:12:56 +00008520 // If the scope has an associated entity and the using directive is at
8521 // namespace or translation unit scope, add the UsingDirectiveDecl into
8522 // its lookup structure so qualified name lookup can find it.
Ted Kremenekc37877d2013-10-08 17:08:03 +00008523 DeclContext *Ctx = S->getEntity();
Richard Smith05afe5e2012-03-13 03:12:56 +00008524 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00008525 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00008526 else
Yaron Keren065da7c2014-05-20 18:23:05 +00008527 // Otherwise, it is at block scope. The using-directives will affect lookup
Richard Smith05afe5e2012-03-13 03:12:56 +00008528 // only to the end of the scope.
John McCall48871652010-08-21 09:40:31 +00008529 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00008530}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00008531
Douglas Gregorfec52632009-06-20 00:51:54 +00008532
John McCall48871652010-08-21 09:40:31 +00008533Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00008534 AccessSpecifier AS,
John McCall9b72f892010-11-10 02:40:36 +00008535 SourceLocation UsingLoc,
Richard Smith151c4562016-12-20 21:35:28 +00008536 SourceLocation TypenameLoc,
John McCall9b72f892010-11-10 02:40:36 +00008537 CXXScopeSpec &SS,
8538 UnqualifiedId &Name,
Richard Smith151c4562016-12-20 21:35:28 +00008539 SourceLocation EllipsisLoc,
8540 AttributeList *AttrList) {
Douglas Gregorfec52632009-06-20 00:51:54 +00008541 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00008542
Richard Smith151c4562016-12-20 21:35:28 +00008543 if (SS.isEmpty()) {
8544 Diag(Name.getLocStart(), diag::err_using_requires_qualname);
8545 return nullptr;
8546 }
8547
Douglas Gregor220f4272009-11-04 16:30:06 +00008548 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00008549 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00008550 case UnqualifiedId::IK_Identifier:
8551 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00008552 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00008553 case UnqualifiedId::IK_ConversionFunctionId:
8554 break;
8555
8556 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00008557 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smithd494c502012-04-27 19:33:05 +00008558 // C++11 inheriting constructors.
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008559 Diag(Name.getLocStart(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008560 getLangOpts().CPlusPlus11 ?
Richard Smithc2bc61b2013-03-18 21:12:30 +00008561 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smith0bf8a4922011-10-18 20:49:44 +00008562 diag::err_using_decl_constructor)
8563 << SS.getRange();
8564
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008565 if (getLangOpts().CPlusPlus11) break;
John McCall3969e302009-12-08 07:46:18 +00008566
Craig Topperc3ec1492014-05-26 06:22:03 +00008567 return nullptr;
8568
Douglas Gregor220f4272009-11-04 16:30:06 +00008569 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008570 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor220f4272009-11-04 16:30:06 +00008571 << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00008572 return nullptr;
8573
Douglas Gregor220f4272009-11-04 16:30:06 +00008574 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008575 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor220f4272009-11-04 16:30:06 +00008576 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00008577 return nullptr;
Douglas Gregor220f4272009-11-04 16:30:06 +00008578 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008579
8580 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
8581 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00008582 if (!TargetName)
Craig Topperc3ec1492014-05-26 06:22:03 +00008583 return nullptr;
John McCall3969e302009-12-08 07:46:18 +00008584
Richard Smithc2bc61b2013-03-18 21:12:30 +00008585 // Warn about access declarations.
Richard Smith6f1daa42016-12-16 00:58:48 +00008586 if (UsingLoc.isInvalid()) {
Enea Zaffanellac70b2512013-07-17 17:28:56 +00008587 Diag(Name.getLocStart(),
Richard Smithf026b602013-06-13 02:12:17 +00008588 getLangOpts().CPlusPlus11 ? diag::err_access_decl
8589 : diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00008590 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00008591 }
8592
Richard Smith151c4562016-12-20 21:35:28 +00008593 if (EllipsisLoc.isInvalid()) {
8594 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
8595 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
8596 return nullptr;
8597 } else {
8598 if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
8599 !TargetNameInfo.containsUnexpandedParameterPack()) {
8600 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
8601 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
8602 EllipsisLoc = SourceLocation();
8603 }
8604 }
Douglas Gregorc4356532010-12-16 00:46:58 +00008605
Richard Smith151c4562016-12-20 21:35:28 +00008606 NamedDecl *UD =
8607 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
8608 SS, TargetNameInfo, EllipsisLoc, AttrList,
8609 /*IsInstantiation*/false);
John McCallb96ec562009-12-04 22:46:56 +00008610 if (UD)
8611 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00008612
John McCall48871652010-08-21 09:40:31 +00008613 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00008614}
8615
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008616/// \brief Determine whether a using declaration considers the given
8617/// declarations as "equivalent", e.g., if they are redeclarations of
8618/// the same entity or are both typedefs of the same type.
Richard Smithfd8634a2013-10-23 02:17:46 +00008619static bool
8620IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
8621 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008622 return true;
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008623
Richard Smithdda56e42011-04-15 14:24:37 +00008624 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithfd8634a2013-10-23 02:17:46 +00008625 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008626 return Context.hasSameType(TD1->getUnderlyingType(),
8627 TD2->getUnderlyingType());
Douglas Gregor1d9ef842010-07-07 23:08:52 +00008628
8629 return false;
8630}
8631
8632
John McCall84d87672009-12-10 09:41:52 +00008633/// Determines whether to create a using shadow decl for a particular
8634/// decl, given the set of decls existing prior to this using lookup.
8635bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithfd8634a2013-10-23 02:17:46 +00008636 const LookupResult &Previous,
8637 UsingShadowDecl *&PrevShadow) {
John McCall84d87672009-12-10 09:41:52 +00008638 // Diagnose finding a decl which is not from a base class of the
8639 // current class. We do this now because there are cases where this
8640 // function will silently decide not to build a shadow decl, which
8641 // will pre-empt further diagnostics.
8642 //
Richard Smith5cbeb752016-05-05 02:13:49 +00008643 // We don't need to do this in C++11 because we do the check once on
John McCall84d87672009-12-10 09:41:52 +00008644 // the qualifier.
8645 //
8646 // FIXME: diagnose the following if we care enough:
8647 // struct A { int foo; };
8648 // struct B : A { using A::foo; };
8649 // template <class T> struct C : A {};
8650 // template <class T> struct D : C<T> { using B::foo; } // <---
8651 // This is invalid (during instantiation) in C++03 because B::foo
8652 // resolves to the using decl in B, which is not a base class of D<T>.
8653 // We can't diagnose it immediately because C<T> is an unknown
8654 // specialization. The UsingShadowDecl in D<T> then points directly
8655 // to A::foo, which will look well-formed when we instantiate.
8656 // The right solution is to not collapse the shadow-decl chain.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008657 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall84d87672009-12-10 09:41:52 +00008658 DeclContext *OrigDC = Orig->getDeclContext();
8659
8660 // Handle enums and anonymous structs.
8661 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
8662 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
8663 while (OrigRec->isAnonymousStructOrUnion())
8664 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
8665
8666 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
8667 if (OrigDC == CurContext) {
8668 Diag(Using->getLocation(),
8669 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008670 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00008671 Diag(Orig->getLocation(), diag::note_using_decl_target);
Richard Smith151c4562016-12-20 21:35:28 +00008672 Using->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00008673 return true;
8674 }
8675
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008676 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00008677 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008678 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00008679 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00008680 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00008681 Diag(Orig->getLocation(), diag::note_using_decl_target);
Richard Smith151c4562016-12-20 21:35:28 +00008682 Using->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00008683 return true;
8684 }
8685 }
8686
8687 if (Previous.empty()) return false;
8688
8689 NamedDecl *Target = Orig;
8690 if (isa<UsingShadowDecl>(Target))
8691 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
8692
John McCalla17e83e2009-12-11 02:33:26 +00008693 // If the target happens to be one of the previous declarations, we
8694 // don't have a conflict.
8695 //
8696 // FIXME: but we might be increasing its access, in which case we
8697 // should redeclare it.
Craig Topperc3ec1492014-05-26 06:22:03 +00008698 NamedDecl *NonTag = nullptr, *Tag = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00008699 bool FoundEquivalentDecl = false;
John McCalla17e83e2009-12-11 02:33:26 +00008700 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8701 I != E; ++I) {
8702 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithe5a91462016-02-27 02:36:43 +00008703 // We can have UsingDecls in our Previous results because we use the same
8704 // LookupResult for checking whether the UsingDecl itself is a valid
8705 // redeclaration.
Richard Smith151c4562016-12-20 21:35:28 +00008706 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
Richard Smithe5a91462016-02-27 02:36:43 +00008707 continue;
8708
Richard Smithfd8634a2013-10-23 02:17:46 +00008709 if (IsEquivalentForUsingDecl(Context, D, Target)) {
8710 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
8711 PrevShadow = Shadow;
8712 FoundEquivalentDecl = true;
Richard Smith2de44e62016-01-12 20:34:32 +00008713 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
8714 // We don't conflict with an existing using shadow decl of an equivalent
8715 // declaration, but we're not a redeclaration of it.
8716 FoundEquivalentDecl = true;
Richard Smithfd8634a2013-10-23 02:17:46 +00008717 }
John McCalla17e83e2009-12-11 02:33:26 +00008718
Richard Smithf091e122015-09-15 01:28:55 +00008719 if (isVisible(D))
8720 (isa<TagDecl>(D) ? Tag : NonTag) = D;
John McCalla17e83e2009-12-11 02:33:26 +00008721 }
8722
Richard Smithfd8634a2013-10-23 02:17:46 +00008723 if (FoundEquivalentDecl)
8724 return false;
8725
Alp Tokera2794f92014-01-22 07:29:52 +00008726 if (FunctionDecl *FD = Target->getAsFunction()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008727 NamedDecl *OldDecl = nullptr;
8728 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
8729 /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00008730 case Ovl_Overload:
8731 return false;
8732
8733 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00008734 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00008735 break;
Richard Smith18819302014-02-06 01:31:33 +00008736
John McCall84d87672009-12-10 09:41:52 +00008737 // We found a decl with the exact signature.
8738 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00008739 // If we're in a record, we want to hide the target, so we
8740 // return true (without a diagnostic) to tell the caller not to
8741 // build a shadow decl.
8742 if (CurContext->isRecord())
8743 return true;
8744
8745 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00008746 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00008747 break;
8748 }
8749
8750 Diag(Target->getLocation(), diag::note_using_decl_target);
8751 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
Richard Smith151c4562016-12-20 21:35:28 +00008752 Using->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00008753 return true;
8754 }
8755
8756 // Target is not a function.
8757
John McCall84d87672009-12-10 09:41:52 +00008758 if (isa<TagDecl>(Target)) {
8759 // No conflict between a tag and a non-tag.
8760 if (!Tag) return false;
8761
John McCalle29c5cd2009-12-10 19:51:03 +00008762 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00008763 Diag(Target->getLocation(), diag::note_using_decl_target);
8764 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
Richard Smith151c4562016-12-20 21:35:28 +00008765 Using->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00008766 return true;
8767 }
8768
8769 // No conflict between a tag and a non-tag.
8770 if (!NonTag) return false;
8771
John McCalle29c5cd2009-12-10 19:51:03 +00008772 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00008773 Diag(Target->getLocation(), diag::note_using_decl_target);
8774 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
Richard Smith151c4562016-12-20 21:35:28 +00008775 Using->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00008776 return true;
8777}
8778
Richard Smith5179eb72016-06-28 19:03:57 +00008779/// Determine whether a direct base class is a virtual base class.
8780static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
8781 if (!Derived->getNumVBases())
8782 return false;
8783 for (auto &B : Derived->bases())
8784 if (B.getType()->getAsCXXRecordDecl() == Base)
8785 return B.isVirtual();
8786 llvm_unreachable("not a direct base class");
8787}
8788
John McCall3f746822009-11-17 05:59:44 +00008789/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00008790UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00008791 UsingDecl *UD,
Richard Smithfd8634a2013-10-23 02:17:46 +00008792 NamedDecl *Orig,
8793 UsingShadowDecl *PrevDecl) {
John McCall3f746822009-11-17 05:59:44 +00008794 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00008795 NamedDecl *Target = Orig;
8796 if (isa<UsingShadowDecl>(Target)) {
8797 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
8798 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00008799 }
Richard Smithfd8634a2013-10-23 02:17:46 +00008800
Richard Smith5179eb72016-06-28 19:03:57 +00008801 NamedDecl *NonTemplateTarget = Target;
8802 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
8803 NonTemplateTarget = TargetTD->getTemplatedDecl();
8804
8805 UsingShadowDecl *Shadow;
8806 if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
8807 bool IsVirtualBase =
8808 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
8809 UD->getQualifier()->getAsRecordDecl());
8810 Shadow = ConstructorUsingShadowDecl::Create(
8811 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
8812 } else {
8813 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
8814 Target);
8815 }
John McCall3f746822009-11-17 05:59:44 +00008816 UD->addShadowDecl(Shadow);
Richard Smithfd8634a2013-10-23 02:17:46 +00008817
Douglas Gregor457104e2010-09-29 04:25:11 +00008818 Shadow->setAccess(UD->getAccess());
8819 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
8820 Shadow->setInvalidDecl();
Richard Smithfd8634a2013-10-23 02:17:46 +00008821
8822 Shadow->setPreviousDecl(PrevDecl);
8823
John McCall3f746822009-11-17 05:59:44 +00008824 if (S)
John McCall3969e302009-12-08 07:46:18 +00008825 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00008826 else
John McCall3969e302009-12-08 07:46:18 +00008827 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00008828
John McCall3969e302009-12-08 07:46:18 +00008829
John McCall84d87672009-12-10 09:41:52 +00008830 return Shadow;
8831}
John McCall3969e302009-12-08 07:46:18 +00008832
John McCall84d87672009-12-10 09:41:52 +00008833/// Hides a using shadow declaration. This is required by the current
8834/// using-decl implementation when a resolvable using declaration in a
8835/// class is followed by a declaration which would hide or override
8836/// one or more of the using decl's targets; for example:
8837///
8838/// struct Base { void foo(int); };
8839/// struct Derived : Base {
8840/// using Base::foo;
8841/// void foo(int);
8842/// };
8843///
8844/// The governing language is C++03 [namespace.udecl]p12:
8845///
8846/// When a using-declaration brings names from a base class into a
8847/// derived class scope, member functions in the derived class
8848/// override and/or hide member functions with the same name and
8849/// parameter types in a base class (rather than conflicting).
8850///
8851/// There are two ways to implement this:
8852/// (1) optimistically create shadow decls when they're not hidden
8853/// by existing declarations, or
8854/// (2) don't create any shadow decls (or at least don't make them
8855/// visible) until we've fully parsed/instantiated the class.
8856/// The problem with (1) is that we might have to retroactively remove
8857/// a shadow decl, which requires several O(n) operations because the
8858/// decl structures are (very reasonably) not designed for removal.
8859/// (2) avoids this but is very fiddly and phase-dependent.
8860void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00008861 if (Shadow->getDeclName().getNameKind() ==
8862 DeclarationName::CXXConversionFunctionName)
8863 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
8864
John McCall84d87672009-12-10 09:41:52 +00008865 // Remove it from the DeclContext...
8866 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00008867
John McCall84d87672009-12-10 09:41:52 +00008868 // ...and the scope, if applicable...
8869 if (S) {
John McCall48871652010-08-21 09:40:31 +00008870 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00008871 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00008872 }
8873
John McCall84d87672009-12-10 09:41:52 +00008874 // ...and the using decl.
8875 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
8876
8877 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00008878 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00008879}
8880
Richard Smith09d5b3a2014-05-01 00:35:04 +00008881/// Find the base specifier for a base class with the given type.
8882static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
8883 QualType DesiredBase,
8884 bool &AnyDependentBases) {
8885 // Check whether the named type is a direct base class.
8886 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
8887 for (auto &Base : Derived->bases()) {
8888 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
8889 if (CanonicalDesiredBase == BaseType)
8890 return &Base;
8891 if (BaseType->isDependentType())
8892 AnyDependentBases = true;
8893 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008894 return nullptr;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008895}
8896
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008897namespace {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008898class UsingValidatorCCC : public CorrectionCandidateCallback {
8899public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +00008900 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
Richard Smith09d5b3a2014-05-01 00:35:04 +00008901 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008902 : HasTypenameKeyword(HasTypenameKeyword),
Richard Smith09d5b3a2014-05-01 00:35:04 +00008903 IsInstantiation(IsInstantiation), OldNNS(NNS),
8904 RequireMemberOf(RequireMemberOf) {}
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008905
Craig Toppera798a9d2014-03-02 09:32:10 +00008906 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008907 NamedDecl *ND = Candidate.getCorrectionDecl();
8908
8909 // Keywords are not valid here.
8910 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008911 return false;
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008912
8913 // Completely unqualified names are invalid for a 'using' declaration.
8914 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
8915 return false;
8916
Richard Smith9385d702016-05-14 01:58:49 +00008917 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
8918 // reject.
8919
Richard Smith09d5b3a2014-05-01 00:35:04 +00008920 if (RequireMemberOf) {
8921 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
8922 if (FoundRecord && FoundRecord->isInjectedClassName()) {
8923 // No-one ever wants a using-declaration to name an injected-class-name
8924 // of a base class, unless they're declaring an inheriting constructor.
8925 ASTContext &Ctx = ND->getASTContext();
8926 if (!Ctx.getLangOpts().CPlusPlus11)
8927 return false;
8928 QualType FoundType = Ctx.getRecordType(FoundRecord);
8929
8930 // Check that the injected-class-name is named as a member of its own
8931 // type; we don't want to suggest 'using Derived::Base;', since that
8932 // means something else.
8933 NestedNameSpecifier *Specifier =
8934 Candidate.WillReplaceSpecifier()
8935 ? Candidate.getCorrectionSpecifier()
8936 : OldNNS;
8937 if (!Specifier->getAsType() ||
8938 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
8939 return false;
8940
8941 // Check that this inheriting constructor declaration actually names a
8942 // direct base class of the current class.
8943 bool AnyDependentBases = false;
8944 if (!findDirectBaseWithType(RequireMemberOf,
8945 Ctx.getRecordType(FoundRecord),
8946 AnyDependentBases) &&
8947 !AnyDependentBases)
8948 return false;
8949 } else {
8950 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
8951 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
8952 return false;
8953
8954 // FIXME: Check that the base class member is accessible?
8955 }
Kaelyn Takatad14c0612015-09-30 18:23:35 +00008956 } else {
8957 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
8958 if (FoundRecord && FoundRecord->isInjectedClassName())
8959 return false;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008960 }
8961
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008962 if (isa<TypeDecl>(ND))
8963 return HasTypenameKeyword || !IsInstantiation;
8964
8965 return !HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008966 }
8967
8968private:
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00008969 bool HasTypenameKeyword;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008970 bool IsInstantiation;
Richard Smith09d5b3a2014-05-01 00:35:04 +00008971 NestedNameSpecifier *OldNNS;
Richard Smith21866c32014-04-30 18:03:21 +00008972 CXXRecordDecl *RequireMemberOf;
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008973};
Benjamin Kramer8bf44352013-07-24 15:28:33 +00008974} // end anonymous namespace
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00008975
John McCalle61f2ba2009-11-18 02:36:19 +00008976/// Builds a using declaration.
8977///
8978/// \param IsInstantiation - Whether this call arises from an
8979/// instantiation of an unresolved using declaration. We treat
8980/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00008981NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
8982 SourceLocation UsingLoc,
Richard Smith151c4562016-12-20 21:35:28 +00008983 bool HasTypenameKeyword,
8984 SourceLocation TypenameLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00008985 CXXScopeSpec &SS,
Richard Smith09d5b3a2014-05-01 00:35:04 +00008986 DeclarationNameInfo NameInfo,
Richard Smith151c4562016-12-20 21:35:28 +00008987 SourceLocation EllipsisLoc,
Anders Carlsson696a3f12009-08-28 05:40:36 +00008988 AttributeList *AttrList,
Richard Smith151c4562016-12-20 21:35:28 +00008989 bool IsInstantiation) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00008990 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00008991 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00008992 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00008993
Anders Carlssonf038fc22009-08-28 05:49:21 +00008994 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00008995
Richard Smith5179eb72016-06-28 19:03:57 +00008996 // For an inheriting constructor declaration, the name of the using
8997 // declaration is the name of a constructor in this class, not in the
8998 // base class.
8999 DeclarationNameInfo UsingName = NameInfo;
9000 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9001 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9002 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9003 Context.getCanonicalType(Context.getRecordType(RD))));
9004
John McCall84d87672009-12-10 09:41:52 +00009005 // Do the redeclaration lookup in the current scope.
Richard Smith5179eb72016-06-28 19:03:57 +00009006 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00009007 ForRedeclaration);
9008 Previous.setHideTags(false);
9009 if (S) {
9010 LookupName(Previous, S);
9011
9012 // It is really dumb that we have to do this.
9013 LookupResult::Filter F = Previous.makeFilter();
9014 while (F.hasNext()) {
9015 NamedDecl *D = F.next();
9016 if (!isDeclInScope(D, CurContext, S))
9017 F.erase();
Richard Smith83e78f52014-04-11 01:03:38 +00009018 // If we found a local extern declaration that's not ordinarily visible,
9019 // and this declaration is being added to a non-block scope, ignore it.
9020 // We're only checking for scope conflicts here, not also for violations
9021 // of the linkage rules.
9022 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9023 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9024 F.erase();
John McCall84d87672009-12-10 09:41:52 +00009025 }
9026 F.done();
9027 } else {
9028 assert(IsInstantiation && "no scope in non-instantiation");
Richard Smithd8a9e372016-12-18 21:39:37 +00009029 if (CurContext->isRecord())
9030 LookupQualifiedName(Previous, CurContext);
9031 else {
9032 // No redeclaration check is needed here; in non-member contexts we
9033 // diagnosed all possible conflicts with other using-declarations when
9034 // building the template:
9035 //
9036 // For a dependent non-type using declaration, the only valid case is
9037 // if we instantiate to a single enumerator. We check for conflicts
9038 // between shadow declarations we introduce, and we check in the template
9039 // definition for conflicts between a non-type using declaration and any
9040 // other declaration, which together covers all cases.
9041 //
9042 // A dependent typename using declaration will never successfully
9043 // instantiate, since it will always name a class member, so we reject
9044 // that in the template definition.
9045 }
John McCall84d87672009-12-10 09:41:52 +00009046 }
9047
John McCall84d87672009-12-10 09:41:52 +00009048 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009049 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9050 SS, IdentLoc, Previous))
Craig Topperc3ec1492014-05-26 06:22:03 +00009051 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00009052
9053 // Check for bad qualifiers.
Richard Smithd8a9e372016-12-18 21:39:37 +00009054 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
9055 IdentLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00009056 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00009057
John McCall84c16cf2009-11-12 03:15:40 +00009058 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00009059 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009060 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
Richard Smith151c4562016-12-20 21:35:28 +00009061 if (!LookupContext || EllipsisLoc.isValid()) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009062 if (HasTypenameKeyword) {
John McCallb96ec562009-12-04 22:46:56 +00009063 // FIXME: not all declaration name kinds are legal here
9064 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9065 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009066 QualifierLoc,
Richard Smith151c4562016-12-20 21:35:28 +00009067 IdentLoc, NameInfo.getName(),
9068 EllipsisLoc);
John McCallb96ec562009-12-04 22:46:56 +00009069 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009070 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
Richard Smith151c4562016-12-20 21:35:28 +00009071 QualifierLoc, NameInfo, EllipsisLoc);
John McCalle61f2ba2009-11-18 02:36:19 +00009072 }
Richard Smith09d5b3a2014-05-01 00:35:04 +00009073 D->setAccess(AS);
9074 CurContext->addDecl(D);
9075 return D;
Anders Carlssonf038fc22009-08-28 05:49:21 +00009076 }
John McCallb96ec562009-12-04 22:46:56 +00009077
Richard Smith09d5b3a2014-05-01 00:35:04 +00009078 auto Build = [&](bool Invalid) {
9079 UsingDecl *UD =
Richard Smith5179eb72016-06-28 19:03:57 +00009080 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
9081 UsingName, HasTypenameKeyword);
Richard Smith09d5b3a2014-05-01 00:35:04 +00009082 UD->setAccess(AS);
9083 CurContext->addDecl(UD);
9084 UD->setInvalidDecl(Invalid);
John McCall3969e302009-12-08 07:46:18 +00009085 return UD;
Richard Smith09d5b3a2014-05-01 00:35:04 +00009086 };
9087 auto BuildInvalid = [&]{ return Build(true); };
9088 auto BuildValid = [&]{ return Build(false); };
9089
9090 if (RequireCompleteDeclContext(SS, LookupContext))
9091 return BuildInvalid();
Anders Carlsson59140b32009-08-28 03:16:11 +00009092
Richard Smith78163e22015-04-01 19:31:06 +00009093 // Look up the target name.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00009094 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00009095
John McCall3969e302009-12-08 07:46:18 +00009096 // Unlike most lookups, we don't always want to hide tag
9097 // declarations: tag names are visible through the using declaration
9098 // even if hidden by ordinary names, *except* in a dependent context
9099 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00009100 if (!IsInstantiation)
9101 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00009102
John McCall5dadb652012-04-07 03:04:20 +00009103 // For the purposes of this lookup, we have a base object type
9104 // equal to that of the current context.
9105 if (CurContext->isRecord()) {
9106 R.setBaseObjectType(
9107 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
9108 }
9109
John McCall27b18f82009-11-17 02:14:36 +00009110 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00009111
Richard Smith78163e22015-04-01 19:31:06 +00009112 // Try to correct typos if possible. If constructor name lookup finds no
9113 // results, that means the named class has no explicit constructors, and we
9114 // suppressed declaring implicit ones (probably because it's dependent or
9115 // invalid).
9116 if (R.empty() &&
9117 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00009118 if (TypoCorrection Corrected = CorrectTypo(
9119 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
9120 llvm::make_unique<UsingValidatorCCC>(
9121 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
9122 dyn_cast<CXXRecordDecl>(CurContext)),
9123 CTK_ErrorRecovery)) {
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009124 // We reject any correction for which ND would be NULL.
9125 NamedDecl *ND = Corrected.getCorrectionDecl();
Richard Smith09d5b3a2014-05-01 00:35:04 +00009126
Richard Smithf9b15102013-08-17 00:46:16 +00009127 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009128 // literal '0' below.
Richard Smithf9b15102013-08-17 00:46:16 +00009129 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
9130 << NameInfo.getName() << LookupContext << 0
9131 << SS.getRange());
Richard Smith09d5b3a2014-05-01 00:35:04 +00009132
9133 // If we corrected to an inheriting constructor, handle it as one.
9134 auto *RD = dyn_cast<CXXRecordDecl>(ND);
9135 if (RD && RD->isInjectedClassName()) {
Richard Smith5179eb72016-06-28 19:03:57 +00009136 // The parent of the injected class name is the class itself.
9137 RD = cast<CXXRecordDecl>(RD->getParent());
9138
Richard Smith09d5b3a2014-05-01 00:35:04 +00009139 // Fix up the information we'll use to build the using declaration.
9140 if (Corrected.WillReplaceSpecifier()) {
9141 NestedNameSpecifierLocBuilder Builder;
9142 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
9143 QualifierLoc.getSourceRange());
9144 QualifierLoc = Builder.getWithLocInContext(Context);
9145 }
9146
Richard Smith5179eb72016-06-28 19:03:57 +00009147 // In this case, the name we introduce is the name of a derived class
9148 // constructor.
9149 auto *CurClass = cast<CXXRecordDecl>(CurContext);
9150 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9151 Context.getCanonicalType(Context.getRecordType(CurClass))));
9152 UsingName.setNamedTypeInfo(nullptr);
Richard Smith78163e22015-04-01 19:31:06 +00009153 for (auto *Ctor : LookupConstructors(RD))
9154 R.addDecl(Ctor);
Richard Smith5179eb72016-06-28 19:03:57 +00009155 R.resolveKind();
Richard Smith78163e22015-04-01 19:31:06 +00009156 } else {
Richard Smith5179eb72016-06-28 19:03:57 +00009157 // FIXME: Pick up all the declarations if we found an overloaded
9158 // function.
9159 UsingName.setName(ND->getDeclName());
Richard Smith78163e22015-04-01 19:31:06 +00009160 R.addDecl(ND);
Richard Smith09d5b3a2014-05-01 00:35:04 +00009161 }
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009162 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00009163 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009164 << NameInfo.getName() << LookupContext << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00009165 return BuildInvalid();
Kaelyn Uhrain8ec9f5f2013-07-10 17:34:22 +00009166 }
Douglas Gregorfec52632009-06-20 00:51:54 +00009167 }
9168
Richard Smith09d5b3a2014-05-01 00:35:04 +00009169 if (R.isAmbiguous())
9170 return BuildInvalid();
Mike Stump11289f42009-09-09 15:08:12 +00009171
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009172 if (HasTypenameKeyword) {
John McCalle61f2ba2009-11-18 02:36:19 +00009173 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00009174 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00009175 Diag(IdentLoc, diag::err_using_typename_non_type);
9176 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9177 Diag((*I)->getUnderlyingDecl()->getLocation(),
9178 diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00009179 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00009180 }
9181 } else {
9182 // If we asked for a non-typename and we got a type, error out,
9183 // but only if this is an instantiation of an unresolved using
9184 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00009185 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00009186 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
9187 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
Richard Smith09d5b3a2014-05-01 00:35:04 +00009188 return BuildInvalid();
John McCalle61f2ba2009-11-18 02:36:19 +00009189 }
Anders Carlsson59140b32009-08-28 03:16:11 +00009190 }
9191
Richard Smith5cbeb752016-05-05 02:13:49 +00009192 // C++14 [namespace.udecl]p6:
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00009193 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00009194 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00009195 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
9196 << SS.getRange();
Richard Smith09d5b3a2014-05-01 00:35:04 +00009197 return BuildInvalid();
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00009198 }
Mike Stump11289f42009-09-09 15:08:12 +00009199
Richard Smith5cbeb752016-05-05 02:13:49 +00009200 // C++14 [namespace.udecl]p7:
9201 // A using-declaration shall not name a scoped enumerator.
9202 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
9203 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
9204 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
9205 << SS.getRange();
9206 return BuildInvalid();
9207 }
9208 }
9209
Richard Smith09d5b3a2014-05-01 00:35:04 +00009210 UsingDecl *UD = BuildValid();
Richard Smith78163e22015-04-01 19:31:06 +00009211
Richard Smith5179eb72016-06-28 19:03:57 +00009212 // Some additional rules apply to inheriting constructors.
9213 if (UsingName.getName().getNameKind() ==
9214 DeclarationName::CXXConstructorName) {
Richard Smith78163e22015-04-01 19:31:06 +00009215 // Suppress access diagnostics; the access check is instead performed at the
9216 // point of use for an inheriting constructor.
9217 R.suppressDiagnostics();
Richard Smith5179eb72016-06-28 19:03:57 +00009218 if (CheckInheritingConstructorUsingDecl(UD))
9219 return UD;
Richard Smith78163e22015-04-01 19:31:06 +00009220 }
9221
John McCall84d87672009-12-10 09:41:52 +00009222 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00009223 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00009224 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
9225 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00009226 }
John McCall3f746822009-11-17 05:59:44 +00009227
9228 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00009229}
9230
Richard Smith151c4562016-12-20 21:35:28 +00009231NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
9232 ArrayRef<NamedDecl *> Expansions) {
9233 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
9234 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
9235 isa<UsingPackDecl>(InstantiatedFrom));
9236
9237 auto *UPD =
9238 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
9239 UPD->setAccess(InstantiatedFrom->getAccess());
9240 CurContext->addDecl(UPD);
9241 return UPD;
9242}
9243
Sebastian Redl08905022011-02-05 19:23:19 +00009244/// Additional checks for a using declaration referring to a constructor name.
Richard Smith23d55872012-04-02 01:30:27 +00009245bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009246 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redl08905022011-02-05 19:23:19 +00009247
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009248 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00009249 assert(SourceType &&
9250 "Using decl naming constructor doesn't have type in scope spec.");
9251 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
9252
9253 // Check whether the named type is a direct base class.
Richard Smith09d5b3a2014-05-01 00:35:04 +00009254 bool AnyDependentBases = false;
9255 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
9256 AnyDependentBases);
9257 if (!Base && !AnyDependentBases) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009258 Diag(UD->getUsingLoc(),
Sebastian Redl08905022011-02-05 19:23:19 +00009259 diag::err_using_decl_constructor_not_in_direct_base)
9260 << UD->getNameInfo().getSourceRange()
9261 << QualType(SourceType, 0) << TargetClass;
Richard Smith09d5b3a2014-05-01 00:35:04 +00009262 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00009263 return true;
9264 }
9265
Richard Smith09d5b3a2014-05-01 00:35:04 +00009266 if (Base)
9267 Base->setInheritConstructors();
Sebastian Redl08905022011-02-05 19:23:19 +00009268
9269 return false;
9270}
9271
John McCall84d87672009-12-10 09:41:52 +00009272/// Checks that the given using declaration is not an invalid
9273/// redeclaration. Note that this is checking only for the using decl
9274/// itself, not for any ill-formedness among the UsingShadowDecls.
9275bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009276 bool HasTypenameKeyword,
John McCall84d87672009-12-10 09:41:52 +00009277 const CXXScopeSpec &SS,
9278 SourceLocation NameLoc,
9279 const LookupResult &Prev) {
Richard Smith4eeaec42016-12-18 22:01:46 +00009280 NestedNameSpecifier *Qual = SS.getScopeRep();
9281
John McCall84d87672009-12-10 09:41:52 +00009282 // C++03 [namespace.udecl]p8:
9283 // C++0x [namespace.udecl]p10:
9284 // A using-declaration is a declaration and can therefore be used
9285 // repeatedly where (and only where) multiple declarations are
9286 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00009287 //
John McCall032092f2010-11-29 18:01:58 +00009288 // That's in non-member contexts.
Richard Smith4eeaec42016-12-18 22:01:46 +00009289 if (!CurContext->getRedeclContext()->isRecord()) {
9290 // A dependent qualifier outside a class can only ever resolve to an
9291 // enumeration type. Therefore it conflicts with any other non-type
9292 // declaration in the same scope.
9293 // FIXME: How should we check for dependent type-type conflicts at block
9294 // scope?
9295 if (Qual->isDependent() && !HasTypenameKeyword) {
9296 for (auto *D : Prev) {
Richard Smith151c4562016-12-20 21:35:28 +00009297 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
Richard Smith4eeaec42016-12-18 22:01:46 +00009298 bool OldCouldBeEnumerator =
9299 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
9300 Diag(NameLoc,
9301 OldCouldBeEnumerator ? diag::err_redefinition
9302 : diag::err_redefinition_different_kind)
9303 << Prev.getLookupName();
9304 Diag(D->getLocation(), diag::note_previous_definition);
9305 return true;
9306 }
9307 }
9308 }
John McCall84d87672009-12-10 09:41:52 +00009309 return false;
Richard Smith4eeaec42016-12-18 22:01:46 +00009310 }
John McCall84d87672009-12-10 09:41:52 +00009311
9312 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
9313 NamedDecl *D = *I;
9314
9315 bool DTypename;
9316 NestedNameSpecifier *DQual;
9317 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009318 DTypename = UD->hasTypename();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009319 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00009320 } else if (UnresolvedUsingValueDecl *UD
9321 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
9322 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009323 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00009324 } else if (UnresolvedUsingTypenameDecl *UD
9325 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
9326 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00009327 DQual = UD->getQualifier();
Richard Smith4eeaec42016-12-18 22:01:46 +00009328 } else continue;
John McCall84d87672009-12-10 09:41:52 +00009329
9330 // using decls differ if one says 'typename' and the other doesn't.
9331 // FIXME: non-dependent using decls?
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00009332 if (HasTypenameKeyword != DTypename) continue;
John McCall84d87672009-12-10 09:41:52 +00009333
9334 // using decls differ if they name different scopes (but note that
9335 // template instantiation can cause this check to trigger when it
9336 // didn't before instantiation).
9337 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
9338 Context.getCanonicalNestedNameSpecifier(DQual))
9339 continue;
9340
9341 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00009342 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00009343 return true;
9344 }
9345
9346 return false;
9347}
9348
John McCall3969e302009-12-08 07:46:18 +00009349
John McCallb96ec562009-12-04 22:46:56 +00009350/// Checks that the given nested-name qualifier used in a using decl
9351/// in the current context is appropriately related to the current
9352/// scope. If an error is found, diagnoses it and returns true.
9353bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
Richard Smithd8a9e372016-12-18 21:39:37 +00009354 bool HasTypename,
John McCallb96ec562009-12-04 22:46:56 +00009355 const CXXScopeSpec &SS,
Richard Smith7ad0b882014-04-02 21:44:35 +00009356 const DeclarationNameInfo &NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00009357 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00009358 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00009359
John McCall3969e302009-12-08 07:46:18 +00009360 if (!CurContext->isRecord()) {
9361 // C++03 [namespace.udecl]p3:
9362 // C++0x [namespace.udecl]p8:
9363 // A using-declaration for a class member shall be a member-declaration.
9364
Richard Smithd8a9e372016-12-18 21:39:37 +00009365 // If we weren't able to compute a valid scope, it might validly be a
9366 // dependent class scope or a dependent enumeration unscoped scope. If
9367 // we have a 'typename' keyword, the scope must resolve to a class type.
9368 if ((HasTypename && !NamedContext) ||
9369 (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
Richard Smith5cbeb752016-05-05 02:13:49 +00009370 auto *RD = NamedContext
9371 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
9372 : nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00009373 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
Craig Topperc3ec1492014-05-26 06:22:03 +00009374 RD = nullptr;
Richard Smith7ad0b882014-04-02 21:44:35 +00009375
John McCall3969e302009-12-08 07:46:18 +00009376 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
9377 << SS.getRange();
Richard Smith7ad0b882014-04-02 21:44:35 +00009378
9379 // If we have a complete, non-dependent source type, try to suggest a
9380 // way to get the same effect.
9381 if (!RD)
9382 return true;
9383
9384 // Find what this using-declaration was referring to.
9385 LookupResult R(*this, NameInfo, LookupOrdinaryName);
9386 R.setHideTags(false);
9387 R.suppressDiagnostics();
9388 LookupQualifiedName(R, RD);
9389
9390 if (R.getAsSingle<TypeDecl>()) {
9391 if (getLangOpts().CPlusPlus11) {
9392 // Convert 'using X::Y;' to 'using Y = X::Y;'.
9393 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
9394 << 0 // alias declaration
9395 << FixItHint::CreateInsertion(SS.getBeginLoc(),
9396 NameInfo.getName().getAsString() +
9397 " = ");
9398 } else {
9399 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
9400 SourceLocation InsertLoc =
Craig Topper07fa1762015-11-15 02:31:46 +00009401 getLocForEndOfToken(NameInfo.getLocEnd());
Richard Smith7ad0b882014-04-02 21:44:35 +00009402 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
9403 << 1 // typedef declaration
9404 << FixItHint::CreateReplacement(UsingLoc, "typedef")
9405 << FixItHint::CreateInsertion(
9406 InsertLoc, " " + NameInfo.getName().getAsString());
9407 }
9408 } else if (R.getAsSingle<VarDecl>()) {
9409 // Don't provide a fixit outside C++11 mode; we don't want to suggest
9410 // repeating the type of the static data member here.
9411 FixItHint FixIt;
9412 if (getLangOpts().CPlusPlus11) {
9413 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9414 FixIt = FixItHint::CreateReplacement(
9415 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
9416 }
9417
9418 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9419 << 2 // reference declaration
9420 << FixIt;
Richard Smithdce10ea2016-05-05 19:16:15 +00009421 } else if (R.getAsSingle<EnumConstantDecl>()) {
9422 // Don't provide a fixit outside C++11 mode; we don't want to suggest
9423 // repeating the type of the enumeration here, and we can't do so if
9424 // the type is anonymous.
9425 FixItHint FixIt;
9426 if (getLangOpts().CPlusPlus11) {
9427 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9428 FixIt = FixItHint::CreateReplacement(
Richard Smithd8a9e372016-12-18 21:39:37 +00009429 UsingLoc,
9430 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
Richard Smithdce10ea2016-05-05 19:16:15 +00009431 }
9432
9433 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9434 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
9435 << FixIt;
Richard Smith7ad0b882014-04-02 21:44:35 +00009436 }
John McCall3969e302009-12-08 07:46:18 +00009437 return true;
9438 }
9439
Richard Smithd8a9e372016-12-18 21:39:37 +00009440 // Otherwise, this might be valid.
John McCall3969e302009-12-08 07:46:18 +00009441 return false;
9442 }
9443
9444 // The current scope is a record.
9445
9446 // If the named context is dependent, we can't decide much.
9447 if (!NamedContext) {
9448 // FIXME: in C++0x, we can diagnose if we can prove that the
9449 // nested-name-specifier does not refer to a base class, which is
9450 // still possible in some cases.
9451
9452 // Otherwise we have to conservatively report that things might be
9453 // okay.
9454 return false;
9455 }
9456
9457 if (!NamedContext->isRecord()) {
9458 // Ideally this would point at the last name in the specifier,
9459 // but we don't have that level of source info.
9460 Diag(SS.getRange().getBegin(),
9461 diag::err_using_decl_nested_name_specifier_is_not_class)
Aaron Ballman5fe6c802014-01-03 13:45:46 +00009462 << SS.getScopeRep() << SS.getRange();
John McCall3969e302009-12-08 07:46:18 +00009463 return true;
9464 }
9465
Douglas Gregor7c842292010-12-21 07:41:49 +00009466 if (!NamedContext->isDependentContext() &&
9467 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
9468 return true;
9469
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009470 if (getLangOpts().CPlusPlus11) {
Richard Smith5cbeb752016-05-05 02:13:49 +00009471 // C++11 [namespace.udecl]p3:
John McCall3969e302009-12-08 07:46:18 +00009472 // In a using-declaration used as a member-declaration, the
9473 // nested-name-specifier shall name a base class of the class
9474 // being defined.
9475
9476 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
9477 cast<CXXRecordDecl>(NamedContext))) {
9478 if (CurContext == NamedContext) {
9479 Diag(NameLoc,
9480 diag::err_using_decl_nested_name_specifier_is_current_class)
9481 << SS.getRange();
9482 return true;
9483 }
9484
Eric Fiselier7ae80c62016-10-10 14:26:40 +00009485 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
9486 Diag(SS.getRange().getBegin(),
9487 diag::err_using_decl_nested_name_specifier_is_not_base_class)
9488 << SS.getScopeRep()
9489 << cast<CXXRecordDecl>(CurContext)
9490 << SS.getRange();
9491 }
John McCall3969e302009-12-08 07:46:18 +00009492 return true;
9493 }
9494
9495 return false;
9496 }
9497
9498 // C++03 [namespace.udecl]p4:
9499 // A using-declaration used as a member-declaration shall refer
9500 // to a member of a base class of the class being defined [etc.].
9501
9502 // Salient point: SS doesn't have to name a base class as long as
9503 // lookup only finds members from base classes. Therefore we can
9504 // diagnose here only if we can prove that that can't happen,
9505 // i.e. if the class hierarchies provably don't intersect.
9506
9507 // TODO: it would be nice if "definitely valid" results were cached
9508 // in the UsingDecl and UsingShadowDecl so that these checks didn't
9509 // need to be repeated.
9510
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00009511 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
9512 auto Collect = [&Bases](const CXXRecordDecl *Base) {
9513 Bases.insert(Base);
9514 return true;
John McCall3969e302009-12-08 07:46:18 +00009515 };
9516
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00009517 // Collect all bases. Return false if we find a dependent base.
9518 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
John McCall3969e302009-12-08 07:46:18 +00009519 return false;
9520
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00009521 // Returns true if the base is dependent or is one of the accumulated base
9522 // classes.
9523 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
9524 return !Bases.count(Base);
9525 };
9526
9527 // Return false if the class has a dependent base or if it or one
John McCall3969e302009-12-08 07:46:18 +00009528 // of its bases is present in the base set of the current context.
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +00009529 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
9530 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
John McCall3969e302009-12-08 07:46:18 +00009531 return false;
9532
9533 Diag(SS.getRange().getBegin(),
9534 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Aaron Ballman4a979672014-01-03 13:56:08 +00009535 << SS.getScopeRep()
John McCall3969e302009-12-08 07:46:18 +00009536 << cast<CXXRecordDecl>(CurContext)
9537 << SS.getRange();
9538
9539 return true;
John McCallb96ec562009-12-04 22:46:56 +00009540}
9541
Richard Smithdda56e42011-04-15 14:24:37 +00009542Decl *Sema::ActOnAliasDeclaration(Scope *S,
9543 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00009544 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00009545 SourceLocation UsingLoc,
9546 UnqualifiedId &Name,
Richard Smith54ecd982013-02-20 19:22:51 +00009547 AttributeList *AttrList,
David Majnemerf9bde282015-03-11 06:45:39 +00009548 TypeResult Type,
9549 Decl *DeclFromDeclSpec) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00009550 // Skip up to the relevant declaration scope.
Davide Italiano5be22332015-11-11 20:06:35 +00009551 while (S->isTemplateParamScope())
Richard Smith3f1b5d02011-05-05 21:57:07 +00009552 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00009553 assert((S->getFlags() & Scope::DeclScope) &&
9554 "got alias-declaration outside of declaration scope");
9555
9556 if (Type.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00009557 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00009558
9559 bool Invalid = false;
9560 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
Craig Topperc3ec1492014-05-26 06:22:03 +00009561 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky82e47802011-05-02 01:07:19 +00009562 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00009563
9564 if (DiagnoseClassNameShadow(CurContext, NameInfo))
Craig Topperc3ec1492014-05-26 06:22:03 +00009565 return nullptr;
Richard Smithdda56e42011-04-15 14:24:37 +00009566
9567 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00009568 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00009569 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00009570 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9571 TInfo->getTypeLoc().getBeginLoc());
9572 }
Richard Smithdda56e42011-04-15 14:24:37 +00009573
9574 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
9575 LookupName(Previous, S);
9576
9577 // Warn about shadowing the name of a template parameter.
9578 if (Previous.isSingleResult() &&
9579 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00009580 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00009581 Previous.clear();
9582 }
9583
9584 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
9585 "name in alias declaration must be an identifier");
9586 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
9587 Name.StartLocation,
9588 Name.Identifier, TInfo);
9589
9590 NewTD->setAccess(AS);
9591
9592 if (Invalid)
9593 NewTD->setInvalidDecl();
9594
Richard Smith54ecd982013-02-20 19:22:51 +00009595 ProcessDeclAttributeList(S, NewTD, AttrList);
9596
Richard Smith3f1b5d02011-05-05 21:57:07 +00009597 CheckTypedefForVariablyModifiedType(S, NewTD);
9598 Invalid |= NewTD->isInvalidDecl();
9599
Richard Smithdda56e42011-04-15 14:24:37 +00009600 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00009601
9602 NamedDecl *NewND;
9603 if (TemplateParamLists.size()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00009604 TypeAliasTemplateDecl *OldDecl = nullptr;
9605 TemplateParameterList *OldTemplateParams = nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00009606
9607 if (TemplateParamLists.size() != 1) {
9608 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009609 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
9610 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3f1b5d02011-05-05 21:57:07 +00009611 }
Benjamin Kramer62b95d82012-08-23 21:35:17 +00009612 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3f1b5d02011-05-05 21:57:07 +00009613
Richard Smith882593f2016-04-06 17:38:58 +00009614 // Check that we can declare a template here.
9615 if (CheckTemplateDeclScope(S, TemplateParams))
9616 return nullptr;
9617
Richard Smith3f1b5d02011-05-05 21:57:07 +00009618 // Only consider previous declarations in the same scope.
9619 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
9620 /*ExplicitInstantiationOrSpecialization*/false);
9621 if (!Previous.empty()) {
9622 Redeclaration = true;
9623
9624 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
9625 if (!OldDecl && !Invalid) {
9626 Diag(UsingLoc, diag::err_redefinition_different_kind)
9627 << Name.Identifier;
9628
9629 NamedDecl *OldD = Previous.getRepresentativeDecl();
9630 if (OldD->getLocation().isValid())
9631 Diag(OldD->getLocation(), diag::note_previous_definition);
9632
9633 Invalid = true;
9634 }
9635
9636 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
9637 if (TemplateParameterListsAreEqual(TemplateParams,
9638 OldDecl->getTemplateParameters(),
9639 /*Complain=*/true,
9640 TPL_TemplateMatch))
9641 OldTemplateParams = OldDecl->getTemplateParameters();
9642 else
9643 Invalid = true;
9644
9645 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
9646 if (!Invalid &&
9647 !Context.hasSameType(OldTD->getUnderlyingType(),
9648 NewTD->getUnderlyingType())) {
9649 // FIXME: The C++0x standard does not clearly say this is ill-formed,
9650 // but we can't reasonably accept it.
9651 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
9652 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
9653 if (OldTD->getLocation().isValid())
9654 Diag(OldTD->getLocation(), diag::note_previous_definition);
9655 Invalid = true;
9656 }
9657 }
9658 }
9659
9660 // Merge any previous default template arguments into our parameters,
9661 // and check the parameter list.
9662 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
9663 TPC_TypeAliasTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +00009664 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +00009665
9666 TypeAliasTemplateDecl *NewDecl =
9667 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
9668 Name.Identifier, TemplateParams,
9669 NewTD);
Richard Smith43ccec8e2014-08-26 03:52:16 +00009670 NewTD->setDescribedAliasTemplate(NewDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00009671
9672 NewDecl->setAccess(AS);
9673
9674 if (Invalid)
9675 NewDecl->setInvalidDecl();
9676 else if (OldDecl)
Rafael Espindola8db352d2013-10-17 15:37:26 +00009677 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3f1b5d02011-05-05 21:57:07 +00009678
9679 NewND = NewDecl;
9680 } else {
David Majnemerf9bde282015-03-11 06:45:39 +00009681 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
9682 setTagNameForLinkagePurposes(TD, NewTD);
9683 handleTagNumbering(TD, S);
9684 }
Richard Smith3f1b5d02011-05-05 21:57:07 +00009685 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
9686 NewND = NewTD;
9687 }
Richard Smithdda56e42011-04-15 14:24:37 +00009688
Richard Smith3cbf3f12016-07-15 20:53:25 +00009689 PushOnScopeChains(NewND, S);
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +00009690 ActOnDocumentableDecl(NewND);
Richard Smith3f1b5d02011-05-05 21:57:07 +00009691 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00009692}
9693
Richard Smithf4634362014-09-03 23:11:22 +00009694Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
9695 SourceLocation AliasLoc,
9696 IdentifierInfo *Alias, CXXScopeSpec &SS,
9697 SourceLocation IdentLoc,
9698 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00009699
Anders Carlssonbb1e4722009-03-28 23:53:49 +00009700 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00009701 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
9702 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00009703
John McCall27b18f82009-11-17 02:14:36 +00009704 if (R.isAmbiguous())
Craig Topperc3ec1492014-05-26 06:22:03 +00009705 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00009706
John McCall9f3059a2009-10-09 21:13:30 +00009707 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00009708 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smitha9746882012-04-05 23:13:23 +00009709 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Craig Topperc3ec1492014-05-26 06:22:03 +00009710 return nullptr;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00009711 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00009712 }
Richard Smithf4634362014-09-03 23:11:22 +00009713 assert(!R.isAmbiguous() && !R.empty());
Richard Smithf2005d32015-12-29 23:34:32 +00009714 NamedDecl *ND = R.getRepresentativeDecl();
Richard Smithf4634362014-09-03 23:11:22 +00009715
9716 // Check if we have a previous declaration with the same name.
Richard Smith10568d82015-11-17 03:02:41 +00009717 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
9718 ForRedeclaration);
Richard Smith2b2a1762015-12-03 23:24:04 +00009719 LookupName(PrevR, S);
Richard Smithf4634362014-09-03 23:11:22 +00009720
Richard Smith2b2a1762015-12-03 23:24:04 +00009721 // Check we're not shadowing a template parameter.
9722 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
9723 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
9724 PrevR.clear();
9725 }
Aaron Ballman43f40102014-11-14 22:34:56 +00009726
Richard Smith2b2a1762015-12-03 23:24:04 +00009727 // Filter out any other lookup result from an enclosing scope.
9728 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
9729 /*AllowInlineNamespace*/false);
9730
9731 // Find the previous declaration and check that we can redeclare it.
9732 NamespaceAliasDecl *Prev = nullptr;
Richard Smith7d8d6722015-12-29 23:42:34 +00009733 if (PrevR.isSingleResult()) {
9734 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
9735 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Richard Smithf4634362014-09-03 23:11:22 +00009736 // We already have an alias with the same name that points to the same
9737 // namespace; check that it matches.
Richard Smith2b2a1762015-12-03 23:24:04 +00009738 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
9739 Prev = AD;
9740 } else if (isVisible(PrevDecl)) {
Richard Smithf4634362014-09-03 23:11:22 +00009741 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
9742 << Alias;
Richard Smithf2005d32015-12-29 23:34:32 +00009743 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
Richard Smithf4634362014-09-03 23:11:22 +00009744 << AD->getNamespace();
9745 return nullptr;
9746 }
Richard Smith2b2a1762015-12-03 23:24:04 +00009747 } else if (isVisible(PrevDecl)) {
Richard Smith7d8d6722015-12-29 23:42:34 +00009748 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
Richard Smithf4634362014-09-03 23:11:22 +00009749 ? diag::err_redefinition
9750 : diag::err_redefinition_different_kind;
9751 Diag(AliasLoc, DiagID) << Alias;
9752 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
9753 return nullptr;
9754 }
9755 }
Mike Stump11289f42009-09-09 15:08:12 +00009756
Nico Riecke50e59a2014-11-24 17:29:52 +00009757 // The use of a nested name specifier may trigger deprecation warnings.
Aaron Ballman43f40102014-11-14 22:34:56 +00009758 DiagnoseUseOfDecl(ND, IdentLoc);
9759
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00009760 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00009761 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00009762 Alias, SS.getWithLocInContext(Context),
Aaron Ballman43f40102014-11-14 22:34:56 +00009763 IdentLoc, ND);
Richard Smith2b2a1762015-12-03 23:24:04 +00009764 if (Prev)
9765 AliasDecl->setPreviousDecl(Prev);
Mike Stump11289f42009-09-09 15:08:12 +00009766
John McCalld8d0d432010-02-16 06:53:13 +00009767 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00009768 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00009769}
9770
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00009771Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +00009772Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
9773 CXXMethodDecl *MD) {
9774 CXXRecordDecl *ClassDecl = MD->getParent();
9775
Douglas Gregor6d880b12010-07-01 22:31:05 +00009776 // C++ [except.spec]p14:
9777 // An implicitly declared special member function (Clause 12) shall have an
9778 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +00009779 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00009780 if (ClassDecl->isInvalidDecl())
9781 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00009782
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009783 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +00009784 for (const auto &B : ClassDecl->bases()) {
9785 if (B.isVirtual()) // Handled below.
Douglas Gregor6d880b12010-07-01 22:31:05 +00009786 continue;
9787
Aaron Ballman574705e2014-03-13 15:41:46 +00009788 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00009789 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00009790 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
9791 // If this is a deleted function, add it anyway. This might be conformant
9792 // with the standard. This might not. I'm not sure. It might not matter.
9793 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +00009794 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00009795 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00009796 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009797
9798 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +00009799 for (const auto &B : ClassDecl->vbases()) {
9800 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor9672f922010-07-03 00:47:00 +00009801 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00009802 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
9803 // If this is a deleted function, add it anyway. This might be conformant
9804 // with the standard. This might not. I'm not sure. It might not matter.
9805 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00009806 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00009807 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00009808 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00009809
9810 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009811 for (const auto *F : ClassDecl->fields()) {
Richard Smith938f40b2011-06-11 17:19:42 +00009812 if (F->hasInClassInitializer()) {
9813 if (Expr *E = F->getInClassInitializer())
9814 ExceptSpec.CalledExpr(E);
Richard Smith938f40b2011-06-11 17:19:42 +00009815 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00009816 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00009817 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9818 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
9819 // If this is a deleted function, add it anyway. This might be conformant
9820 // with the standard. This might not. I'm not sure. It might not matter.
9821 // In particular, the problem is that this function never gets called. It
9822 // might just be ill-formed because this function attempts to refer to
9823 // a deleted function here.
9824 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +00009825 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00009826 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00009827 }
John McCalldb40c7f2010-12-14 08:05:40 +00009828
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00009829 return ExceptSpec;
9830}
9831
Richard Smithc2bc61b2013-03-18 21:12:30 +00009832Sema::ImplicitExceptionSpecification
Richard Smith5179eb72016-06-28 19:03:57 +00009833Sema::ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
9834 CXXConstructorDecl *CD) {
Richard Smithb7151b92013-04-10 06:11:48 +00009835 CXXRecordDecl *ClassDecl = CD->getParent();
9836
9837 // C++ [except.spec]p14:
9838 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smithc2bc61b2013-03-18 21:12:30 +00009839 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smithb7151b92013-04-10 06:11:48 +00009840 if (ClassDecl->isInvalidDecl())
9841 return ExceptSpec;
9842
Richard Smith5179eb72016-06-28 19:03:57 +00009843 auto Inherited = CD->getInheritedConstructor();
9844 InheritedConstructorInfo ICI(*this, Loc, Inherited.getShadowDecl());
Richard Smithb7151b92013-04-10 06:11:48 +00009845
Richard Smith5179eb72016-06-28 19:03:57 +00009846 // Direct and virtual base-class constructors.
9847 for (bool VBase : {false, true}) {
9848 for (CXXBaseSpecifier &B :
9849 VBase ? ClassDecl->vbases() : ClassDecl->bases()) {
9850 // Don't visit direct vbases twice.
9851 if (B.isVirtual() != VBase)
Richard Smithb7151b92013-04-10 06:11:48 +00009852 continue;
Richard Smithb7151b92013-04-10 06:11:48 +00009853
Richard Smith5179eb72016-06-28 19:03:57 +00009854 CXXRecordDecl *BaseClass = B.getType()->getAsCXXRecordDecl();
9855 if (!BaseClass)
Richard Smithb7151b92013-04-10 06:11:48 +00009856 continue;
Richard Smith5179eb72016-06-28 19:03:57 +00009857
9858 CXXConstructorDecl *Constructor =
9859 ICI.findConstructorForBase(BaseClass, Inherited.getConstructor())
9860 .first;
9861 if (!Constructor)
9862 Constructor = LookupDefaultConstructor(BaseClass);
Richard Smithb7151b92013-04-10 06:11:48 +00009863 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +00009864 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smithb7151b92013-04-10 06:11:48 +00009865 }
9866 }
9867
9868 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009869 for (const auto *F : ClassDecl->fields()) {
Richard Smithb7151b92013-04-10 06:11:48 +00009870 if (F->hasInClassInitializer()) {
9871 if (Expr *E = F->getInClassInitializer())
9872 ExceptSpec.CalledExpr(E);
Richard Smithb7151b92013-04-10 06:11:48 +00009873 } else if (const RecordType *RecordTy
9874 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
9875 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9876 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
9877 if (Constructor)
9878 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
9879 }
9880 }
9881
Richard Smithc2bc61b2013-03-18 21:12:30 +00009882 return ExceptSpec;
9883}
9884
Richard Smith8bf22e52012-11-29 01:34:07 +00009885namespace {
9886/// RAII object to register a special member as being currently declared.
9887struct DeclaringSpecialMember {
9888 Sema &S;
9889 Sema::SpecialMemberDecl D;
Richard Smith12e79312016-05-13 06:47:56 +00009890 Sema::ContextRAII SavedContext;
Richard Smith8bf22e52012-11-29 01:34:07 +00009891 bool WasAlreadyBeingDeclared;
9892
9893 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
Richard Smith12e79312016-05-13 06:47:56 +00009894 : S(S), D(RD, CSM), SavedContext(S, RD) {
David Blaikie82e95a32014-11-19 07:49:47 +00009895 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
Richard Smith8bf22e52012-11-29 01:34:07 +00009896 if (WasAlreadyBeingDeclared)
9897 // This almost never happens, but if it does, ensure that our cache
9898 // doesn't contain a stale result.
9899 S.SpecialMemberCache.clear();
9900
9901 // FIXME: Register a note to be produced if we encounter an error while
9902 // declaring the special member.
9903 }
9904 ~DeclaringSpecialMember() {
9905 if (!WasAlreadyBeingDeclared)
9906 S.SpecialMembersBeingDeclared.erase(D);
9907 }
9908
9909 /// \brief Are we already trying to declare this special member?
9910 bool isAlreadyBeingDeclared() const {
9911 return WasAlreadyBeingDeclared;
9912 }
9913};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009914}
Richard Smith8bf22e52012-11-29 01:34:07 +00009915
Richard Smith12e79312016-05-13 06:47:56 +00009916void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
9917 // Look up any existing declarations, but don't trigger declaration of all
9918 // implicit special members with this name.
9919 DeclarationName Name = FD->getDeclName();
9920 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
9921 ForRedeclaration);
9922 for (auto *D : FD->getParent()->lookup(Name))
9923 if (auto *Acceptable = R.getAcceptableDecl(D))
9924 R.addDecl(Acceptable);
9925 R.resolveKind();
Richard Smitha87b7662016-05-13 18:48:05 +00009926 R.suppressDiagnostics();
Richard Smith12e79312016-05-13 06:47:56 +00009927
9928 CheckFunctionDeclaration(S, FD, R, /*IsExplicitSpecialization*/false);
9929}
9930
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00009931CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
9932 CXXRecordDecl *ClassDecl) {
9933 // C++ [class.ctor]p5:
9934 // A default constructor for a class X is a constructor of class X
9935 // that can be called without an argument. If there is no
9936 // user-declared constructor for class X, a default constructor is
9937 // implicitly declared. An implicitly-declared default constructor
9938 // is an inline public member of its class.
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009939 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00009940 "Should not build implicit default constructor!");
9941
Richard Smith8bf22e52012-11-29 01:34:07 +00009942 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
9943 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +00009944 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +00009945
Richard Smithb5800092012-06-10 05:43:50 +00009946 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9947 CXXDefaultConstructor,
9948 false);
9949
Douglas Gregor6d880b12010-07-01 22:31:05 +00009950 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00009951 CanQualType ClassType
9952 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00009953 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00009954 DeclarationName Name
9955 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00009956 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00009957 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +00009958 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
9959 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
9960 /*isImplicitlyDeclared=*/true, Constexpr);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00009961 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00009962 DefaultCon->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009963
9964 if (getLangOpts().CUDA) {
9965 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
9966 DefaultCon,
9967 /* ConstRHS */ false,
9968 /* Diagnose */ false);
9969 }
Richard Smithd3b5c9082012-07-27 04:22:15 +00009970
9971 // Build an exception specification pointing back at this constructor.
Reid Kleckner78af0702013-08-27 23:08:25 +00009972 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00009973 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +00009974
Richard Smith6b02d462012-12-08 08:32:28 +00009975 // We don't need to use SpecialMemberIsTrivial here; triviality for default
9976 // constructors is easy to compute.
9977 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
9978
Douglas Gregor9672f922010-07-03 00:47:00 +00009979 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00009980 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smith6b02d462012-12-08 08:32:28 +00009981
Richard Smith12e79312016-05-13 06:47:56 +00009982 Scope *S = getScopeForContext(ClassDecl);
9983 CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
9984
9985 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
9986 SetDeclDeleted(DefaultCon, ClassLoc);
9987
9988 if (S)
Douglas Gregor9672f922010-07-03 00:47:00 +00009989 PushOnScopeChains(DefaultCon, S, false);
9990 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00009991
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00009992 return DefaultCon;
9993}
9994
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00009995void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
9996 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00009997 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00009998 !Constructor->doesThisDeclarationHaveABody() &&
9999 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +000010000 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +000010001
Anders Carlsson423f5d82010-04-23 16:04:08 +000010002 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +000010003 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +000010004
Eli Friedmaneaf34142012-10-18 20:14:08 +000010005 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010006 DiagnosticErrorTrap Trap(Diags);
David Blaikie3fc2f912013-01-17 05:26:25 +000010007 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000010008 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +000010009 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +000010010 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +000010011 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +000010012 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +000010013 }
Douglas Gregor73193272010-09-20 16:48:21 +000010014
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010015 // The exception specification is needed because we are defining the
10016 // function.
10017 ResolveExceptionSpec(CurrentLocation,
10018 Constructor->getType()->castAs<FunctionProtoType>());
10019
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010020 SourceLocation Loc = Constructor->getLocEnd().isValid()
10021 ? Constructor->getLocEnd()
10022 : Constructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +000010023 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor73193272010-09-20 16:48:21 +000010024
Eli Friedman276dd182013-09-05 00:02:25 +000010025 Constructor->markUsed(Context);
Douglas Gregor73193272010-09-20 16:48:21 +000010026 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +000010027
10028 if (ASTMutationListener *L = getASTMutationListener()) {
10029 L->CompletedImplicitDefinition(Constructor);
10030 }
Richard Trieuef64e942013-10-25 00:56:00 +000010031
10032 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +000010033}
10034
Richard Smith938f40b2011-06-11 17:19:42 +000010035void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Tokerae3a9442013-10-18 05:54:19 +000010036 // Perform any delayed checks on exception specifications.
10037 CheckDelayedMemberExceptionSpecs();
Richard Smith938f40b2011-06-11 17:19:42 +000010038}
10039
Richard Smith5179eb72016-06-28 19:03:57 +000010040/// Find or create the fake constructor we synthesize to model constructing an
10041/// object of a derived class via a constructor of a base class.
10042CXXConstructorDecl *
10043Sema::findInheritingConstructor(SourceLocation Loc,
10044 CXXConstructorDecl *BaseCtor,
10045 ConstructorUsingShadowDecl *Shadow) {
10046 CXXRecordDecl *Derived = Shadow->getParent();
10047 SourceLocation UsingLoc = Shadow->getLocation();
Richard Smith185be182013-04-10 05:48:59 +000010048
Richard Smith5179eb72016-06-28 19:03:57 +000010049 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
10050 // For now we use the name of the base class constructor as a member of the
10051 // derived class to indicate a (fake) inherited constructor name.
10052 DeclarationName Name = BaseCtor->getDeclName();
Richard Smith185be182013-04-10 05:48:59 +000010053
Richard Smith5179eb72016-06-28 19:03:57 +000010054 // Check to see if we already have a fake constructor for this inherited
10055 // constructor call.
10056 for (NamedDecl *Ctor : Derived->lookup(Name))
10057 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
10058 ->getInheritedConstructor()
10059 .getConstructor(),
10060 BaseCtor))
10061 return cast<CXXConstructorDecl>(Ctor);
Richard Smith185be182013-04-10 05:48:59 +000010062
Richard Smith5179eb72016-06-28 19:03:57 +000010063 DeclarationNameInfo NameInfo(Name, UsingLoc);
10064 TypeSourceInfo *TInfo =
10065 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
10066 FunctionProtoTypeLoc ProtoLoc =
10067 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
Richard Smith185be182013-04-10 05:48:59 +000010068
Richard Smith5179eb72016-06-28 19:03:57 +000010069 // Check the inherited constructor is valid and find the list of base classes
10070 // from which it was inherited.
10071 InheritedConstructorInfo ICI(*this, Loc, Shadow);
Richard Smith185be182013-04-10 05:48:59 +000010072
Richard Smith5179eb72016-06-28 19:03:57 +000010073 bool Constexpr =
10074 BaseCtor->isConstexpr() &&
10075 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
10076 false, BaseCtor, &ICI);
Richard Smith185be182013-04-10 05:48:59 +000010077
Richard Smith5179eb72016-06-28 19:03:57 +000010078 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
10079 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
10080 BaseCtor->isExplicit(), /*Inline=*/true,
10081 /*ImplicitlyDeclared=*/true, Constexpr,
10082 InheritedConstructor(Shadow, BaseCtor));
10083 if (Shadow->isInvalidDecl())
10084 DerivedCtor->setInvalidDecl();
Richard Smith185be182013-04-10 05:48:59 +000010085
Richard Smith5179eb72016-06-28 19:03:57 +000010086 // Build an unevaluated exception specification for this fake constructor.
10087 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
10088 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10089 EPI.ExceptionSpec.Type = EST_Unevaluated;
10090 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
10091 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
10092 FPT->getParamTypes(), EPI));
Richard Smith185be182013-04-10 05:48:59 +000010093
Richard Smith5179eb72016-06-28 19:03:57 +000010094 // Build the parameter declarations.
10095 SmallVector<ParmVarDecl *, 16> ParamDecls;
10096 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith185be182013-04-10 05:48:59 +000010097 TypeSourceInfo *TInfo =
Richard Smith5179eb72016-06-28 19:03:57 +000010098 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
10099 ParmVarDecl *PD = ParmVarDecl::Create(
10100 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
10101 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
10102 PD->setScopeInfo(0, I);
10103 PD->setImplicit();
10104 // Ensure attributes are propagated onto parameters (this matters for
10105 // format, pass_object_size, ...).
10106 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
10107 ParamDecls.push_back(PD);
10108 ProtoLoc.setParam(I, PD);
Richard Smith185be182013-04-10 05:48:59 +000010109 }
10110
Richard Smith5179eb72016-06-28 19:03:57 +000010111 // Set up the new constructor.
10112 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
10113 DerivedCtor->setAccess(BaseCtor->getAccess());
10114 DerivedCtor->setParams(ParamDecls);
10115 Derived->addDecl(DerivedCtor);
Richard Smith80a47022016-06-29 01:10:27 +000010116
10117 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
10118 SetDeclDeleted(DerivedCtor, UsingLoc);
10119
Richard Smith5179eb72016-06-28 19:03:57 +000010120 return DerivedCtor;
Sebastian Redl08905022011-02-05 19:23:19 +000010121}
10122
Richard Smith80a47022016-06-29 01:10:27 +000010123void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
10124 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
10125 Ctor->getInheritedConstructor().getShadowDecl());
10126 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
10127 /*Diagnose*/true);
10128}
10129
Richard Smithc2bc61b2013-03-18 21:12:30 +000010130void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
10131 CXXConstructorDecl *Constructor) {
10132 CXXRecordDecl *ClassDecl = Constructor->getParent();
10133 assert(Constructor->getInheritedConstructor() &&
10134 !Constructor->doesThisDeclarationHaveABody() &&
10135 !Constructor->isDeleted());
Richard Smith5179eb72016-06-28 19:03:57 +000010136 if (Constructor->isInvalidDecl())
10137 return;
Richard Smithc2bc61b2013-03-18 21:12:30 +000010138
Richard Smith5179eb72016-06-28 19:03:57 +000010139 ConstructorUsingShadowDecl *Shadow =
10140 Constructor->getInheritedConstructor().getShadowDecl();
10141 CXXConstructorDecl *InheritedCtor =
10142 Constructor->getInheritedConstructor().getConstructor();
10143
10144 // [class.inhctor.init]p1:
10145 // initialization proceeds as if a defaulted default constructor is used to
10146 // initialize the D object and each base class subobject from which the
10147 // constructor was inherited
10148
10149 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
10150 CXXRecordDecl *RD = Shadow->getParent();
10151 SourceLocation InitLoc = Shadow->getLocation();
10152
10153 // Initializations are performed "as if by a defaulted default constructor",
10154 // so enter the appropriate scope.
Richard Smithc2bc61b2013-03-18 21:12:30 +000010155 SynthesizedFunctionScope Scope(*this, Constructor);
10156 DiagnosticErrorTrap Trap(Diags);
Richard Smith5179eb72016-06-28 19:03:57 +000010157
10158 // Build explicit initializers for all base classes from which the
10159 // constructor was inherited.
10160 SmallVector<CXXCtorInitializer*, 8> Inits;
10161 for (bool VBase : {false, true}) {
10162 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
10163 if (B.isVirtual() != VBase)
10164 continue;
10165
10166 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
10167 if (!BaseRD)
10168 continue;
10169
10170 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
10171 if (!BaseCtor.first)
10172 continue;
10173
10174 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
10175 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
10176 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
10177
10178 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
10179 Inits.push_back(new (Context) CXXCtorInitializer(
10180 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
10181 SourceLocation()));
10182 }
10183 }
10184
10185 // We now proceed as if for a defaulted default constructor, with the relevant
10186 // initializers replaced.
10187
10188 bool HadError = SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits);
10189 if (HadError || Trap.hasErrorOccurred()) {
10190 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) << RD;
Richard Smithc2bc61b2013-03-18 21:12:30 +000010191 Constructor->setInvalidDecl();
10192 return;
10193 }
10194
Richard Smith5179eb72016-06-28 19:03:57 +000010195 // The exception specification is needed because we are defining the
10196 // function.
10197 ResolveExceptionSpec(CurrentLocation,
10198 Constructor->getType()->castAs<FunctionProtoType>());
10199
10200 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
Richard Smithc2bc61b2013-03-18 21:12:30 +000010201
Eli Friedman276dd182013-09-05 00:02:25 +000010202 Constructor->markUsed(Context);
Richard Smithc2bc61b2013-03-18 21:12:30 +000010203 MarkVTableUsed(CurrentLocation, ClassDecl);
10204
10205 if (ASTMutationListener *L = getASTMutationListener()) {
10206 L->CompletedImplicitDefinition(Constructor);
10207 }
Richard Smithc2bc61b2013-03-18 21:12:30 +000010208
Richard Smith5179eb72016-06-28 19:03:57 +000010209 DiagnoseUninitializedFields(*this, Constructor);
10210}
Richard Smithc2bc61b2013-03-18 21:12:30 +000010211
Alexis Huntf91729462011-05-12 22:46:25 +000010212Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000010213Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
10214 CXXRecordDecl *ClassDecl = MD->getParent();
10215
Douglas Gregorf1203042010-07-01 19:09:28 +000010216 // C++ [except.spec]p14:
10217 // An implicitly declared special member function (Clause 12) shall have
10218 // an exception-specification.
Richard Smithf623c962012-04-17 00:58:00 +000010219 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +000010220 if (ClassDecl->isInvalidDecl())
10221 return ExceptSpec;
10222
Douglas Gregorf1203042010-07-01 19:09:28 +000010223 // Direct base-class destructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000010224 for (const auto &B : ClassDecl->bases()) {
10225 if (B.isVirtual()) // Handled below.
Douglas Gregorf1203042010-07-01 19:09:28 +000010226 continue;
10227
Aaron Ballman574705e2014-03-13 15:41:46 +000010228 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
10229 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +000010230 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +000010231 }
Sebastian Redl623ea822011-05-19 05:13:44 +000010232
Douglas Gregorf1203042010-07-01 19:09:28 +000010233 // Virtual base-class destructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000010234 for (const auto &B : ClassDecl->vbases()) {
10235 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
10236 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl623ea822011-05-19 05:13:44 +000010237 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +000010238 }
Sebastian Redl623ea822011-05-19 05:13:44 +000010239
Douglas Gregorf1203042010-07-01 19:09:28 +000010240 // Field destructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010241 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorf1203042010-07-01 19:09:28 +000010242 if (const RecordType *RecordTy
10243 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithf623c962012-04-17 00:58:00 +000010244 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl623ea822011-05-19 05:13:44 +000010245 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +000010246 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010247
Alexis Huntf91729462011-05-12 22:46:25 +000010248 return ExceptSpec;
10249}
10250
10251CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
10252 // C++ [class.dtor]p2:
10253 // If a class has no user-declared destructor, a destructor is
10254 // declared implicitly. An implicitly-declared destructor is an
10255 // inline public member of its class.
Richard Smith2be35f52012-12-01 02:35:44 +000010256 assert(ClassDecl->needsImplicitDestructor());
Alexis Huntf91729462011-05-12 22:46:25 +000010257
Richard Smith8bf22e52012-11-29 01:34:07 +000010258 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
10259 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010260 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010261
Douglas Gregor7454c562010-07-02 20:37:36 +000010262 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +000010263 CanQualType ClassType
10264 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +000010265 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +000010266 DeclarationName Name
10267 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +000010268 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +000010269 CXXDestructorDecl *Destructor
Richard Smithd3b5c9082012-07-27 04:22:15 +000010270 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +000010271 QualType(), nullptr, /*isInline=*/true,
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010272 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +000010273 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +000010274 Destructor->setDefaulted();
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010275
10276 if (getLangOpts().CUDA) {
10277 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
10278 Destructor,
10279 /* ConstRHS */ false,
10280 /* Diagnose */ false);
10281 }
Richard Smithd3b5c9082012-07-27 04:22:15 +000010282
10283 // Build an exception specification pointing back at this destructor.
Reid Kleckner78af0702013-08-27 23:08:25 +000010284 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000010285 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010286
Richard Smith6b02d462012-12-08 08:32:28 +000010287 // We don't need to use SpecialMemberIsTrivial here; triviality for
10288 // destructors is easy to compute.
10289 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
10290
Douglas Gregor7454c562010-07-02 20:37:36 +000010291 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +000010292 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithd3b5c9082012-07-27 04:22:15 +000010293
Richard Smith12e79312016-05-13 06:47:56 +000010294 Scope *S = getScopeForContext(ClassDecl);
10295 CheckImplicitSpecialMemberDeclaration(S, Destructor);
10296
Richard Smithb2f0f052016-10-10 18:54:32 +000010297 // We can't check whether an implicit destructor is deleted before we complete
10298 // the definition of the class, because its validity depends on the alignment
10299 // of the class. We'll check this from ActOnFields once the class is complete.
10300 if (ClassDecl->isCompleteDefinition() &&
10301 ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith12e79312016-05-13 06:47:56 +000010302 SetDeclDeleted(Destructor, ClassLoc);
10303
Douglas Gregor7454c562010-07-02 20:37:36 +000010304 // Introduce this destructor into its scope.
Richard Smith12e79312016-05-13 06:47:56 +000010305 if (S)
Douglas Gregor7454c562010-07-02 20:37:36 +000010306 PushOnScopeChains(Destructor, S, false);
10307 ClassDecl->addDecl(Destructor);
Alexis Huntf91729462011-05-12 22:46:25 +000010308
Douglas Gregorf1203042010-07-01 19:09:28 +000010309 return Destructor;
10310}
10311
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010312void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +000010313 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +000010314 assert((Destructor->isDefaulted() &&
Richard Smith273c4e92012-02-26 07:51:39 +000010315 !Destructor->doesThisDeclarationHaveABody() &&
10316 !Destructor->isDeleted()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010317 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +000010318 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010319 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010320
Douglas Gregor54818f02010-05-12 16:39:35 +000010321 if (Destructor->isInvalidDecl())
10322 return;
10323
Eli Friedmaneaf34142012-10-18 20:14:08 +000010324 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000010325
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000010326 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +000010327 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10328 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +000010329
Douglas Gregor54818f02010-05-12 16:39:35 +000010330 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +000010331 Diag(CurrentLocation, diag::note_member_synthesized_at)
10332 << CXXDestructor << Context.getTagDeclType(ClassDecl);
10333
10334 Destructor->setInvalidDecl();
10335 return;
10336 }
10337
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000010338 // The exception specification is needed because we are defining the
10339 // function.
10340 ResolveExceptionSpec(CurrentLocation,
10341 Destructor->getType()->castAs<FunctionProtoType>());
10342
Daniel Jasperb3b0b802014-06-20 08:44:22 +000010343 SourceLocation Loc = Destructor->getLocEnd().isValid()
10344 ? Destructor->getLocEnd()
10345 : Destructor->getLocation();
Benjamin Kramere2a929d2012-07-04 17:03:41 +000010346 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman276dd182013-09-05 00:02:25 +000010347 Destructor->markUsed(Context);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010348 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +000010349
10350 if (ASTMutationListener *L = getASTMutationListener()) {
10351 L->CompletedImplicitDefinition(Destructor);
10352 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010353}
10354
Richard Smith84973e52012-04-21 18:42:51 +000010355/// \brief Perform any semantic analysis which needs to be delayed until all
10356/// pending class member declarations have been parsed.
10357void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregorbc0e5c02013-02-01 04:49:10 +000010358 // If the context is an invalid C++ class, just suppress these checks.
10359 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
10360 if (Record->isInvalidDecl()) {
Alp Tokerae3a9442013-10-18 05:54:19 +000010361 DelayedDefaultedMemberExceptionSpecs.clear();
Richard Smith88f45492014-11-22 03:09:05 +000010362 DelayedExceptionSpecChecks.clear();
Douglas Gregorbc0e5c02013-02-01 04:49:10 +000010363 return;
10364 }
10365 }
Richard Smith84973e52012-04-21 18:42:51 +000010366}
10367
Reid Klecknerc01ee752016-11-23 16:51:30 +000010368static void checkDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) {
Reid Klecknerbba3cb92015-03-17 19:00:50 +000010369 // Don't do anything for template patterns.
10370 if (Class->getDescribedClassTemplate())
10371 return;
10372
David Majnemer474b3232015-12-31 05:36:46 +000010373 CallingConv ExpectedCallingConv = S.Context.getDefaultCallingConvention(
10374 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
10375
10376 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
Reid Klecknerbba3cb92015-03-17 19:00:50 +000010377 for (Decl *Member : Class->decls()) {
10378 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
10379 if (!CD) {
10380 // Recurse on nested classes.
10381 if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member))
Reid Klecknerc01ee752016-11-23 16:51:30 +000010382 checkDefaultArgExprsForConstructors(S, NestedRD);
Reid Klecknerbba3cb92015-03-17 19:00:50 +000010383 continue;
10384 } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) {
10385 continue;
10386 }
10387
David Majnemer474b3232015-12-31 05:36:46 +000010388 CallingConv ActualCallingConv =
10389 CD->getType()->getAs<FunctionProtoType>()->getCallConv();
10390
10391 // Skip default constructors with typical calling conventions and no default
10392 // arguments.
10393 unsigned NumParams = CD->getNumParams();
10394 if (ExpectedCallingConv == ActualCallingConv && NumParams == 0)
10395 continue;
10396
10397 if (LastExportedDefaultCtor) {
10398 S.Diag(LastExportedDefaultCtor->getLocation(),
10399 diag::err_attribute_dll_ambiguous_default_ctor) << Class;
10400 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
10401 << CD->getDeclName();
10402 return;
10403 }
10404 LastExportedDefaultCtor = CD;
10405
10406 for (unsigned I = 0; I != NumParams; ++I) {
Reid Klecknerc01ee752016-11-23 16:51:30 +000010407 (void)S.CheckCXXDefaultArgExpr(Class->getLocation(), CD,
10408 CD->getParamDecl(I));
David Majnemer9321f922015-06-11 02:38:06 +000010409 S.DiscardCleanupsInEvaluationContext();
Reid Klecknerbba3cb92015-03-17 19:00:50 +000010410 }
10411 }
10412}
10413
Hans Wennborg99000c22015-08-15 01:18:16 +000010414void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
Reid Klecknerbba3cb92015-03-17 19:00:50 +000010415 auto *RD = dyn_cast<CXXRecordDecl>(D);
10416
10417 // Default constructors that are annotated with __declspec(dllexport) which
10418 // have default arguments or don't use the standard calling convention are
10419 // wrapped with a thunk called the default constructor closure.
10420 if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft())
Reid Klecknerc01ee752016-11-23 16:51:30 +000010421 checkDefaultArgExprsForConstructors(*this, RD);
Hans Wennborg99000c22015-08-15 01:18:16 +000010422
Reid Kleckner5b640342016-02-26 19:51:02 +000010423 referenceDLLExportedClassMethods();
10424}
10425
10426void Sema::referenceDLLExportedClassMethods() {
Hans Wennborg99000c22015-08-15 01:18:16 +000010427 if (!DelayedDllExportClasses.empty()) {
10428 // Calling ReferenceDllExportedMethods might cause the current function to
10429 // be called again, so use a local copy of DelayedDllExportClasses.
10430 SmallVector<CXXRecordDecl *, 4> WorkList;
10431 std::swap(DelayedDllExportClasses, WorkList);
10432 for (CXXRecordDecl *Class : WorkList)
10433 ReferenceDllExportedMethods(*this, Class);
10434 }
Reid Klecknerbba3cb92015-03-17 19:00:50 +000010435}
10436
Richard Smithd3b5c9082012-07-27 04:22:15 +000010437void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
10438 CXXDestructorDecl *Destructor) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010439 assert(getLangOpts().CPlusPlus11 &&
Richard Smithd3b5c9082012-07-27 04:22:15 +000010440 "adjusting dtor exception specs was introduced in c++11");
10441
Sebastian Redl623ea822011-05-19 05:13:44 +000010442 // C++11 [class.dtor]p3:
10443 // A declaration of a destructor that does not have an exception-
10444 // specification is implicitly considered to have the same exception-
10445 // specification as an implicit declaration.
Richard Smithd3b5c9082012-07-27 04:22:15 +000010446 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl623ea822011-05-19 05:13:44 +000010447 getAs<FunctionProtoType>();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010448 if (DtorType->hasExceptionSpec())
Sebastian Redl623ea822011-05-19 05:13:44 +000010449 return;
10450
Chandler Carruth9a797572011-09-20 04:55:26 +000010451 // Replace the destructor's type, building off the existing one. Fortunately,
10452 // the only thing of interest in the destructor type is its extended info.
10453 // The return and arguments are fixed.
Richard Smithd3b5c9082012-07-27 04:22:15 +000010454 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +000010455 EPI.ExceptionSpec.Type = EST_Unevaluated;
10456 EPI.ExceptionSpec.SourceDecl = Destructor;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000010457 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith84973e52012-04-21 18:42:51 +000010458
Sebastian Redl623ea822011-05-19 05:13:44 +000010459 // FIXME: If the destructor has a body that could throw, and the newly created
10460 // spec doesn't allow exceptions, we should emit a warning, because this
10461 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithd3b5c9082012-07-27 04:22:15 +000010462 // However, we don't have a body or an exception specification yet, so it
10463 // needs to be done somewhere else.
Sebastian Redl623ea822011-05-19 05:13:44 +000010464}
10465
Pavel Labath58934982013-08-30 08:52:28 +000010466namespace {
10467/// \brief An abstract base class for all helper classes used in building the
10468// copy/move operators. These classes serve as factory functions and help us
10469// avoid using the same Expr* in the AST twice.
10470class ExprBuilder {
Aaron Ballmanabc18922015-02-15 22:54:08 +000010471 ExprBuilder(const ExprBuilder&) = delete;
10472 ExprBuilder &operator=(const ExprBuilder&) = delete;
Pavel Labath58934982013-08-30 08:52:28 +000010473
10474protected:
10475 static Expr *assertNotNull(Expr *E) {
10476 assert(E && "Expression construction must not fail.");
10477 return E;
10478 }
10479
10480public:
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000010481 ExprBuilder() {}
10482 virtual ~ExprBuilder() {}
Pavel Labath58934982013-08-30 08:52:28 +000010483
10484 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
10485};
10486
10487class RefBuilder: public ExprBuilder {
10488 VarDecl *Var;
10489 QualType VarType;
10490
10491public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010492 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010493 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +000010494 }
10495
10496 RefBuilder(VarDecl *Var, QualType VarType)
10497 : Var(Var), VarType(VarType) {}
10498};
10499
10500class ThisBuilder: public ExprBuilder {
10501public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010502 Expr *build(Sema &S, SourceLocation Loc) const override {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010503 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
Pavel Labath58934982013-08-30 08:52:28 +000010504 }
10505};
10506
10507class CastBuilder: public ExprBuilder {
10508 const ExprBuilder &Builder;
10509 QualType Type;
10510 ExprValueKind Kind;
10511 const CXXCastPath &Path;
10512
10513public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010514 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010515 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
10516 CK_UncheckedDerivedToBase, Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010517 &Path).get());
Pavel Labath58934982013-08-30 08:52:28 +000010518 }
10519
10520 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
10521 const CXXCastPath &Path)
10522 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
10523};
10524
10525class DerefBuilder: public ExprBuilder {
10526 const ExprBuilder &Builder;
10527
10528public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010529 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010530 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010531 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +000010532 }
10533
10534 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10535};
10536
10537class MemberBuilder: public ExprBuilder {
10538 const ExprBuilder &Builder;
10539 QualType Type;
10540 CXXScopeSpec SS;
10541 bool IsArrow;
10542 LookupResult &MemberLookup;
10543
10544public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010545 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010546 return assertNotNull(S.BuildMemberReferenceExpr(
Craig Topperc3ec1492014-05-26 06:22:03 +000010547 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
Aaron Ballman6924dcd2015-09-01 14:49:24 +000010548 nullptr, MemberLookup, nullptr, nullptr).get());
Pavel Labath58934982013-08-30 08:52:28 +000010549 }
10550
10551 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
10552 LookupResult &MemberLookup)
10553 : Builder(Builder), Type(Type), IsArrow(IsArrow),
10554 MemberLookup(MemberLookup) {}
10555};
10556
10557class MoveCastBuilder: public ExprBuilder {
10558 const ExprBuilder &Builder;
10559
10560public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010561 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010562 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
10563 }
10564
10565 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10566};
10567
10568class LvalueConvBuilder: public ExprBuilder {
10569 const ExprBuilder &Builder;
10570
10571public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010572 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010573 return assertNotNull(
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010574 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
Pavel Labath58934982013-08-30 08:52:28 +000010575 }
10576
10577 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10578};
10579
10580class SubscriptBuilder: public ExprBuilder {
10581 const ExprBuilder &Base;
10582 const ExprBuilder &Index;
10583
10584public:
David Blaikie1cbb9712014-11-14 19:09:44 +000010585 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath58934982013-08-30 08:52:28 +000010586 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010587 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
Pavel Labath58934982013-08-30 08:52:28 +000010588 }
10589
10590 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
10591 : Base(Base), Index(Index) {}
10592};
10593
10594} // end anonymous namespace
10595
Richard Smith41ae3282012-11-14 00:50:40 +000010596/// When generating a defaulted copy or move assignment operator, if a field
10597/// should be copied with __builtin_memcpy rather than via explicit assignments,
10598/// do so. This optimization only applies for arrays of scalars, and for arrays
10599/// of class type where the selected copy/move-assignment operator is trivial.
10600static StmtResult
10601buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +000010602 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith41ae3282012-11-14 00:50:40 +000010603 // Compute the size of the memory buffer to be copied.
10604 QualType SizeType = S.Context.getSizeType();
10605 llvm::APInt Size(S.Context.getTypeSize(SizeType),
10606 S.Context.getTypeSizeInChars(T).getQuantity());
10607
10608 // Take the address of the field references for "from" and "to". We
10609 // directly construct UnaryOperators here because semantic analysis
10610 // does not permit us to take the address of an xvalue.
Pavel Labath58934982013-08-30 08:52:28 +000010611 Expr *From = FromB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000010612 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
10613 S.Context.getPointerType(From->getType()),
10614 VK_RValue, OK_Ordinary, Loc);
Pavel Labath58934982013-08-30 08:52:28 +000010615 Expr *To = ToB.build(S, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000010616 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
10617 S.Context.getPointerType(To->getType()),
10618 VK_RValue, OK_Ordinary, Loc);
10619
10620 const Type *E = T->getBaseElementTypeUnsafe();
10621 bool NeedsCollectableMemCpy =
10622 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
10623
10624 // Create a reference to the __builtin_objc_memmove_collectable function
10625 StringRef MemCpyName = NeedsCollectableMemCpy ?
10626 "__builtin_objc_memmove_collectable" :
10627 "__builtin_memcpy";
10628 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
10629 Sema::LookupOrdinaryName);
10630 S.LookupName(R, S.TUScope, true);
10631
10632 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
10633 if (!MemCpy)
10634 // Something went horribly wrong earlier, and we will have complained
10635 // about it.
10636 return StmtError();
10637
10638 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
Craig Topperc3ec1492014-05-26 06:22:03 +000010639 VK_RValue, Loc, nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +000010640 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
10641
10642 Expr *CallArgs[] = {
10643 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
10644 };
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010645 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
Richard Smith41ae3282012-11-14 00:50:40 +000010646 Loc, CallArgs, Loc);
10647
10648 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010649 return Call.getAs<Stmt>();
Richard Smith41ae3282012-11-14 00:50:40 +000010650}
10651
Sebastian Redl22653ba2011-08-30 19:58:05 +000010652/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +000010653/// \c To.
10654///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010655/// This routine is used to copy/move the members of a class with an
10656/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +000010657/// copied are arrays, this routine builds for loops to copy them.
10658///
10659/// \param S The Sema object used for type-checking.
10660///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010661/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +000010662///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010663/// \param T The type of the expressions being copied/moved. Both expressions
10664/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +000010665///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010666/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +000010667///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010668/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +000010669///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010670/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +000010671/// Otherwise, it's a non-static member subobject.
10672///
Sebastian Redl22653ba2011-08-30 19:58:05 +000010673/// \param Copying Whether we're copying or moving.
10674///
Douglas Gregorb139cd52010-05-01 20:49:11 +000010675/// \param Depth Internal parameter recording the depth of the recursion.
10676///
Richard Smith41ae3282012-11-14 00:50:40 +000010677/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
10678/// if a memcpy should be used instead.
John McCalldadc5752010-08-24 06:29:42 +000010679static StmtResult
Richard Smith41ae3282012-11-14 00:50:40 +000010680buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +000010681 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +000010682 bool CopyingBaseSubobject, bool Copying,
10683 unsigned Depth = 0) {
Richard Smith52c0b582012-11-13 00:54:12 +000010684 // C++11 [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +000010685 // Each subobject is assigned in the manner appropriate to its type:
10686 //
Sebastian Redl22653ba2011-08-30 19:58:05 +000010687 // - if the subobject is of class type, as if by a call to operator= with
10688 // the subobject as the object expression and the corresponding
10689 // subobject of x as a single function argument (as if by explicit
10690 // qualification; that is, ignoring any possible virtual overriding
10691 // functions in more derived classes);
Richard Smith52c0b582012-11-13 00:54:12 +000010692 //
10693 // C++03 [class.copy]p13:
10694 // - if the subobject is of class type, the copy assignment operator for
10695 // the class is used (as if by explicit qualification; that is,
10696 // ignoring any possible virtual overriding functions in more derived
10697 // classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010698 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
10699 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith52c0b582012-11-13 00:54:12 +000010700
Douglas Gregorb139cd52010-05-01 20:49:11 +000010701 // Look for operator=.
10702 DeclarationName Name
10703 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10704 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
10705 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010706
Richard Smith52c0b582012-11-13 00:54:12 +000010707 // Prior to C++11, filter out any result that isn't a copy/move-assignment
10708 // operator.
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010709 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith52c0b582012-11-13 00:54:12 +000010710 LookupResult::Filter F = OpLookup.makeFilter();
10711 while (F.hasNext()) {
10712 NamedDecl *D = F.next();
10713 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
10714 if (Method->isCopyAssignmentOperator() ||
10715 (!Copying && Method->isMoveAssignmentOperator()))
10716 continue;
10717
10718 F.erase();
10719 }
10720 F.done();
John McCallab8c2732010-03-16 06:11:48 +000010721 }
Richard Smith52c0b582012-11-13 00:54:12 +000010722
Douglas Gregor40c92bb2010-05-04 15:20:55 +000010723 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith52c0b582012-11-13 00:54:12 +000010724 // assignment operators we found. This strange dance is required when
Douglas Gregor40c92bb2010-05-04 15:20:55 +000010725 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith52c0b582012-11-13 00:54:12 +000010726 // ensure that we're getting the right base class subobject (without
Douglas Gregor40c92bb2010-05-04 15:20:55 +000010727 // ambiguities), we need to cast "this" to that subobject type; to
10728 // ensure that we don't go through the virtual call mechanism, we need
10729 // to qualify the operator= name with the base class (see below). However,
10730 // this means that if the base class has a protected copy assignment
10731 // operator, the protected member access check will fail. So, we
10732 // rewrite "protected" access to "public" access in this case, since we
10733 // know by construction that we're calling from a derived class.
10734 if (CopyingBaseSubobject) {
10735 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
10736 L != LEnd; ++L) {
10737 if (L.getAccess() == AS_protected)
10738 L.setAccess(AS_public);
10739 }
10740 }
Richard Smith52c0b582012-11-13 00:54:12 +000010741
Douglas Gregorb139cd52010-05-01 20:49:11 +000010742 // Create the nested-name-specifier that will be used to qualify the
10743 // reference to operator=; this is required to suppress the virtual
10744 // call mechanism.
10745 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +000010746 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith52c0b582012-11-13 00:54:12 +000010747 SS.MakeTrivial(S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +000010748 NestedNameSpecifier::Create(S.Context, nullptr, false,
Manuel Klimeke7167412012-02-06 21:51:39 +000010749 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +000010750 Loc);
Richard Smith52c0b582012-11-13 00:54:12 +000010751
Douglas Gregorb139cd52010-05-01 20:49:11 +000010752 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +000010753 ExprResult OpEqualRef
Pavel Labath58934982013-08-30 08:52:28 +000010754 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
10755 SS, /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000010756 /*FirstQualifierInScope=*/nullptr,
Abramo Bagnara7945c982012-01-27 09:46:47 +000010757 OpLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000010758 /*TemplateArgs=*/nullptr, /*S*/nullptr,
Douglas Gregorb139cd52010-05-01 20:49:11 +000010759 /*SuppressQualifierCheck=*/true);
10760 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010761 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +000010762
Douglas Gregorb139cd52010-05-01 20:49:11 +000010763 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +000010764
Pavel Labath58934982013-08-30 08:52:28 +000010765 Expr *FromInst = From.build(S, Loc);
Craig Topperc3ec1492014-05-26 06:22:03 +000010766 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010767 OpEqualRef.getAs<Expr>(),
Pavel Labath58934982013-08-30 08:52:28 +000010768 Loc, FromInst, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010769 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010770 return StmtError();
Richard Smith52c0b582012-11-13 00:54:12 +000010771
Richard Smith41ae3282012-11-14 00:50:40 +000010772 // If we built a call to a trivial 'operator=' while copying an array,
10773 // bail out. We'll replace the whole shebang with a memcpy.
10774 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
10775 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
Craig Topperc3ec1492014-05-26 06:22:03 +000010776 return StmtResult((Stmt*)nullptr);
Richard Smith41ae3282012-11-14 00:50:40 +000010777
Richard Smith52c0b582012-11-13 00:54:12 +000010778 // Convert to an expression-statement, and clean up any produced
10779 // temporaries.
Richard Smith945f8d32013-01-14 22:39:08 +000010780 return S.ActOnExprStmt(Call);
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010781 }
John McCallab8c2732010-03-16 06:11:48 +000010782
Richard Smith52c0b582012-11-13 00:54:12 +000010783 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregorb139cd52010-05-01 20:49:11 +000010784 // operator is used.
Richard Smith52c0b582012-11-13 00:54:12 +000010785 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregorb139cd52010-05-01 20:49:11 +000010786 if (!ArrayTy) {
Pavel Labath58934982013-08-30 08:52:28 +000010787 ExprResult Assignment = S.CreateBuiltinBinOp(
10788 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000010789 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010790 return StmtError();
Richard Smith945f8d32013-01-14 22:39:08 +000010791 return S.ActOnExprStmt(Assignment);
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010792 }
Richard Smith52c0b582012-11-13 00:54:12 +000010793
10794 // - if the subobject is an array, each element is assigned, in the
Douglas Gregorb139cd52010-05-01 20:49:11 +000010795 // manner appropriate to the element type;
Richard Smith52c0b582012-11-13 00:54:12 +000010796
Douglas Gregorb139cd52010-05-01 20:49:11 +000010797 // Construct a loop over the array bounds, e.g.,
10798 //
10799 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
10800 //
10801 // that will copy each of the array elements.
10802 QualType SizeType = S.Context.getSizeType();
Richard Smith41ae3282012-11-14 00:50:40 +000010803
Douglas Gregorb139cd52010-05-01 20:49:11 +000010804 // Create the iteration variable.
Craig Topperc3ec1492014-05-26 06:22:03 +000010805 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010806 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000010807 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +000010808 llvm::raw_svector_ostream OS(Str);
10809 OS << "__i" << Depth;
10810 IterationVarName = &S.Context.Idents.get(OS.str());
10811 }
Abramo Bagnaradff19302011-03-08 08:55:46 +000010812 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +000010813 IterationVarName, SizeType,
10814 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindola6ae7e502013-04-03 19:27:57 +000010815 SC_None);
Richard Smith41ae3282012-11-14 00:50:40 +000010816
Douglas Gregorb139cd52010-05-01 20:49:11 +000010817 // Initialize the iteration variable to zero.
10818 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000010819 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000010820
Pavel Labath58934982013-08-30 08:52:28 +000010821 // Creates a reference to the iteration variable.
10822 RefBuilder IterationVarRef(IterationVar, SizeType);
10823 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman844f9452012-01-23 02:35:22 +000010824
Douglas Gregorb139cd52010-05-01 20:49:11 +000010825 // Create the DeclStmt that holds the iteration variable.
10826 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000010827
Douglas Gregorb139cd52010-05-01 20:49:11 +000010828 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath58934982013-08-30 08:52:28 +000010829 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
10830 MoveCastBuilder FromIndexMove(FromIndexCopy);
10831 const ExprBuilder *FromIndex;
10832 if (Copying)
10833 FromIndex = &FromIndexCopy;
10834 else
10835 FromIndex = &FromIndexMove;
10836
10837 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl22653ba2011-08-30 19:58:05 +000010838
10839 // Build the copy/move for an individual element of the array.
Richard Smith41ae3282012-11-14 00:50:40 +000010840 StmtResult Copy =
10841 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath58934982013-08-30 08:52:28 +000010842 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith41ae3282012-11-14 00:50:40 +000010843 Copying, Depth + 1);
10844 // Bail out if copying fails or if we determined that we should use memcpy.
10845 if (Copy.isInvalid() || !Copy.get())
10846 return Copy;
10847
10848 // Create the comparison against the array bound.
10849 llvm::APInt Upper
10850 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
10851 Expr *Comparison
Pavel Labath58934982013-08-30 08:52:28 +000010852 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith41ae3282012-11-14 00:50:40 +000010853 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
10854 BO_NE, S.Context.BoolTy,
10855 VK_RValue, OK_Ordinary, Loc, false);
10856
10857 // Create the pre-increment of the iteration variable.
10858 Expr *Increment
Pavel Labath58934982013-08-30 08:52:28 +000010859 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
10860 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith41ae3282012-11-14 00:50:40 +000010861
Douglas Gregorb139cd52010-05-01 20:49:11 +000010862 // Construct the loop that copies all elements of this array.
Richard Smith03a4aa32016-06-23 19:02:52 +000010863 return S.ActOnForStmt(
10864 Loc, Loc, InitStmt,
10865 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
10866 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010867}
10868
Richard Smith41ae3282012-11-14 00:50:40 +000010869static StmtResult
10870buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath58934982013-08-30 08:52:28 +000010871 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith41ae3282012-11-14 00:50:40 +000010872 bool CopyingBaseSubobject, bool Copying) {
10873 // Maybe we should use a memcpy?
10874 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
10875 T.isTriviallyCopyableType(S.Context))
10876 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
10877
10878 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
10879 CopyingBaseSubobject,
10880 Copying, 0));
10881
10882 // If we ended up picking a trivial assignment operator for an array of a
10883 // non-trivially-copyable class type, just emit a memcpy.
10884 if (!Result.isInvalid() && !Result.get())
10885 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
10886
10887 return Result;
10888}
10889
Richard Smithd3b5c9082012-07-27 04:22:15 +000010890Sema::ImplicitExceptionSpecification
10891Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
10892 CXXRecordDecl *ClassDecl = MD->getParent();
10893
10894 ImplicitExceptionSpecification ExceptSpec(*this);
10895 if (ClassDecl->isInvalidDecl())
10896 return ExceptSpec;
10897
10898 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000010899 assert(T->getNumParams() == 1 && "not a copy assignment op");
10900 unsigned ArgQuals =
10901 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010902
Douglas Gregor68e11362010-07-01 17:48:08 +000010903 // C++ [except.spec]p14:
Richard Smithd3b5c9082012-07-27 04:22:15 +000010904 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregor68e11362010-07-01 17:48:08 +000010905 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +000010906
10907 // It is unspecified whether or not an implicit copy assignment operator
10908 // attempts to deduplicate calls to assignment operators of virtual bases are
10909 // made. As such, this exception specification is effectively unspecified.
10910 // Based on a similar decision made for constness in C++0x, we're erring on
10911 // the side of assuming such calls to be made regardless of whether they
10912 // actually happen.
Aaron Ballman574705e2014-03-13 15:41:46 +000010913 for (const auto &Base : ClassDecl->bases()) {
10914 if (Base.isVirtual())
Alexis Hunt491ec602011-06-21 23:42:56 +000010915 continue;
10916
Douglas Gregor330b9cf2010-07-02 21:50:04 +000010917 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000010918 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +000010919 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10920 ArgQuals, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +000010921 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregor68e11362010-07-01 17:48:08 +000010922 }
Alexis Hunt491ec602011-06-21 23:42:56 +000010923
Aaron Ballman445a9392014-03-13 16:15:17 +000010924 for (const auto &Base : ClassDecl->vbases()) {
Alexis Hunt491ec602011-06-21 23:42:56 +000010925 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000010926 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +000010927 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10928 ArgQuals, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +000010929 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Alexis Hunt491ec602011-06-21 23:42:56 +000010930 }
10931
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000010932 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000010933 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +000010934 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10935 if (CXXMethodDecl *CopyAssign =
Richard Smith1c6461e2012-07-18 03:36:00 +000010936 LookupCopyingAssignment(FieldClassDecl,
10937 ArgQuals | FieldType.getCVRQualifiers(),
10938 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +000010939 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +000010940 }
Douglas Gregor68e11362010-07-01 17:48:08 +000010941 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000010942
Richard Smithd3b5c9082012-07-27 04:22:15 +000010943 return ExceptSpec;
Alexis Hunt119f3652011-05-14 05:23:20 +000010944}
10945
10946CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
10947 // Note: The following rules are largely analoguous to the copy
10948 // constructor rules. Note that virtual bases are not taken into account
10949 // for determining the argument type of the operator. Note also that
10950 // operators taking an object instead of a reference are allowed.
Richard Smith2be35f52012-12-01 02:35:44 +000010951 assert(ClassDecl->needsImplicitCopyAssignment());
Alexis Hunt119f3652011-05-14 05:23:20 +000010952
Richard Smith8bf22e52012-11-29 01:34:07 +000010953 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
10954 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000010955 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000010956
Alexis Hunt119f3652011-05-14 05:23:20 +000010957 QualType ArgType = Context.getTypeDeclType(ClassDecl);
10958 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smith99005e62013-05-07 03:19:20 +000010959 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
10960 if (Const)
Alexis Hunt119f3652011-05-14 05:23:20 +000010961 ArgType = ArgType.withConst();
10962 ArgType = Context.getLValueReferenceType(ArgType);
10963
Richard Smith99005e62013-05-07 03:19:20 +000010964 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10965 CXXCopyAssignment,
10966 Const);
10967
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010968 // An implicitly-declared copy assignment operator is an inline public
10969 // member of its class.
10970 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +000010971 SourceLocation ClassLoc = ClassDecl->getLocation();
10972 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000010973 CXXMethodDecl *CopyAssignment =
10974 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000010975 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10976 /*isInline=*/true, Constexpr, SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010977 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +000010978 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010979 CopyAssignment->setImplicit();
Richard Smithd3b5c9082012-07-27 04:22:15 +000010980
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010981 if (getLangOpts().CUDA) {
10982 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
10983 CopyAssignment,
10984 /* ConstRHS */ Const,
10985 /* Diagnose */ false);
10986 }
10987
Richard Smithd3b5c9082012-07-27 04:22:15 +000010988 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000010989 FunctionProtoType::ExtProtoInfo EPI =
10990 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000010991 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000010992
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000010993 // Add the parameter to the operator.
10994 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000010995 ClassLoc, ClassLoc,
10996 /*Id=*/nullptr, ArgType,
10997 /*TInfo=*/nullptr, SC_None,
10998 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000010999 CopyAssignment->setParams(FromParam);
Alexis Huntb2f27802011-05-14 05:23:24 +000011000
Richard Smith6b02d462012-12-08 08:32:28 +000011001 CopyAssignment->setTrivial(
11002 ClassDecl->needsOverloadResolutionForCopyAssignment()
11003 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11004 : ClassDecl->hasTrivialCopyAssignment());
11005
Richard Smith6b02d462012-12-08 08:32:28 +000011006 // Note that we have added this copy-assignment operator.
11007 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
11008
Richard Smith12e79312016-05-13 06:47:56 +000011009 Scope *S = getScopeForContext(ClassDecl);
11010 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11011
11012 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11013 SetDeclDeleted(CopyAssignment, ClassLoc);
11014
11015 if (S)
Richard Smith6b02d462012-12-08 08:32:28 +000011016 PushOnScopeChains(CopyAssignment, S, false);
11017 ClassDecl->addDecl(CopyAssignment);
11018
Douglas Gregorf56ab7b2010-07-01 16:36:15 +000011019 return CopyAssignment;
11020}
11021
Richard Smithd577fbb2013-06-13 03:23:42 +000011022/// Diagnose an implicit copy operation for a class which is odr-used, but
11023/// which is deprecated because the class has a user-declared copy constructor,
11024/// copy assignment operator, or destructor.
11025static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
11026 SourceLocation UseLoc) {
11027 assert(CopyOp->isImplicit());
11028
11029 CXXRecordDecl *RD = CopyOp->getParent();
Craig Topperc3ec1492014-05-26 06:22:03 +000011030 CXXMethodDecl *UserDeclaredOperation = nullptr;
Richard Smithd577fbb2013-06-13 03:23:42 +000011031
11032 // In Microsoft mode, assignment operations don't affect constructors and
11033 // vice versa.
11034 if (RD->hasUserDeclaredDestructor()) {
11035 UserDeclaredOperation = RD->getDestructor();
11036 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11037 RD->hasUserDeclaredCopyConstructor() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000011038 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011039 // Find any user-declared copy constructor.
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +000011040 for (auto *I : RD->ctors()) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011041 if (I->isCopyConstructor()) {
Aaron Ballman2a4bd6d2014-03-13 16:51:27 +000011042 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +000011043 break;
11044 }
11045 }
11046 assert(UserDeclaredOperation);
11047 } else if (isa<CXXConstructorDecl>(CopyOp) &&
11048 RD->hasUserDeclaredCopyAssignment() &&
Alp Tokerbfa39342014-01-14 12:51:41 +000011049 !S.getLangOpts().MSVCCompat) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011050 // Find any user-declared move assignment operator.
Aaron Ballman2b124d12014-03-13 16:36:16 +000011051 for (auto *I : RD->methods()) {
Richard Smithd577fbb2013-06-13 03:23:42 +000011052 if (I->isCopyAssignmentOperator()) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000011053 UserDeclaredOperation = I;
Richard Smithd577fbb2013-06-13 03:23:42 +000011054 break;
11055 }
11056 }
11057 assert(UserDeclaredOperation);
11058 }
11059
11060 if (UserDeclaredOperation) {
11061 S.Diag(UserDeclaredOperation->getLocation(),
11062 diag::warn_deprecated_copy_operation)
11063 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11064 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11065 S.Diag(UseLoc, diag::note_member_synthesized_at)
11066 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
11067 : Sema::CXXCopyAssignment)
11068 << RD;
11069 }
11070}
11071
Douglas Gregorb139cd52010-05-01 20:49:11 +000011072void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11073 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +000011074 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000011075 CopyAssignOperator->isOverloadedOperator() &&
11076 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000011077 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11078 !CopyAssignOperator->isDeleted()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +000011079 "DefineImplicitCopyAssignment called for wrong function");
11080
11081 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11082
11083 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
11084 CopyAssignOperator->setInvalidDecl();
11085 return;
11086 }
Richard Smithd577fbb2013-06-13 03:23:42 +000011087
11088 // C++11 [class.copy]p18:
11089 // The [definition of an implicitly declared copy assignment operator] is
11090 // deprecated if the class has a user-declared copy constructor or a
11091 // user-declared destructor.
11092 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11093 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
11094
Eli Friedman276dd182013-09-05 00:02:25 +000011095 CopyAssignOperator->markUsed(Context);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011096
Eli Friedmaneaf34142012-10-18 20:14:08 +000011097 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000011098 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011099
11100 // C++0x [class.copy]p30:
11101 // The implicitly-defined or explicitly-defaulted copy assignment operator
11102 // for a non-union class X performs memberwise copy assignment of its
11103 // subobjects. The direct base classes of X are assigned first, in the
11104 // order of their declaration in the base-specifier-list, and then the
11105 // immediate non-static data members of X are assigned, in the order in
11106 // which they were declared in the class definition.
11107
11108 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000011109 SmallVector<Stmt*, 8> Statements;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011110
11111 // The parameter for the "other" object, which we are copying from.
11112 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11113 Qualifiers OtherQuals = Other->getType().getQualifiers();
11114 QualType OtherRefType = Other->getType();
11115 if (const LValueReferenceType *OtherRef
11116 = OtherRefType->getAs<LValueReferenceType>()) {
11117 OtherRefType = OtherRef->getPointeeType();
11118 OtherQuals = OtherRefType.getQualifiers();
11119 }
11120
11121 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011122 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
11123 ? CopyAssignOperator->getLocEnd()
11124 : CopyAssignOperator->getLocation();
11125
Pavel Labath58934982013-08-30 08:52:28 +000011126 // Builds a DeclRefExpr for the "other" object.
11127 RefBuilder OtherRef(Other, OtherRefType);
11128
11129 // Builds the "this" pointer.
11130 ThisBuilder This;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011131
11132 // Assign base classes.
11133 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000011134 for (auto &Base : ClassDecl->bases()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000011135 // Form the assignment:
11136 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000011137 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +000011138 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +000011139 Invalid = true;
11140 continue;
11141 }
11142
John McCallcf142162010-08-07 06:22:56 +000011143 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000011144 BasePath.push_back(&Base);
John McCallcf142162010-08-07 06:22:56 +000011145
Douglas Gregorb139cd52010-05-01 20:49:11 +000011146 // Construct the "from" expression, which is an implicit cast to the
11147 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000011148 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
11149 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011150
11151 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000011152 DerefBuilder DerefThis(This);
11153 CastBuilder To(DerefThis,
11154 Context.getCVRQualifiedType(
11155 BaseType, CopyAssignOperator->getTypeQualifiers()),
11156 VK_LValue, BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011157
11158 // Build the copy.
Richard Smith41ae3282012-11-14 00:50:40 +000011159 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000011160 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000011161 /*CopyingBaseSubobject=*/true,
11162 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011163 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000011164 Diag(CurrentLocation, diag::note_member_synthesized_at)
11165 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11166 CopyAssignOperator->setInvalidDecl();
11167 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011168 }
11169
11170 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011171 Statements.push_back(Copy.getAs<Expr>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000011172 }
11173
Douglas Gregorb139cd52010-05-01 20:49:11 +000011174 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011175 for (auto *Field : ClassDecl->fields()) {
Richard Smith419bd092015-04-29 19:26:57 +000011176 // FIXME: We should form some kind of AST representation for the implied
11177 // memcpy in a union copy operation.
11178 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
Douglas Gregor556e5862011-10-10 17:22:13 +000011179 continue;
Eli Friedmanc9817fd2013-06-07 01:48:56 +000011180
11181 if (Field->isInvalidDecl()) {
11182 Invalid = true;
11183 continue;
11184 }
11185
Douglas Gregorb139cd52010-05-01 20:49:11 +000011186 // Check for members of reference type; we can't copy those.
11187 if (Field->getType()->isReferenceType()) {
11188 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11189 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11190 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000011191 Diag(CurrentLocation, diag::note_member_synthesized_at)
11192 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011193 Invalid = true;
11194 continue;
11195 }
11196
11197 // Check for members of const-qualified, non-class type.
11198 QualType BaseType = Context.getBaseElementType(Field->getType());
11199 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11200 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11201 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11202 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +000011203 Diag(CurrentLocation, diag::note_member_synthesized_at)
11204 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011205 Invalid = true;
11206 continue;
11207 }
John McCall1b1a1db2011-06-17 00:18:42 +000011208
11209 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000011210 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11211 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011212
11213 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +000011214 if (FieldType->isIncompleteArrayType()) {
11215 assert(ClassDecl->hasFlexibleArrayMember() &&
11216 "Incomplete array type is not valid");
11217 continue;
11218 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000011219
11220 // Build references to the field in the object we're copying from and to.
11221 CXXScopeSpec SS; // Intentionally empty
11222 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11223 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011224 MemberLookup.addDecl(Field);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011225 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000011226
11227 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
11228
11229 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011230
Douglas Gregorb139cd52010-05-01 20:49:11 +000011231 // Build the copy of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000011232 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000011233 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000011234 /*CopyingBaseSubobject=*/false,
11235 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +000011236 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +000011237 Diag(CurrentLocation, diag::note_member_synthesized_at)
11238 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11239 CopyAssignOperator->setInvalidDecl();
11240 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +000011241 }
11242
11243 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011244 Statements.push_back(Copy.getAs<Stmt>());
Douglas Gregorb139cd52010-05-01 20:49:11 +000011245 }
11246
11247 if (!Invalid) {
11248 // Add a "return *this;"
Pavel Labath58934982013-08-30 08:52:28 +000011249 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +000011250
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000011251 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +000011252 if (Return.isInvalid())
11253 Invalid = true;
11254 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011255 Statements.push_back(Return.getAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +000011256
11257 if (Trap.hasErrorOccurred()) {
11258 Diag(CurrentLocation, diag::note_member_synthesized_at)
11259 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11260 Invalid = true;
11261 }
Douglas Gregorb139cd52010-05-01 20:49:11 +000011262 }
11263 }
11264
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000011265 // The exception specification is needed because we are defining the
11266 // function.
11267 ResolveExceptionSpec(CurrentLocation,
11268 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11269
Douglas Gregorb139cd52010-05-01 20:49:11 +000011270 if (Invalid) {
11271 CopyAssignOperator->setInvalidDecl();
11272 return;
11273 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011274
11275 StmtResult Body;
11276 {
11277 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011278 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011279 /*isStmtExpr=*/false);
11280 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11281 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011282 CopyAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +000011283
11284 if (ASTMutationListener *L = getASTMutationListener()) {
11285 L->CompletedImplicitDefinition(CopyAssignOperator);
11286 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +000011287}
11288
Sebastian Redl22653ba2011-08-30 19:58:05 +000011289Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000011290Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
11291 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl22653ba2011-08-30 19:58:05 +000011292
Richard Smithd3b5c9082012-07-27 04:22:15 +000011293 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011294 if (ClassDecl->isInvalidDecl())
11295 return ExceptSpec;
11296
11297 // C++0x [except.spec]p14:
11298 // An implicitly declared special member function (Clause 12) shall have an
11299 // exception-specification. [...]
11300
11301 // It is unspecified whether or not an implicit move assignment operator
11302 // attempts to deduplicate calls to assignment operators of virtual bases are
11303 // made. As such, this exception specification is effectively unspecified.
11304 // Based on a similar decision made for constness in C++0x, we're erring on
11305 // the side of assuming such calls to be made regardless of whether they
11306 // actually happen.
11307 // Note that a move constructor is not implicitly declared when there are
11308 // virtual bases, but it can still be user-declared and explicitly defaulted.
Aaron Ballman574705e2014-03-13 15:41:46 +000011309 for (const auto &Base : ClassDecl->bases()) {
11310 if (Base.isVirtual())
Sebastian Redl22653ba2011-08-30 19:58:05 +000011311 continue;
11312
11313 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000011314 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011315 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000011316 0, false, 0))
Aaron Ballman574705e2014-03-13 15:41:46 +000011317 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011318 }
11319
Aaron Ballman445a9392014-03-13 16:15:17 +000011320 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000011321 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000011322 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011323 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith1c6461e2012-07-18 03:36:00 +000011324 0, false, 0))
Aaron Ballman445a9392014-03-13 16:15:17 +000011325 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011326 }
11327
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011328 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000011329 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011330 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000011331 if (CXXMethodDecl *MoveAssign =
11332 LookupMovingAssignment(FieldClassDecl,
11333 FieldType.getCVRQualifiers(),
11334 false, 0))
Richard Smithf623c962012-04-17 00:58:00 +000011335 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011336 }
11337 }
11338
11339 return ExceptSpec;
11340}
11341
11342CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000011343 assert(ClassDecl->needsImplicitMoveAssignment());
11344
Richard Smith8bf22e52012-11-29 01:34:07 +000011345 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
11346 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000011347 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000011348
Sebastian Redl22653ba2011-08-30 19:58:05 +000011349 // Note: The following rules are largely analoguous to the move
11350 // constructor rules.
11351
Sebastian Redl22653ba2011-08-30 19:58:05 +000011352 QualType ArgType = Context.getTypeDeclType(ClassDecl);
11353 QualType RetType = Context.getLValueReferenceType(ArgType);
11354 ArgType = Context.getRValueReferenceType(ArgType);
11355
Richard Smith99005e62013-05-07 03:19:20 +000011356 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11357 CXXMoveAssignment,
11358 false);
11359
Sebastian Redl22653ba2011-08-30 19:58:05 +000011360 // An implicitly-declared move assignment operator is an inline public
11361 // member of its class.
Sebastian Redl22653ba2011-08-30 19:58:05 +000011362 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11363 SourceLocation ClassLoc = ClassDecl->getLocation();
11364 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith99005e62013-05-07 03:19:20 +000011365 CXXMethodDecl *MoveAssignment =
11366 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Craig Topperc3ec1492014-05-26 06:22:03 +000011367 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
Richard Smith99005e62013-05-07 03:19:20 +000011368 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011369 MoveAssignment->setAccess(AS_public);
11370 MoveAssignment->setDefaulted();
11371 MoveAssignment->setImplicit();
Sebastian Redl22653ba2011-08-30 19:58:05 +000011372
Eli Bendersky9a220fc2014-09-29 20:38:29 +000011373 if (getLangOpts().CUDA) {
11374 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
11375 MoveAssignment,
11376 /* ConstRHS */ false,
11377 /* Diagnose */ false);
11378 }
11379
Richard Smithd3b5c9082012-07-27 04:22:15 +000011380 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000011381 FunctionProtoType::ExtProtoInfo EPI =
11382 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rose5c382722013-03-08 21:51:21 +000011383 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000011384
Sebastian Redl22653ba2011-08-30 19:58:05 +000011385 // Add the parameter to the operator.
11386 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
Craig Topperc3ec1492014-05-26 06:22:03 +000011387 ClassLoc, ClassLoc,
11388 /*Id=*/nullptr, ArgType,
11389 /*TInfo=*/nullptr, SC_None,
11390 nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000011391 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011392
Richard Smith6b02d462012-12-08 08:32:28 +000011393 MoveAssignment->setTrivial(
11394 ClassDecl->needsOverloadResolutionForMoveAssignment()
11395 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
11396 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011397
Richard Smith12e79312016-05-13 06:47:56 +000011398 // Note that we have added this copy-assignment operator.
11399 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
11400
11401 Scope *S = getScopeForContext(ClassDecl);
11402 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
11403
Richard Smithd951a1d2012-02-18 02:02:13 +000011404 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000011405 ClassDecl->setImplicitMoveAssignmentIsDeleted();
11406 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011407 }
11408
Richard Smith12e79312016-05-13 06:47:56 +000011409 if (S)
Sebastian Redl22653ba2011-08-30 19:58:05 +000011410 PushOnScopeChains(MoveAssignment, S, false);
11411 ClassDecl->addDecl(MoveAssignment);
11412
Sebastian Redl22653ba2011-08-30 19:58:05 +000011413 return MoveAssignment;
11414}
11415
Richard Smithb2504bd2013-11-04 04:26:14 +000011416/// Check if we're implicitly defining a move assignment operator for a class
11417/// with virtual bases. Such a move assignment might move-assign the virtual
11418/// base multiple times.
11419static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
11420 SourceLocation CurrentLocation) {
11421 assert(!Class->isDependentContext() && "should not define dependent move");
11422
11423 // Only a virtual base could get implicitly move-assigned multiple times.
11424 // Only a non-trivial move assignment can observe this. We only want to
11425 // diagnose if we implicitly define an assignment operator that assigns
11426 // two base classes, both of which move-assign the same virtual base.
11427 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
11428 Class->getNumBases() < 2)
11429 return;
11430
11431 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
11432 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
11433 VBaseMap VBases;
11434
Aaron Ballman574705e2014-03-13 15:41:46 +000011435 for (auto &BI : Class->bases()) {
11436 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000011437 while (!Worklist.empty()) {
11438 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
11439 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
11440
11441 // If the base has no non-trivial move assignment operators,
11442 // we don't care about moves from it.
11443 if (!Base->hasNonTrivialMoveAssignment())
11444 continue;
11445
11446 // If there's nothing virtual here, skip it.
11447 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
11448 continue;
11449
11450 // If we're not actually going to call a move assignment for this base,
11451 // or the selected move assignment is trivial, skip it.
11452 Sema::SpecialMemberOverloadResult *SMOR =
11453 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
11454 /*ConstArg*/false, /*VolatileArg*/false,
11455 /*RValueThis*/true, /*ConstThis*/false,
11456 /*VolatileThis*/false);
11457 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
11458 !SMOR->getMethod()->isMoveAssignmentOperator())
11459 continue;
11460
11461 if (BaseSpec->isVirtual()) {
11462 // We're going to move-assign this virtual base, and its move
11463 // assignment operator is not trivial. If this can happen for
11464 // multiple distinct direct bases of Class, diagnose it. (If it
11465 // only happens in one base, we'll diagnose it when synthesizing
11466 // that base class's move assignment operator.)
11467 CXXBaseSpecifier *&Existing =
Aaron Ballman574705e2014-03-13 15:41:46 +000011468 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smithb2504bd2013-11-04 04:26:14 +000011469 .first->second;
Aaron Ballman574705e2014-03-13 15:41:46 +000011470 if (Existing && Existing != &BI) {
Richard Smithb2504bd2013-11-04 04:26:14 +000011471 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
11472 << Class << Base;
11473 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
11474 << (Base->getCanonicalDecl() ==
11475 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11476 << Base << Existing->getType() << Existing->getSourceRange();
Aaron Ballman574705e2014-03-13 15:41:46 +000011477 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smithb2504bd2013-11-04 04:26:14 +000011478 << (Base->getCanonicalDecl() ==
Aaron Ballman574705e2014-03-13 15:41:46 +000011479 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11480 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smithb2504bd2013-11-04 04:26:14 +000011481
11482 // Only diagnose each vbase once.
Craig Topperc3ec1492014-05-26 06:22:03 +000011483 Existing = nullptr;
Richard Smithb2504bd2013-11-04 04:26:14 +000011484 }
11485 } else {
11486 // Only walk over bases that have defaulted move assignment operators.
11487 // We assume that any user-provided move assignment operator handles
11488 // the multiple-moves-of-vbase case itself somehow.
11489 if (!SMOR->getMethod()->isDefaulted())
11490 continue;
11491
11492 // We're going to move the base classes of Base. Add them to the list.
Aaron Ballman574705e2014-03-13 15:41:46 +000011493 for (auto &BI : Base->bases())
11494 Worklist.push_back(&BI);
Richard Smithb2504bd2013-11-04 04:26:14 +000011495 }
11496 }
11497 }
11498}
11499
Sebastian Redl22653ba2011-08-30 19:58:05 +000011500void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
11501 CXXMethodDecl *MoveAssignOperator) {
11502 assert((MoveAssignOperator->isDefaulted() &&
11503 MoveAssignOperator->isOverloadedOperator() &&
11504 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith273c4e92012-02-26 07:51:39 +000011505 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
11506 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000011507 "DefineImplicitMoveAssignment called for wrong function");
11508
11509 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
11510
11511 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
11512 MoveAssignOperator->setInvalidDecl();
11513 return;
11514 }
11515
Eli Friedman276dd182013-09-05 00:02:25 +000011516 MoveAssignOperator->markUsed(Context);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011517
Eli Friedmaneaf34142012-10-18 20:14:08 +000011518 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011519 DiagnosticErrorTrap Trap(Diags);
11520
11521 // C++0x [class.copy]p28:
11522 // The implicitly-defined or move assignment operator for a non-union class
11523 // X performs memberwise move assignment of its subobjects. The direct base
11524 // classes of X are assigned first, in the order of their declaration in the
11525 // base-specifier-list, and then the immediate non-static data members of X
11526 // are assigned, in the order in which they were declared in the class
11527 // definition.
11528
Richard Smithb2504bd2013-11-04 04:26:14 +000011529 // Issue a warning if our implicit move assignment operator will move
11530 // from a virtual base more than once.
11531 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith8b86f2d2013-11-04 01:48:18 +000011532
Sebastian Redl22653ba2011-08-30 19:58:05 +000011533 // The statements that form the synthesized function body.
Benjamin Kramerf0623432012-08-23 22:51:59 +000011534 SmallVector<Stmt*, 8> Statements;
Sebastian Redl22653ba2011-08-30 19:58:05 +000011535
11536 // The parameter for the "other" object, which we are move from.
11537 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
11538 QualType OtherRefType = Other->getType()->
11539 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7d170102013-05-15 07:37:26 +000011540 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000011541 "Bad argument type of defaulted move assignment");
11542
11543 // Our location for everything implicitly-generated.
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011544 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
11545 ? MoveAssignOperator->getLocEnd()
11546 : MoveAssignOperator->getLocation();
Sebastian Redl22653ba2011-08-30 19:58:05 +000011547
Pavel Labath58934982013-08-30 08:52:28 +000011548 // Builds a reference to the "other" object.
11549 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011550 // Cast to rvalue.
Pavel Labath58934982013-08-30 08:52:28 +000011551 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011552
Pavel Labath58934982013-08-30 08:52:28 +000011553 // Builds the "this" pointer.
11554 ThisBuilder This;
Richard Smithcf8ec8d2012-04-02 18:40:40 +000011555
Sebastian Redl22653ba2011-08-30 19:58:05 +000011556 // Assign base classes.
11557 bool Invalid = false;
Aaron Ballman574705e2014-03-13 15:41:46 +000011558 for (auto &Base : ClassDecl->bases()) {
Richard Smithb2504bd2013-11-04 04:26:14 +000011559 // C++11 [class.copy]p28:
11560 // It is unspecified whether subobjects representing virtual base classes
11561 // are assigned more than once by the implicitly-defined copy assignment
11562 // operator.
11563 // FIXME: Do not assign to a vbase that will be assigned by some other base
11564 // class. For a move-assignment, this can result in the vbase being moved
11565 // multiple times.
11566
Sebastian Redl22653ba2011-08-30 19:58:05 +000011567 // Form the assignment:
11568 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Aaron Ballman574705e2014-03-13 15:41:46 +000011569 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl22653ba2011-08-30 19:58:05 +000011570 if (!BaseType->isRecordType()) {
11571 Invalid = true;
11572 continue;
11573 }
11574
11575 CXXCastPath BasePath;
Aaron Ballman574705e2014-03-13 15:41:46 +000011576 BasePath.push_back(&Base);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011577
11578 // Construct the "from" expression, which is an implicit cast to the
11579 // appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000011580 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011581
11582 // Dereference "this".
Pavel Labath58934982013-08-30 08:52:28 +000011583 DerefBuilder DerefThis(This);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011584
11585 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath58934982013-08-30 08:52:28 +000011586 CastBuilder To(DerefThis,
11587 Context.getCVRQualifiedType(
11588 BaseType, MoveAssignOperator->getTypeQualifiers()),
11589 VK_LValue, BasePath);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011590
11591 // Build the move.
Richard Smith41ae3282012-11-14 00:50:40 +000011592 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath58934982013-08-30 08:52:28 +000011593 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000011594 /*CopyingBaseSubobject=*/true,
11595 /*Copying=*/false);
11596 if (Move.isInvalid()) {
11597 Diag(CurrentLocation, diag::note_member_synthesized_at)
11598 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11599 MoveAssignOperator->setInvalidDecl();
11600 return;
11601 }
11602
11603 // Success! Record the move.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011604 Statements.push_back(Move.getAs<Expr>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011605 }
11606
Sebastian Redl22653ba2011-08-30 19:58:05 +000011607 // Assign non-static members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011608 for (auto *Field : ClassDecl->fields()) {
Richard Smith419bd092015-04-29 19:26:57 +000011609 // FIXME: We should form some kind of AST representation for the implied
11610 // memcpy in a union copy operation.
11611 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
Douglas Gregor556e5862011-10-10 17:22:13 +000011612 continue;
11613
Eli Friedmanc9817fd2013-06-07 01:48:56 +000011614 if (Field->isInvalidDecl()) {
11615 Invalid = true;
11616 continue;
11617 }
11618
Sebastian Redl22653ba2011-08-30 19:58:05 +000011619 // Check for members of reference type; we can't move those.
11620 if (Field->getType()->isReferenceType()) {
11621 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11622 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11623 Diag(Field->getLocation(), diag::note_declared_at);
11624 Diag(CurrentLocation, diag::note_member_synthesized_at)
11625 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11626 Invalid = true;
11627 continue;
11628 }
11629
11630 // Check for members of const-qualified, non-class type.
11631 QualType BaseType = Context.getBaseElementType(Field->getType());
11632 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11633 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11634 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11635 Diag(Field->getLocation(), diag::note_declared_at);
11636 Diag(CurrentLocation, diag::note_member_synthesized_at)
11637 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11638 Invalid = true;
11639 continue;
11640 }
11641
11642 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +000011643 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11644 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +000011645
11646 QualType FieldType = Field->getType().getNonReferenceType();
11647 if (FieldType->isIncompleteArrayType()) {
11648 assert(ClassDecl->hasFlexibleArrayMember() &&
11649 "Incomplete array type is not valid");
11650 continue;
11651 }
11652
11653 // Build references to the field in the object we're copying from and to.
Sebastian Redl22653ba2011-08-30 19:58:05 +000011654 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11655 LookupMemberName);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011656 MemberLookup.addDecl(Field);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011657 MemberLookup.resolveKind();
Pavel Labath58934982013-08-30 08:52:28 +000011658 MemberBuilder From(MoveOther, OtherRefType,
11659 /*IsArrow=*/false, MemberLookup);
11660 MemberBuilder To(This, getCurrentThisType(),
11661 /*IsArrow=*/true, MemberLookup);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011662
Pavel Labath58934982013-08-30 08:52:28 +000011663 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl22653ba2011-08-30 19:58:05 +000011664 "Member reference with rvalue base must be rvalue except for reference "
11665 "members, which aren't allowed for move assignment.");
11666
Sebastian Redl22653ba2011-08-30 19:58:05 +000011667 // Build the move of this field.
Richard Smith41ae3282012-11-14 00:50:40 +000011668 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath58934982013-08-30 08:52:28 +000011669 To, From,
Sebastian Redl22653ba2011-08-30 19:58:05 +000011670 /*CopyingBaseSubobject=*/false,
11671 /*Copying=*/false);
11672 if (Move.isInvalid()) {
11673 Diag(CurrentLocation, diag::note_member_synthesized_at)
11674 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11675 MoveAssignOperator->setInvalidDecl();
11676 return;
11677 }
Richard Smith11d19592012-11-12 23:33:00 +000011678
Sebastian Redl22653ba2011-08-30 19:58:05 +000011679 // Success! Record the copy.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011680 Statements.push_back(Move.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011681 }
11682
11683 if (!Invalid) {
11684 // Add a "return *this;"
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011685 ExprResult ThisObj =
11686 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11687
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000011688 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011689 if (Return.isInvalid())
11690 Invalid = true;
11691 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011692 Statements.push_back(Return.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011693
11694 if (Trap.hasErrorOccurred()) {
11695 Diag(CurrentLocation, diag::note_member_synthesized_at)
11696 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11697 Invalid = true;
11698 }
11699 }
11700 }
11701
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000011702 // The exception specification is needed because we are defining the
11703 // function.
11704 ResolveExceptionSpec(CurrentLocation,
11705 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
11706
Sebastian Redl22653ba2011-08-30 19:58:05 +000011707 if (Invalid) {
11708 MoveAssignOperator->setInvalidDecl();
11709 return;
11710 }
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011711
11712 StmtResult Body;
11713 {
11714 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011715 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011716 /*isStmtExpr=*/false);
11717 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11718 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011719 MoveAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011720
11721 if (ASTMutationListener *L = getASTMutationListener()) {
11722 L->CompletedImplicitDefinition(MoveAssignOperator);
11723 }
11724}
11725
Richard Smithd3b5c9082012-07-27 04:22:15 +000011726Sema::ImplicitExceptionSpecification
11727Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
11728 CXXRecordDecl *ClassDecl = MD->getParent();
11729
11730 ImplicitExceptionSpecification ExceptSpec(*this);
11731 if (ClassDecl->isInvalidDecl())
11732 return ExceptSpec;
11733
11734 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +000011735 assert(T->getNumParams() >= 1 && "not a copy ctor");
11736 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithd3b5c9082012-07-27 04:22:15 +000011737
Douglas Gregor8453ddb2010-07-01 20:59:04 +000011738 // C++ [except.spec]p14:
11739 // An implicitly declared special member function (Clause 12) shall have an
11740 // exception-specification. [...]
Aaron Ballman574705e2014-03-13 15:41:46 +000011741 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor8453ddb2010-07-01 20:59:04 +000011742 // Virtual bases are handled below.
Aaron Ballman574705e2014-03-13 15:41:46 +000011743 if (Base.isVirtual())
Douglas Gregor8453ddb2010-07-01 20:59:04 +000011744 continue;
11745
Douglas Gregora6d69502010-07-02 23:41:54 +000011746 CXXRecordDecl *BaseClassDecl
Aaron Ballman574705e2014-03-13 15:41:46 +000011747 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000011748 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000011749 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman574705e2014-03-13 15:41:46 +000011750 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000011751 }
Aaron Ballman445a9392014-03-13 16:15:17 +000011752 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregora6d69502010-07-02 23:41:54 +000011753 CXXRecordDecl *BaseClassDecl
Aaron Ballman445a9392014-03-13 16:15:17 +000011754 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +000011755 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +000011756 LookupCopyingConstructor(BaseClassDecl, Quals))
Aaron Ballman445a9392014-03-13 16:15:17 +000011757 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000011758 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011759 for (const auto *Field : ClassDecl->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +000011760 QualType FieldType = Context.getBaseElementType(Field->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +000011761 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
11762 if (CXXConstructorDecl *CopyConstructor =
Richard Smith1c6461e2012-07-18 03:36:00 +000011763 LookupCopyingConstructor(FieldClassDecl,
11764 Quals | FieldType.getCVRQualifiers()))
Richard Smithf623c962012-04-17 00:58:00 +000011765 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +000011766 }
11767 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +000011768
Richard Smithd3b5c9082012-07-27 04:22:15 +000011769 return ExceptSpec;
Alexis Hunt913820d2011-05-13 06:10:58 +000011770}
11771
11772CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
11773 CXXRecordDecl *ClassDecl) {
11774 // C++ [class.copy]p4:
11775 // If the class definition does not explicitly declare a copy
11776 // constructor, one is declared implicitly.
Richard Smith2be35f52012-12-01 02:35:44 +000011777 assert(ClassDecl->needsImplicitCopyConstructor());
Alexis Hunt913820d2011-05-13 06:10:58 +000011778
Richard Smith8bf22e52012-11-29 01:34:07 +000011779 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
11780 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000011781 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000011782
Alexis Hunt913820d2011-05-13 06:10:58 +000011783 QualType ClassType = Context.getTypeDeclType(ClassDecl);
11784 QualType ArgType = ClassType;
Richard Smith1c33fe82012-11-28 06:23:12 +000011785 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Alexis Hunt913820d2011-05-13 06:10:58 +000011786 if (Const)
11787 ArgType = ArgType.withConst();
11788 ArgType = Context.getLValueReferenceType(ArgType);
Alexis Hunt913820d2011-05-13 06:10:58 +000011789
Richard Smithb5800092012-06-10 05:43:50 +000011790 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11791 CXXCopyConstructor,
11792 Const);
11793
Douglas Gregor54be3392010-07-01 17:57:27 +000011794 DeclarationName Name
11795 = Context.DeclarationNames.getCXXConstructorName(
11796 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +000011797 SourceLocation ClassLoc = ClassDecl->getLocation();
11798 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +000011799
11800 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000011801 // member of its class.
11802 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000011803 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000011804 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000011805 Constexpr);
Douglas Gregor54be3392010-07-01 17:57:27 +000011806 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +000011807 CopyConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000011808
Eli Bendersky9a220fc2014-09-29 20:38:29 +000011809 if (getLangOpts().CUDA) {
11810 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
11811 CopyConstructor,
11812 /* ConstRHS */ Const,
11813 /* Diagnose */ false);
11814 }
11815
Richard Smithd3b5c9082012-07-27 04:22:15 +000011816 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000011817 FunctionProtoType::ExtProtoInfo EPI =
11818 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000011819 CopyConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000011820 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000011821
Douglas Gregor54be3392010-07-01 17:57:27 +000011822 // Add the parameter to the constructor.
11823 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +000011824 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000011825 /*IdentifierInfo=*/nullptr,
11826 ArgType, /*TInfo=*/nullptr,
11827 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000011828 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +000011829
Richard Smith6b02d462012-12-08 08:32:28 +000011830 CopyConstructor->setTrivial(
11831 ClassDecl->needsOverloadResolutionForCopyConstructor()
11832 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
11833 : ClassDecl->hasTrivialCopyConstructor());
Alexis Hunte77a28f2011-05-18 03:41:58 +000011834
Richard Smith6b02d462012-12-08 08:32:28 +000011835 // Note that we have declared this constructor.
11836 ++ASTContext::NumImplicitCopyConstructorsDeclared;
11837
Richard Smith12e79312016-05-13 06:47:56 +000011838 Scope *S = getScopeForContext(ClassDecl);
11839 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
11840
11841 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
11842 SetDeclDeleted(CopyConstructor, ClassLoc);
11843
11844 if (S)
Richard Smith6b02d462012-12-08 08:32:28 +000011845 PushOnScopeChains(CopyConstructor, S, false);
11846 ClassDecl->addDecl(CopyConstructor);
11847
Douglas Gregor54be3392010-07-01 17:57:27 +000011848 return CopyConstructor;
11849}
11850
Fariborz Jahanian477d2422009-06-22 23:34:40 +000011851void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +000011852 CXXConstructorDecl *CopyConstructor) {
11853 assert((CopyConstructor->isDefaulted() &&
11854 CopyConstructor->isCopyConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000011855 !CopyConstructor->doesThisDeclarationHaveABody() &&
11856 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +000011857 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +000011858
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +000011859 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +000011860 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011861
Richard Smithd577fbb2013-06-13 03:23:42 +000011862 // C++11 [class.copy]p7:
Benjamin Kramer60509af2013-09-09 14:48:42 +000011863 // The [definition of an implicitly declared copy constructor] is
Richard Smithd577fbb2013-06-13 03:23:42 +000011864 // deprecated if the class has a user-declared copy assignment operator
11865 // or a user-declared destructor.
11866 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
11867 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
11868
Eli Friedmaneaf34142012-10-18 20:14:08 +000011869 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +000011870 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +000011871
David Blaikie3fc2f912013-01-17 05:26:25 +000011872 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +000011873 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +000011874 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +000011875 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +000011876 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +000011877 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011878 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
11879 ? CopyConstructor->getLocEnd()
11880 : CopyConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011881 Sema::CompoundScopeRAII CompoundScope(*this);
Daniel Jasperb3b0b802014-06-20 08:44:22 +000011882 CopyConstructor->setBody(
11883 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +000011884 }
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000011885
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000011886 // The exception specification is needed because we are defining the
11887 // function.
11888 ResolveExceptionSpec(CurrentLocation,
11889 CopyConstructor->getType()->castAs<FunctionProtoType>());
11890
Eli Friedman276dd182013-09-05 00:02:25 +000011891 CopyConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000011892 MarkVTableUsed(CurrentLocation, ClassDecl);
11893
Sebastian Redlab238a72011-04-24 16:28:06 +000011894 if (ASTMutationListener *L = getASTMutationListener()) {
11895 L->CompletedImplicitDefinition(CopyConstructor);
11896 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000011897}
11898
Sebastian Redl22653ba2011-08-30 19:58:05 +000011899Sema::ImplicitExceptionSpecification
Richard Smithd3b5c9082012-07-27 04:22:15 +000011900Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
11901 CXXRecordDecl *ClassDecl = MD->getParent();
11902
Sebastian Redl22653ba2011-08-30 19:58:05 +000011903 // C++ [except.spec]p14:
11904 // An implicitly declared special member function (Clause 12) shall have an
11905 // exception-specification. [...]
Richard Smithf623c962012-04-17 00:58:00 +000011906 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011907 if (ClassDecl->isInvalidDecl())
11908 return ExceptSpec;
11909
11910 // Direct base-class constructors.
Aaron Ballman574705e2014-03-13 15:41:46 +000011911 for (const auto &B : ClassDecl->bases()) {
11912 if (B.isVirtual()) // Handled below.
Sebastian Redl22653ba2011-08-30 19:58:05 +000011913 continue;
11914
Aaron Ballman574705e2014-03-13 15:41:46 +000011915 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000011916 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000011917 CXXConstructorDecl *Constructor =
11918 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011919 // If this is a deleted function, add it anyway. This might be conformant
11920 // with the standard. This might not. I'm not sure. It might not matter.
11921 if (Constructor)
Aaron Ballman574705e2014-03-13 15:41:46 +000011922 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011923 }
11924 }
11925
11926 // Virtual base-class constructors.
Aaron Ballman445a9392014-03-13 16:15:17 +000011927 for (const auto &B : ClassDecl->vbases()) {
11928 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000011929 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith1c6461e2012-07-18 03:36:00 +000011930 CXXConstructorDecl *Constructor =
11931 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011932 // If this is a deleted function, add it anyway. This might be conformant
11933 // with the standard. This might not. I'm not sure. It might not matter.
11934 if (Constructor)
Aaron Ballman445a9392014-03-13 16:15:17 +000011935 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011936 }
11937 }
11938
11939 // Field constructors.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011940 for (const auto *F : ClassDecl->fields()) {
Richard Smith1c6461e2012-07-18 03:36:00 +000011941 QualType FieldType = Context.getBaseElementType(F->getType());
11942 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
11943 CXXConstructorDecl *Constructor =
11944 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl22653ba2011-08-30 19:58:05 +000011945 // If this is a deleted function, add it anyway. This might be conformant
11946 // with the standard. This might not. I'm not sure. It might not matter.
11947 // In particular, the problem is that this function never gets called. It
11948 // might just be ill-formed because this function attempts to refer to
11949 // a deleted function here.
11950 if (Constructor)
Richard Smithf623c962012-04-17 00:58:00 +000011951 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011952 }
11953 }
11954
11955 return ExceptSpec;
11956}
11957
11958CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
11959 CXXRecordDecl *ClassDecl) {
Richard Smithcf8ec8d2012-04-02 18:40:40 +000011960 assert(ClassDecl->needsImplicitMoveConstructor());
11961
Richard Smith8bf22e52012-11-29 01:34:07 +000011962 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
11963 if (DSM.isAlreadyBeingDeclared())
Craig Topperc3ec1492014-05-26 06:22:03 +000011964 return nullptr;
Richard Smith8bf22e52012-11-29 01:34:07 +000011965
Sebastian Redl22653ba2011-08-30 19:58:05 +000011966 QualType ClassType = Context.getTypeDeclType(ClassDecl);
11967 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011968
Richard Smithb5800092012-06-10 05:43:50 +000011969 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11970 CXXMoveConstructor,
11971 false);
11972
Sebastian Redl22653ba2011-08-30 19:58:05 +000011973 DeclarationName Name
11974 = Context.DeclarationNames.getCXXConstructorName(
11975 Context.getCanonicalType(ClassType));
11976 SourceLocation ClassLoc = ClassDecl->getLocation();
11977 DeclarationNameInfo NameInfo(Name, ClassLoc);
11978
Richard Smith99005e62013-05-07 03:19:20 +000011979 // C++11 [class.copy]p11:
Sebastian Redl22653ba2011-08-30 19:58:05 +000011980 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +000011981 // member of its class.
11982 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Craig Topperc3ec1492014-05-26 06:22:03 +000011983 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smithcc36f692011-12-22 02:22:31 +000011984 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smithb5800092012-06-10 05:43:50 +000011985 Constexpr);
Sebastian Redl22653ba2011-08-30 19:58:05 +000011986 MoveConstructor->setAccess(AS_public);
11987 MoveConstructor->setDefaulted();
Richard Smithcc36f692011-12-22 02:22:31 +000011988
Eli Bendersky9a220fc2014-09-29 20:38:29 +000011989 if (getLangOpts().CUDA) {
11990 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
11991 MoveConstructor,
11992 /* ConstRHS */ false,
11993 /* Diagnose */ false);
11994 }
11995
Richard Smithd3b5c9082012-07-27 04:22:15 +000011996 // Build an exception specification pointing back at this member.
Reid Kleckner78af0702013-08-27 23:08:25 +000011997 FunctionProtoType::ExtProtoInfo EPI =
11998 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithd3b5c9082012-07-27 04:22:15 +000011999 MoveConstructor->setType(
Jordan Rose5c382722013-03-08 21:51:21 +000012000 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithd3b5c9082012-07-27 04:22:15 +000012001
Sebastian Redl22653ba2011-08-30 19:58:05 +000012002 // Add the parameter to the constructor.
12003 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12004 ClassLoc, ClassLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +000012005 /*IdentifierInfo=*/nullptr,
12006 ArgType, /*TInfo=*/nullptr,
12007 SC_None, nullptr);
David Blaikie9c70e042011-09-21 18:16:56 +000012008 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012009
Richard Smith6b02d462012-12-08 08:32:28 +000012010 MoveConstructor->setTrivial(
12011 ClassDecl->needsOverloadResolutionForMoveConstructor()
12012 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12013 : ClassDecl->hasTrivialMoveConstructor());
12014
Richard Smith12e79312016-05-13 06:47:56 +000012015 // Note that we have declared this constructor.
12016 ++ASTContext::NumImplicitMoveConstructorsDeclared;
12017
12018 Scope *S = getScopeForContext(ClassDecl);
12019 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12020
Alexis Hunt77c1f9f2011-10-11 06:43:29 +000012021 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith8b86f2d2013-11-04 01:48:18 +000012022 ClassDecl->setImplicitMoveConstructorIsDeleted();
12023 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012024 }
12025
Richard Smith12e79312016-05-13 06:47:56 +000012026 if (S)
Sebastian Redl22653ba2011-08-30 19:58:05 +000012027 PushOnScopeChains(MoveConstructor, S, false);
12028 ClassDecl->addDecl(MoveConstructor);
12029
12030 return MoveConstructor;
12031}
12032
12033void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12034 CXXConstructorDecl *MoveConstructor) {
12035 assert((MoveConstructor->isDefaulted() &&
12036 MoveConstructor->isMoveConstructor() &&
Richard Smith273c4e92012-02-26 07:51:39 +000012037 !MoveConstructor->doesThisDeclarationHaveABody() &&
12038 !MoveConstructor->isDeleted()) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +000012039 "DefineImplicitMoveConstructor - call it for implicit move ctor");
12040
12041 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12042 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12043
Eli Friedmaneaf34142012-10-18 20:14:08 +000012044 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012045 DiagnosticErrorTrap Trap(Diags);
12046
David Blaikie3fc2f912013-01-17 05:26:25 +000012047 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl22653ba2011-08-30 19:58:05 +000012048 Trap.hasErrorOccurred()) {
12049 Diag(CurrentLocation, diag::note_member_synthesized_at)
12050 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
12051 MoveConstructor->setInvalidDecl();
12052 } else {
Daniel Jasperb3b0b802014-06-20 08:44:22 +000012053 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
12054 ? MoveConstructor->getLocEnd()
12055 : MoveConstructor->getLocation();
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012056 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelm27b2c9a32013-08-19 20:51:20 +000012057 MoveConstructor->setBody(ActOnCompoundStmt(
Daniel Jasperb3b0b802014-06-20 08:44:22 +000012058 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
Sebastian Redl22653ba2011-08-30 19:58:05 +000012059 }
12060
Ben Langmuir2f8e6b82014-09-25 20:55:00 +000012061 // The exception specification is needed because we are defining the
12062 // function.
12063 ResolveExceptionSpec(CurrentLocation,
12064 MoveConstructor->getType()->castAs<FunctionProtoType>());
12065
Eli Friedman276dd182013-09-05 00:02:25 +000012066 MoveConstructor->markUsed(Context);
Reid Kleckner3be586f2014-07-18 01:48:10 +000012067 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl22653ba2011-08-30 19:58:05 +000012068
12069 if (ASTMutationListener *L = getASTMutationListener()) {
12070 L->CompletedImplicitDefinition(MoveConstructor);
12071 }
12072}
12073
Douglas Gregor74f7d502012-02-15 19:33:52 +000012074bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanebea0f22013-07-18 23:29:14 +000012075 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregor74f7d502012-02-15 19:33:52 +000012076}
Douglas Gregord3b672c2012-02-16 01:06:16 +000012077
12078void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Vali571df122013-09-29 08:45:24 +000012079 SourceLocation CurrentLocation,
12080 CXXConversionDecl *Conv) {
12081 CXXRecordDecl *Lambda = Conv->getParent();
12082 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
12083 // If we are defining a specialization of a conversion to function-ptr
12084 // cache the deduced template arguments for this specialization
12085 // so that we can use them to retrieve the corresponding call-operator
12086 // and static-invoker.
Craig Topperc3ec1492014-05-26 06:22:03 +000012087 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
12088
Faisal Vali571df122013-09-29 08:45:24 +000012089 // Retrieve the corresponding call-operator specialization.
12090 if (Lambda->isGenericLambda()) {
12091 assert(Conv->isFunctionTemplateSpecialization());
12092 FunctionTemplateDecl *CallOpTemplate =
12093 CallOp->getDescribedFunctionTemplate();
12094 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
Craig Topperc3ec1492014-05-26 06:22:03 +000012095 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000012096 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000012097 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000012098 InsertPos);
12099 assert(CallOpSpec &&
12100 "Conversion operator must have a corresponding call operator");
12101 CallOp = cast<CXXMethodDecl>(CallOpSpec);
12102 }
12103 // Mark the call operator referenced (and add to pending instantiations
12104 // if necessary).
12105 // For both the conversion and static-invoker template specializations
12106 // we construct their body's in this function, so no need to add them
12107 // to the PendingInstantiations.
12108 MarkFunctionReferenced(CurrentLocation, CallOp);
12109
Eli Friedmaneaf34142012-10-18 20:14:08 +000012110 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000012111 DiagnosticErrorTrap Trap(Diags);
Faisal Vali571df122013-09-29 08:45:24 +000012112
Alp Tokerf6a24ce2013-12-05 16:25:25 +000012113 // Retrieve the static invoker...
Faisal Vali571df122013-09-29 08:45:24 +000012114 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
12115 // ... and get the corresponding specialization for a generic lambda.
12116 if (Lambda->isGenericLambda()) {
12117 assert(DeducedTemplateArgs &&
12118 "Must have deduced template arguments from Conversion Operator");
12119 FunctionTemplateDecl *InvokeTemplate =
12120 Invoker->getDescribedFunctionTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +000012121 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +000012122 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +000012123 DeducedTemplateArgs->asArray(),
Faisal Vali571df122013-09-29 08:45:24 +000012124 InsertPos);
12125 assert(InvokeSpec &&
12126 "Must have a corresponding static invoker specialization");
12127 Invoker = cast<CXXMethodDecl>(InvokeSpec);
12128 }
12129 // Construct the body of the conversion function { return __invoke; }.
12130 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012131 VK_LValue, Conv->getLocation()).get();
Faisal Vali571df122013-09-29 08:45:24 +000012132 assert(FunctionRef && "Can't refer to __invoke function?");
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012133 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
Faisal Vali571df122013-09-29 08:45:24 +000012134 Conv->setBody(new (Context) CompoundStmt(Context, Return,
12135 Conv->getLocation(),
12136 Conv->getLocation()));
12137
12138 Conv->markUsed(Context);
12139 Conv->setReferenced();
Douglas Gregord3b672c2012-02-16 01:06:16 +000012140
Faisal Vali571df122013-09-29 08:45:24 +000012141 // Fill in the __invoke function with a dummy implementation. IR generation
12142 // will fill in the actual details.
12143 Invoker->markUsed(Context);
12144 Invoker->setReferenced();
12145 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12146
Douglas Gregord3b672c2012-02-16 01:06:16 +000012147 if (ASTMutationListener *L = getASTMutationListener()) {
12148 L->CompletedImplicitDefinition(Conv);
Faisal Vali571df122013-09-29 08:45:24 +000012149 L->CompletedImplicitDefinition(Invoker);
12150 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000012151}
12152
Faisal Vali571df122013-09-29 08:45:24 +000012153
12154
Douglas Gregord3b672c2012-02-16 01:06:16 +000012155void Sema::DefineImplicitLambdaToBlockPointerConversion(
12156 SourceLocation CurrentLocation,
12157 CXXConversionDecl *Conv)
12158{
Faisal Vali850da1a2013-09-29 17:08:32 +000012159 assert(!Conv->getParent()->isGenericLambda());
Faisal Vali571df122013-09-29 08:45:24 +000012160
Eli Friedman276dd182013-09-05 00:02:25 +000012161 Conv->markUsed(Context);
Douglas Gregord3b672c2012-02-16 01:06:16 +000012162
Eli Friedmaneaf34142012-10-18 20:14:08 +000012163 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregord3b672c2012-02-16 01:06:16 +000012164 DiagnosticErrorTrap Trap(Diags);
12165
Douglas Gregored90df32012-02-22 05:02:47 +000012166 // Copy-initialize the lambda object as needed to capture it.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012167 Expr *This = ActOnCXXThis(CurrentLocation).get();
12168 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
Douglas Gregord3b672c2012-02-16 01:06:16 +000012169
Eli Friedman98b01ed2012-03-01 04:01:32 +000012170 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12171 Conv->getLocation(),
12172 Conv, DerefThis);
12173
12174 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12175 // behavior. Note that only the general conversion function does this
12176 // (since it's unusable otherwise); in the case where we inline the
12177 // block literal, it has block literal lifetime semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +000012178 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman98b01ed2012-03-01 04:01:32 +000012179 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12180 CK_CopyAndAutoreleaseBlockObject,
Craig Topperc3ec1492014-05-26 06:22:03 +000012181 BuildBlock.get(), nullptr, VK_RValue);
Eli Friedman98b01ed2012-03-01 04:01:32 +000012182
12183 if (BuildBlock.isInvalid()) {
Douglas Gregord3b672c2012-02-16 01:06:16 +000012184 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregored90df32012-02-22 05:02:47 +000012185 Conv->setInvalidDecl();
12186 return;
Douglas Gregord3b672c2012-02-16 01:06:16 +000012187 }
Douglas Gregored90df32012-02-22 05:02:47 +000012188
Douglas Gregored90df32012-02-22 05:02:47 +000012189 // Create the return statement that returns the block from the conversion
12190 // function.
Nick Lewyckyd78f92f2014-05-03 00:41:18 +000012191 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregored90df32012-02-22 05:02:47 +000012192 if (Return.isInvalid()) {
12193 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12194 Conv->setInvalidDecl();
12195 return;
12196 }
12197
12198 // Set the body of the conversion function.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012199 Stmt *ReturnS = Return.get();
Nico Webera2a0eb92012-12-29 20:03:39 +000012200 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregored90df32012-02-22 05:02:47 +000012201 Conv->getLocation(),
Douglas Gregord3b672c2012-02-16 01:06:16 +000012202 Conv->getLocation()));
12203
Douglas Gregored90df32012-02-22 05:02:47 +000012204 // We're done; notify the mutation listener, if any.
Douglas Gregord3b672c2012-02-16 01:06:16 +000012205 if (ASTMutationListener *L = getASTMutationListener()) {
12206 L->CompletedImplicitDefinition(Conv);
12207 }
12208}
12209
Douglas Gregord2f70072012-03-10 06:53:13 +000012210/// \brief Determine whether the given list arguments contains exactly one
12211/// "real" (non-default) argument.
12212static bool hasOneRealArgument(MultiExprArg Args) {
12213 switch (Args.size()) {
12214 case 0:
12215 return false;
12216
12217 default:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012218 if (!Args[1]->isDefaultArgument())
Douglas Gregord2f70072012-03-10 06:53:13 +000012219 return false;
12220
12221 // fall through
12222 case 1:
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012223 return !Args[0]->isDefaultArgument();
Douglas Gregord2f70072012-03-10 06:53:13 +000012224 }
12225
12226 return false;
12227}
12228
John McCalldadc5752010-08-24 06:29:42 +000012229ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000012230Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Richard Smithc2bebe92016-05-11 20:37:46 +000012231 NamedDecl *FoundDecl,
Mike Stump11289f42009-09-09 15:08:12 +000012232 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000012233 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012234 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000012235 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000012236 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000012237 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000012238 unsigned ConstructKind,
12239 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +000012240 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +000012241
Douglas Gregor45cf7e32010-04-02 18:24:57 +000012242 // C++0x [class.copy]p34:
12243 // When certain criteria are met, an implementation is allowed to
12244 // omit the copy/move construction of a class object, even if the
12245 // copy/move constructor and/or destructor for the object have
12246 // side effects. [...]
12247 // - when a temporary class object that has not been bound to a
12248 // reference (12.2) would be copied/moved to a class object
12249 // with the same cv-unqualified type, the copy/move operation
12250 // can be omitted by constructing the temporary object
12251 // directly into the target of the omitted copy/move
Richard Smith5179eb72016-06-28 19:03:57 +000012252 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
Douglas Gregord2f70072012-03-10 06:53:13 +000012253 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000012254 Expr *SubExpr = ExprArgs[0];
Richard Smith5179eb72016-06-28 19:03:57 +000012255 Elidable = SubExpr->isTemporaryObject(
12256 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
Anders Carlsson250aada2009-08-16 05:13:48 +000012257 }
Mike Stump11289f42009-09-09 15:08:12 +000012258
Richard Smithc2bebe92016-05-11 20:37:46 +000012259 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12260 FoundDecl, Constructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012261 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithf8adcdc2014-07-17 05:12:35 +000012262 IsListInitialization,
12263 IsStdInitListInitialization, RequiresZeroInit,
Richard Smithd59b8322012-12-19 01:39:02 +000012264 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +000012265}
12266
John McCalldadc5752010-08-24 06:29:42 +000012267ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +000012268Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Richard Smithc2bebe92016-05-11 20:37:46 +000012269 NamedDecl *FoundDecl,
12270 CXXConstructorDecl *Constructor,
12271 bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +000012272 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012273 bool HadMultipleCandidates,
Richard Smithd59b8322012-12-19 01:39:02 +000012274 bool IsListInitialization,
Richard Smithf8adcdc2014-07-17 05:12:35 +000012275 bool IsStdInitListInitialization,
Douglas Gregor7ae2d772010-01-31 09:12:51 +000012276 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +000012277 unsigned ConstructKind,
12278 SourceRange ParenRange) {
Richard Smith80a47022016-06-29 01:10:27 +000012279 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
Richard Smith5179eb72016-06-28 19:03:57 +000012280 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
Richard Smith80a47022016-06-29 01:10:27 +000012281 if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12282 return ExprError();
12283 }
Richard Smith5179eb72016-06-28 19:03:57 +000012284
Richard Smithc83bf822016-06-10 00:58:19 +000012285 return BuildCXXConstructExpr(
12286 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12287 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12288 RequiresZeroInit, ConstructKind, ParenRange);
12289}
12290
12291/// BuildCXXConstructExpr - Creates a complete call to a constructor,
12292/// including handling of its default argument expressions.
12293ExprResult
12294Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12295 CXXConstructorDecl *Constructor,
12296 bool Elidable,
12297 MultiExprArg ExprArgs,
12298 bool HadMultipleCandidates,
12299 bool IsListInitialization,
12300 bool IsStdInitListInitialization,
12301 bool RequiresZeroInit,
12302 unsigned ConstructKind,
12303 SourceRange ParenRange) {
Richard Smith5179eb72016-06-28 19:03:57 +000012304 assert(declaresSameEntity(
12305 Constructor->getParent(),
12306 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12307 "given constructor for wrong type");
Eli Friedmanfa0df832012-02-02 03:46:19 +000012308 MarkFunctionReferenced(ConstructLoc, Constructor);
Justin Lebar18e2d822016-08-15 23:00:49 +000012309 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
12310 return ExprError();
Richard Smith5179eb72016-06-28 19:03:57 +000012311
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012312 return CXXConstructExpr::Create(
Richard Smithc83bf822016-06-10 00:58:19 +000012313 Context, DeclInitType, ConstructLoc, Constructor, Elidable,
Richard Smithc2bebe92016-05-11 20:37:46 +000012314 ExprArgs, HadMultipleCandidates, IsListInitialization,
12315 IsStdInitListInitialization, RequiresZeroInit,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012316 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12317 ParenRange);
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +000012318}
12319
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012320ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12321 assert(Field->hasInClassInitializer());
12322
12323 // If we already have the in-class initializer nothing needs to be done.
12324 if (Field->getInClassInitializer())
12325 return CXXDefaultInitExpr::Create(Context, Loc, Field);
12326
12327 // Maybe we haven't instantiated the in-class initializer. Go check the
12328 // pattern FieldDecl to see if it has one.
12329 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12330
12331 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12332 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12333 DeclContext::lookup_result Lookup =
12334 ClassPattern->lookup(Field->getDeclName());
Reid Kleckner327b0642016-04-29 18:06:53 +000012335
12336 // Lookup can return at most two results: the pattern for the field, or the
12337 // injected class name of the parent record. No other member can have the
12338 // same name as the field.
Vassil Vassileve53a4b72016-10-26 10:24:29 +000012339 // In modules mode, lookup can return multiple results (coming from
12340 // different modules).
12341 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
Reid Kleckner327b0642016-04-29 18:06:53 +000012342 "more than two lookup results for field name");
12343 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
12344 if (!Pattern) {
12345 assert(isa<CXXRecordDecl>(Lookup[0]) &&
12346 "cannot have other non-field member with same name");
Vassil Vassileve53a4b72016-10-26 10:24:29 +000012347 for (auto L : Lookup)
12348 if (isa<FieldDecl>(L)) {
12349 Pattern = cast<FieldDecl>(L);
12350 break;
12351 }
12352 assert(Pattern && "We must have set the Pattern!");
Reid Kleckner327b0642016-04-29 18:06:53 +000012353 }
12354
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012355 if (InstantiateInClassInitializer(Loc, Field, Pattern,
12356 getTemplateInstantiationArgs(Field)))
12357 return ExprError();
12358 return CXXDefaultInitExpr::Create(Context, Loc, Field);
12359 }
12360
12361 // DR1351:
12362 // If the brace-or-equal-initializer of a non-static data member
12363 // invokes a defaulted default constructor of its class or of an
12364 // enclosing class in a potentially evaluated subexpression, the
12365 // program is ill-formed.
12366 //
12367 // This resolution is unworkable: the exception specification of the
12368 // default constructor can be needed in an unevaluated context, in
12369 // particular, in the operand of a noexcept-expression, and we can be
12370 // unable to compute an exception specification for an enclosed class.
12371 //
12372 // Any attempt to resolve the exception specification of a defaulted default
12373 // constructor before the initializer is lexically complete will ultimately
12374 // come here at which point we can diagnose it.
12375 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
Richard Smith8dbc6b22016-11-22 22:55:12 +000012376 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
12377 << OutermostClass << Field;
12378 Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
Reid Klecknerd60b82f2014-11-17 23:36:45 +000012379
12380 return ExprError();
12381}
12382
John McCall03c48482010-02-02 09:10:11 +000012383void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +000012384 if (VD->isInvalidDecl()) return;
12385
John McCall03c48482010-02-02 09:10:11 +000012386 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +000012387 if (ClassDecl->isInvalidDecl()) return;
Richard Smitheec915d62012-02-18 04:13:32 +000012388 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000012389 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +000012390
Chandler Carruth86d17d32011-03-27 21:26:48 +000012391 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +000012392 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +000012393 CheckDestructorAccess(VD->getLocation(), Destructor,
12394 PDiag(diag::err_access_dtor_var)
12395 << VD->getDeclName()
12396 << VD->getType());
Richard Smitheec915d62012-02-18 04:13:32 +000012397 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson98766db2011-03-24 01:01:41 +000012398
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000012399 if (Destructor->isTrivial()) return;
Chandler Carruth86d17d32011-03-27 21:26:48 +000012400 if (!VD->hasGlobalStorage()) return;
12401
12402 // Emit warning for non-trivial dtor in global scope (a real global,
12403 // class-static, function-static).
12404 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
12405
12406 // TODO: this should be re-enabled for static locals by !CXAAtExit
Stephan Tolksdorf5604a272014-03-27 20:23:36 +000012407 if (!VD->isStaticLocal())
Chandler Carruth86d17d32011-03-27 21:26:48 +000012408 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000012409}
12410
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012411/// \brief Given a constructor and the set of arguments provided for the
12412/// constructor, convert the arguments and add any required default arguments
12413/// to form a proper call to this constructor.
12414///
12415/// \returns true if an error occurred, false otherwise.
12416bool
12417Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
12418 MultiExprArg ArgsPtr,
Richard Smith55ce3522012-06-25 20:30:08 +000012419 SourceLocation Loc,
Benjamin Kramerf0623432012-08-23 22:51:59 +000012420 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smith6b216962013-02-05 05:52:24 +000012421 bool AllowExplicit,
12422 bool IsListInitialization) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012423 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
12424 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +000012425 Expr **Args = ArgsPtr.data();
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012426
12427 const FunctionProtoType *Proto
12428 = Constructor->getType()->getAs<FunctionProtoType>();
12429 assert(Proto && "Constructor without a prototype?");
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012430 unsigned NumParams = Proto->getNumParams();
Alp Toker9cacbab2014-01-20 20:26:09 +000012431
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012432 // If too few arguments are available, we'll fill in the rest with defaults.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012433 if (NumArgs < NumParams)
12434 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012435 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +000012436 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012437
12438 VariadicCallType CallType =
12439 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012440 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012441 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012442 Proto, 0,
12443 llvm::makeArrayRef(Args, NumArgs),
12444 AllArgs,
Richard Smith6b216962013-02-05 05:52:24 +000012445 CallType, AllowExplicit,
12446 IsListInitialization);
Benjamin Kramer8001f742012-02-14 12:06:21 +000012447 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmanff4b4072012-02-18 04:48:30 +000012448
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012449 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012450
Dmitri Gribenko765396f2013-01-13 20:46:02 +000012451 CheckConstructorCall(Constructor,
Craig Topper8c2a2a02014-08-30 16:55:39 +000012452 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
Richard Smith55ce3522012-06-25 20:30:08 +000012453 Proto, Loc);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012454
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +000012455 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +000012456}
12457
Anders Carlssone363c8e2009-12-12 00:32:00 +000012458static inline bool
12459CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
12460 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +000012461 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +000012462 if (isa<NamespaceDecl>(DC)) {
12463 return SemaRef.Diag(FnDecl->getLocation(),
12464 diag::err_operator_new_delete_declared_in_namespace)
12465 << FnDecl->getDeclName();
12466 }
12467
12468 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +000012469 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000012470 return SemaRef.Diag(FnDecl->getLocation(),
12471 diag::err_operator_new_delete_declared_static)
12472 << FnDecl->getDeclName();
12473 }
12474
Anders Carlsson60659a82009-12-12 02:43:16 +000012475 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +000012476}
12477
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012478static inline bool
12479CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
12480 CanQualType ExpectedResultType,
12481 CanQualType ExpectedFirstParamType,
12482 unsigned DependentParamTypeDiag,
12483 unsigned InvalidParamTypeDiag) {
Alp Toker314cc812014-01-25 16:55:45 +000012484 QualType ResultType =
12485 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012486
12487 // Check that the result type is not dependent.
12488 if (ResultType->isDependentType())
12489 return SemaRef.Diag(FnDecl->getLocation(),
12490 diag::err_operator_new_delete_dependent_result_type)
12491 << FnDecl->getDeclName() << ExpectedResultType;
12492
12493 // Check that the result type is what we expect.
12494 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
12495 return SemaRef.Diag(FnDecl->getLocation(),
12496 diag::err_operator_new_delete_invalid_result_type)
12497 << FnDecl->getDeclName() << ExpectedResultType;
12498
12499 // A function template must have at least 2 parameters.
12500 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
12501 return SemaRef.Diag(FnDecl->getLocation(),
12502 diag::err_operator_new_delete_template_too_few_parameters)
12503 << FnDecl->getDeclName();
12504
12505 // The function decl must have at least 1 parameter.
12506 if (FnDecl->getNumParams() == 0)
12507 return SemaRef.Diag(FnDecl->getLocation(),
12508 diag::err_operator_new_delete_too_few_parameters)
12509 << FnDecl->getDeclName();
12510
Sylvestre Ledru830885c2012-07-23 08:59:39 +000012511 // Check the first parameter type is not dependent.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012512 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
12513 if (FirstParamType->isDependentType())
12514 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
12515 << FnDecl->getDeclName() << ExpectedFirstParamType;
12516
12517 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +000012518 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012519 ExpectedFirstParamType)
12520 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
12521 << FnDecl->getDeclName() << ExpectedFirstParamType;
12522
12523 return false;
12524}
12525
Anders Carlsson12308f42009-12-11 23:23:22 +000012526static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012527CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +000012528 // C++ [basic.stc.dynamic.allocation]p1:
12529 // A program is ill-formed if an allocation function is declared in a
12530 // namespace scope other than global scope or declared static in global
12531 // scope.
12532 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12533 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012534
12535 CanQualType SizeTy =
12536 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
12537
12538 // C++ [basic.stc.dynamic.allocation]p1:
12539 // The return type shall be void*. The first parameter shall have type
12540 // std::size_t.
12541 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
12542 SizeTy,
12543 diag::err_operator_new_dependent_param_type,
12544 diag::err_operator_new_param_type))
12545 return true;
12546
12547 // C++ [basic.stc.dynamic.allocation]p1:
12548 // The first parameter shall not have an associated default argument.
12549 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +000012550 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012551 diag::err_operator_new_default_arg)
12552 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
12553
12554 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +000012555}
12556
12557static bool
Richard Smith66f3ac92012-10-20 08:26:51 +000012558CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson12308f42009-12-11 23:23:22 +000012559 // C++ [basic.stc.dynamic.deallocation]p1:
12560 // A program is ill-formed if deallocation functions are declared in a
12561 // namespace scope other than global scope or declared static in global
12562 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +000012563 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12564 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000012565
12566 // C++ [basic.stc.dynamic.deallocation]p2:
12567 // Each deallocation function shall return void and its first parameter
12568 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +000012569 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
12570 SemaRef.Context.VoidPtrTy,
12571 diag::err_operator_delete_dependent_param_type,
12572 diag::err_operator_delete_param_type))
12573 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +000012574
Anders Carlsson12308f42009-12-11 23:23:22 +000012575 return false;
12576}
12577
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012578/// CheckOverloadedOperatorDeclaration - Check whether the declaration
12579/// of this overloaded operator is well-formed. If so, returns false;
12580/// otherwise, emits appropriate diagnostics and returns true.
12581bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +000012582 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012583 "Expected an overloaded operator declaration");
12584
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012585 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
12586
Mike Stump11289f42009-09-09 15:08:12 +000012587 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012588 // The allocation and deallocation functions, operator new,
12589 // operator new[], operator delete and operator delete[], are
12590 // described completely in 3.7.3. The attributes and restrictions
12591 // found in the rest of this subclause do not apply to them unless
12592 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +000012593 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +000012594 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +000012595
Anders Carlsson22f443f2009-12-12 00:26:23 +000012596 if (Op == OO_New || Op == OO_Array_New)
12597 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012598
12599 // C++ [over.oper]p6:
12600 // An operator function shall either be a non-static member
12601 // function or be a non-member function and have at least one
12602 // parameter whose type is a class, a reference to a class, an
12603 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +000012604 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
12605 if (MethodDecl->isStatic())
12606 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012607 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012608 } else {
12609 bool ClassOrEnumParam = false;
David Majnemer59f77922016-06-24 04:05:48 +000012610 for (auto Param : FnDecl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012611 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +000012612 if (ParamType->isDependentType() || ParamType->isRecordType() ||
12613 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012614 ClassOrEnumParam = true;
12615 break;
12616 }
12617 }
12618
Douglas Gregord69246b2008-11-17 16:14:12 +000012619 if (!ClassOrEnumParam)
12620 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000012621 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012622 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012623 }
12624
12625 // C++ [over.oper]p8:
12626 // An operator function cannot have default arguments (8.3.6),
12627 // except where explicitly stated below.
12628 //
Mike Stump11289f42009-09-09 15:08:12 +000012629 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012630 // (C++ [over.call]p1).
12631 if (Op != OO_Call) {
David Majnemer59f77922016-06-24 04:05:48 +000012632 for (auto Param : FnDecl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012633 if (Param->hasDefaultArg())
12634 return Diag(Param->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +000012635 diag::err_operator_overload_default_arg)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012636 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012637 }
12638 }
12639
Douglas Gregor6cf08062008-11-10 13:38:07 +000012640 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
12641 { false, false, false }
12642#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
12643 , { Unary, Binary, MemberOnly }
12644#include "clang/Basic/OperatorKinds.def"
12645 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012646
Douglas Gregor6cf08062008-11-10 13:38:07 +000012647 bool CanBeUnaryOperator = OperatorUses[Op][0];
12648 bool CanBeBinaryOperator = OperatorUses[Op][1];
12649 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012650
12651 // C++ [over.oper]p8:
12652 // [...] Operator functions cannot have more or fewer parameters
12653 // than the number required for the corresponding operator, as
12654 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +000012655 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +000012656 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012657 if (Op != OO_Call &&
12658 ((NumParams == 1 && !CanBeUnaryOperator) ||
12659 (NumParams == 2 && !CanBeBinaryOperator) ||
12660 (NumParams < 1) || (NumParams > 2))) {
12661 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012662 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +000012663 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012664 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +000012665 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012666 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +000012667 } else {
Chris Lattner2b786902008-11-21 07:50:02 +000012668 assert(CanBeBinaryOperator &&
12669 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012670 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +000012671 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012672
Chris Lattnerc5bab9f2008-11-21 07:57:12 +000012673 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012674 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012675 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +000012676
Douglas Gregord69246b2008-11-17 16:14:12 +000012677 // Overloaded operators other than operator() cannot be variadic.
12678 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +000012679 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +000012680 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012681 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012682 }
12683
12684 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +000012685 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
12686 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +000012687 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +000012688 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012689 }
12690
12691 // C++ [over.inc]p1:
12692 // The user-defined function called operator++ implements the
12693 // prefix and postfix ++ operator. If this function is a member
12694 // function with no parameters, or a non-member function with one
12695 // parameter of class or enumeration type, it defines the prefix
12696 // increment operator ++ for objects of that type. If the function
12697 // is a member function with one parameter (which shall be of type
12698 // int) or a non-member function with two parameters (the second
12699 // of which shall be of type int), it defines the postfix
12700 // increment operator ++ for objects of that type.
12701 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
12702 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Richard Smith538b52a2014-01-30 22:24:05 +000012703 QualType ParamType = LastParam->getType();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012704
Richard Smith538b52a2014-01-30 22:24:05 +000012705 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
12706 !ParamType->isDependentType())
Chris Lattner2b786902008-11-21 07:50:02 +000012707 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +000012708 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +000012709 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012710 }
12711
Douglas Gregord69246b2008-11-17 16:14:12 +000012712 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +000012713}
Chris Lattner3b024a32008-12-17 07:09:26 +000012714
Richard Smithc28aee62016-02-17 00:04:04 +000012715static bool
12716checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
12717 FunctionTemplateDecl *TpDecl) {
12718 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
12719
12720 // Must have one or two template parameters.
12721 if (TemplateParams->size() == 1) {
12722 NonTypeTemplateParmDecl *PmDecl =
12723 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
12724
12725 // The template parameter must be a char parameter pack.
12726 if (PmDecl && PmDecl->isTemplateParameterPack() &&
12727 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
12728 return false;
12729
12730 } else if (TemplateParams->size() == 2) {
12731 TemplateTypeParmDecl *PmType =
12732 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
12733 NonTypeTemplateParmDecl *PmArgs =
12734 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
12735
12736 // The second template parameter must be a parameter pack with the
12737 // first template parameter as its type.
12738 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
12739 PmArgs->isTemplateParameterPack()) {
12740 const TemplateTypeParmType *TArgs =
12741 PmArgs->getType()->getAs<TemplateTypeParmType>();
12742 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
12743 TArgs->getIndex() == PmType->getIndex()) {
12744 if (SemaRef.ActiveTemplateInstantiations.empty())
12745 SemaRef.Diag(TpDecl->getLocation(),
12746 diag::ext_string_literal_operator_template);
12747 return false;
12748 }
12749 }
12750 }
12751
12752 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
12753 diag::err_literal_operator_template)
12754 << TpDecl->getTemplateParameters()->getSourceRange();
12755 return true;
12756}
12757
Alexis Huntc88db062010-01-13 09:01:02 +000012758/// CheckLiteralOperatorDeclaration - Check whether the declaration
12759/// of this literal operator function is well-formed. If so, returns
12760/// false; otherwise, emits appropriate diagnostics and returns true.
12761bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smith5731c752012-03-10 22:18:57 +000012762 if (isa<CXXMethodDecl>(FnDecl)) {
Alexis Huntc88db062010-01-13 09:01:02 +000012763 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
12764 << FnDecl->getDeclName();
12765 return true;
12766 }
12767
Richard Smith72eebee2012-03-04 09:41:16 +000012768 if (FnDecl->isExternC()) {
12769 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
Alex Lorenz560ae562016-11-02 15:46:34 +000012770 if (const LinkageSpecDecl *LSD =
12771 FnDecl->getDeclContext()->getExternCContext())
12772 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
Richard Smith72eebee2012-03-04 09:41:16 +000012773 return true;
12774 }
12775
Richard Smithbcc22fc2012-03-09 08:00:36 +000012776 // This might be the definition of a literal operator template.
12777 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
Richard Smithc28aee62016-02-17 00:04:04 +000012778
Richard Smithbcc22fc2012-03-09 08:00:36 +000012779 // This might be a specialization of a literal operator template.
12780 if (!TpDecl)
12781 TpDecl = FnDecl->getPrimaryTemplate();
12782
Richard Smithb8b41d32013-10-07 19:57:58 +000012783 // template <char...> type operator "" name() and
12784 // template <class T, T...> type operator "" name() are the only valid
12785 // template signatures, and the only valid signatures with no parameters.
Richard Smithbcc22fc2012-03-09 08:00:36 +000012786 if (TpDecl) {
Richard Smithc28aee62016-02-17 00:04:04 +000012787 if (FnDecl->param_size() != 0) {
12788 Diag(FnDecl->getLocation(),
12789 diag::err_literal_operator_template_with_params);
12790 return true;
Alexis Hunt7dd26172010-04-07 23:11:06 +000012791 }
Richard Smithc28aee62016-02-17 00:04:04 +000012792
12793 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
12794 return true;
12795
12796 } else if (FnDecl->param_size() == 1) {
12797 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
12798
12799 QualType ParamType = Param->getType().getUnqualifiedType();
12800
12801 // Only unsigned long long int, long double, any character type, and const
12802 // char * are allowed as the only parameters.
12803 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
12804 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
12805 Context.hasSameType(ParamType, Context.CharTy) ||
12806 Context.hasSameType(ParamType, Context.WideCharTy) ||
12807 Context.hasSameType(ParamType, Context.Char16Ty) ||
12808 Context.hasSameType(ParamType, Context.Char32Ty)) {
12809 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
12810 QualType InnerType = Ptr->getPointeeType();
12811
12812 // Pointer parameter must be a const char *.
12813 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
12814 Context.CharTy) &&
12815 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
12816 Diag(Param->getSourceRange().getBegin(),
12817 diag::err_literal_operator_param)
12818 << ParamType << "'const char *'" << Param->getSourceRange();
12819 return true;
12820 }
12821
12822 } else if (ParamType->isRealFloatingType()) {
12823 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12824 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
12825 return true;
12826
12827 } else if (ParamType->isIntegerType()) {
12828 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12829 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
12830 return true;
12831
12832 } else {
12833 Diag(Param->getSourceRange().getBegin(),
12834 diag::err_literal_operator_invalid_param)
12835 << ParamType << Param->getSourceRange();
12836 return true;
12837 }
12838
12839 } else if (FnDecl->param_size() == 2) {
Alexis Hunt7dd26172010-04-07 23:11:06 +000012840 FunctionDecl::param_iterator Param = FnDecl->param_begin();
12841
Richard Smithc28aee62016-02-17 00:04:04 +000012842 // First, verify that the first parameter is correct.
Alexis Huntc88db062010-01-13 09:01:02 +000012843
Richard Smithc28aee62016-02-17 00:04:04 +000012844 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
12845
12846 // Two parameter function must have a pointer to const as a
12847 // first parameter; let's strip those qualifiers.
12848 const PointerType *PT = FirstParamType->getAs<PointerType>();
12849
12850 if (!PT) {
12851 Diag((*Param)->getSourceRange().getBegin(),
12852 diag::err_literal_operator_param)
12853 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12854 return true;
Alexis Huntc88db062010-01-13 09:01:02 +000012855 }
12856
Richard Smithc28aee62016-02-17 00:04:04 +000012857 QualType PointeeType = PT->getPointeeType();
12858 // First parameter must be const
12859 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
12860 Diag((*Param)->getSourceRange().getBegin(),
12861 diag::err_literal_operator_param)
12862 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12863 return true;
12864 }
Alexis Huntc88db062010-01-13 09:01:02 +000012865
Richard Smithc28aee62016-02-17 00:04:04 +000012866 QualType InnerType = PointeeType.getUnqualifiedType();
12867 // Only const char *, const wchar_t*, const char16_t*, and const char32_t*
12868 // are allowed as the first parameter to a two-parameter function
12869 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
12870 Context.hasSameType(InnerType, Context.WideCharTy) ||
12871 Context.hasSameType(InnerType, Context.Char16Ty) ||
12872 Context.hasSameType(InnerType, Context.Char32Ty))) {
12873 Diag((*Param)->getSourceRange().getBegin(),
12874 diag::err_literal_operator_param)
12875 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12876 return true;
12877 }
12878
12879 // Move on to the second and final parameter.
Alexis Huntc88db062010-01-13 09:01:02 +000012880 ++Param;
12881
Richard Smithc28aee62016-02-17 00:04:04 +000012882 // The second parameter must be a std::size_t.
12883 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
12884 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
12885 Diag((*Param)->getSourceRange().getBegin(),
12886 diag::err_literal_operator_param)
12887 << SecondParamType << Context.getSizeType()
12888 << (*Param)->getSourceRange();
12889 return true;
Alexis Huntc88db062010-01-13 09:01:02 +000012890 }
Richard Smithc28aee62016-02-17 00:04:04 +000012891 } else {
12892 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
Alexis Huntc88db062010-01-13 09:01:02 +000012893 return true;
12894 }
12895
Richard Smithc28aee62016-02-17 00:04:04 +000012896 // Parameters are good.
12897
Richard Smith768cecc2012-03-09 08:16:22 +000012898 // A parameter-declaration-clause containing a default argument is not
12899 // equivalent to any of the permitted forms.
David Majnemer59f77922016-06-24 04:05:48 +000012900 for (auto Param : FnDecl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012901 if (Param->hasDefaultArg()) {
12902 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smith768cecc2012-03-09 08:16:22 +000012903 diag::err_literal_operator_default_argument)
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +000012904 << Param->getDefaultArgRange();
Richard Smith768cecc2012-03-09 08:16:22 +000012905 break;
12906 }
12907 }
12908
Richard Smith0df56f42012-03-08 02:39:21 +000012909 StringRef LiteralName
Douglas Gregor86325ad2011-08-30 22:40:35 +000012910 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
12911 if (LiteralName[0] != '_') {
Richard Smith0df56f42012-03-08 02:39:21 +000012912 // C++11 [usrlit.suffix]p1:
12913 // Literal suffix identifiers that do not start with an underscore
12914 // are reserved for future standardization.
Richard Smithf4198b72013-07-23 08:14:48 +000012915 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
12916 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor86325ad2011-08-30 22:40:35 +000012917 }
Richard Smith0df56f42012-03-08 02:39:21 +000012918
Alexis Huntc88db062010-01-13 09:01:02 +000012919 return false;
12920}
12921
Douglas Gregor07665a62009-01-05 19:45:36 +000012922/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
12923/// linkage specification, including the language and (if present)
Richard Smith4ee696d2014-02-17 23:25:27 +000012924/// the '{'. ExternLoc is the location of the 'extern', Lang is the
12925/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor07665a62009-01-05 19:45:36 +000012926/// the '{' brace. Otherwise, this linkage specification does not
12927/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +000012928Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Richard Smith4ee696d2014-02-17 23:25:27 +000012929 Expr *LangStr,
Chris Lattner8ea64422010-11-09 20:15:55 +000012930 SourceLocation LBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000012931 StringLiteral *Lit = cast<StringLiteral>(LangStr);
12932 if (!Lit->isAscii()) {
12933 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
12934 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000012935 return nullptr;
Richard Smith4ee696d2014-02-17 23:25:27 +000012936 }
12937
12938 StringRef Lang = Lit->getString();
Chris Lattner438e5012008-12-17 07:13:27 +000012939 LinkageSpecDecl::LanguageIDs Language;
Richard Smith4ee696d2014-02-17 23:25:27 +000012940 if (Lang == "C")
Chris Lattner438e5012008-12-17 07:13:27 +000012941 Language = LinkageSpecDecl::lang_c;
Richard Smith4ee696d2014-02-17 23:25:27 +000012942 else if (Lang == "C++")
Chris Lattner438e5012008-12-17 07:13:27 +000012943 Language = LinkageSpecDecl::lang_cxx;
12944 else {
Richard Smith4ee696d2014-02-17 23:25:27 +000012945 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
12946 << LangStr->getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000012947 return nullptr;
Chris Lattner438e5012008-12-17 07:13:27 +000012948 }
Mike Stump11289f42009-09-09 15:08:12 +000012949
Chris Lattner438e5012008-12-17 07:13:27 +000012950 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +000012951
Richard Smith4ee696d2014-02-17 23:25:27 +000012952 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
12953 LangStr->getExprLoc(), Language,
Rafael Espindola327be3c2013-04-26 01:30:23 +000012954 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000012955 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +000012956 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +000012957 return D;
Chris Lattner438e5012008-12-17 07:13:27 +000012958}
12959
Abramo Bagnaraed5b6892010-07-30 16:47:02 +000012960/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +000012961/// the C++ linkage specification LinkageSpec. If RBraceLoc is
12962/// valid, it's the position of the closing '}' brace in a linkage
12963/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +000012964Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000012965 Decl *LinkageSpec,
12966 SourceLocation RBraceLoc) {
Richard Smith4ee696d2014-02-17 23:25:27 +000012967 if (RBraceLoc.isValid()) {
12968 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
12969 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara4a8cda82011-03-03 14:52:38 +000012970 }
Richard Smith4ee696d2014-02-17 23:25:27 +000012971 PopDeclContext();
Douglas Gregor07665a62009-01-05 19:45:36 +000012972 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +000012973}
12974
Michael Han84324352013-02-22 17:15:32 +000012975Decl *Sema::ActOnEmptyDeclaration(Scope *S,
12976 AttributeList *AttrList,
12977 SourceLocation SemiLoc) {
12978 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
12979 // Attribute declarations appertain to empty declaration so we handle
12980 // them here.
12981 if (AttrList)
12982 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith54ecd982013-02-20 19:22:51 +000012983
Michael Han84324352013-02-22 17:15:32 +000012984 CurContext->addDecl(ED);
12985 return ED;
Richard Smith54ecd982013-02-20 19:22:51 +000012986}
12987
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000012988/// \brief Perform semantic analysis for the variable declaration that
12989/// occurs within a C++ catch clause, returning the newly-created
12990/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +000012991VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +000012992 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +000012993 SourceLocation StartLoc,
12994 SourceLocation Loc,
12995 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000012996 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000012997 QualType ExDeclType = TInfo->getType();
12998
Sebastian Redl54c04d42008-12-22 19:15:10 +000012999 // Arrays and functions decay.
13000 if (ExDeclType->isArrayType())
13001 ExDeclType = Context.getArrayDecayedType(ExDeclType);
13002 else if (ExDeclType->isFunctionType())
13003 ExDeclType = Context.getPointerType(ExDeclType);
13004
13005 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13006 // The exception-declaration shall not denote a pointer or reference to an
13007 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +000013008 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +000013009 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000013010 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +000013011 Invalid = true;
13012 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013013
David Majnemere56d1a02016-06-08 16:05:07 +000013014 if (ExDeclType->isVariablyModifiedType()) {
13015 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13016 Invalid = true;
13017 }
13018
Sebastian Redl54c04d42008-12-22 19:15:10 +000013019 QualType BaseType = ExDeclType;
13020 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +000013021 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +000013022 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000013023 BaseType = Ptr->getPointeeType();
13024 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000013025 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +000013026 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +000013027 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +000013028 BaseType = Ref->getPointeeType();
13029 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000013030 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +000013031 }
Sebastian Redlb28b4072009-03-22 23:49:27 +000013032 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +000013033 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +000013034 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000013035
Mike Stump11289f42009-09-09 15:08:12 +000013036 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013037 RequireNonAbstractType(Loc, ExDeclType,
13038 diag::err_abstract_type_in_decl,
13039 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +000013040 Invalid = true;
13041
John McCall2ca705e2010-07-24 00:37:23 +000013042 // Only the non-fragile NeXT runtime currently supports C++ catches
13043 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikiebbafb8a2012-03-11 07:00:24 +000013044 if (!Invalid && getLangOpts().ObjC1) {
John McCall2ca705e2010-07-24 00:37:23 +000013045 QualType T = ExDeclType;
13046 if (const ReferenceType *RT = T->getAs<ReferenceType>())
13047 T = RT->getPointeeType();
13048
13049 if (T->isObjCObjectType()) {
13050 Diag(Loc, diag::err_objc_object_catch);
13051 Invalid = true;
13052 } else if (T->isObjCObjectPointerType()) {
John McCall5fb5df92012-06-20 06:18:46 +000013053 // FIXME: should this be a test for macosx-fragile specifically?
13054 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +000013055 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +000013056 }
13057 }
13058
Abramo Bagnaradff19302011-03-08 08:55:46 +000013059 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +000013060 ExDeclType, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +000013061 ExDecl->setExceptionVariable(true);
13062
Douglas Gregor8ca0c642011-12-10 01:22:52 +000013063 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +000013064 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor8ca0c642011-12-10 01:22:52 +000013065 Invalid = true;
13066
Douglas Gregor750734c2011-07-06 18:14:43 +000013067 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +000013068 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCalleaef89b2013-03-22 02:10:40 +000013069 // Insulate this from anything else we might currently be parsing.
13070 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
13071
Douglas Gregor6de584c2010-03-05 23:38:39 +000013072 // C++ [except.handle]p16:
Nick Lewycky0f292892013-09-22 10:06:57 +000013073 // The object declared in an exception-declaration or, if the
13074 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6de584c2010-03-05 23:38:39 +000013075 // copy-initialized (8.5) from the exception object. [...]
13076 // The object is destroyed when the handler exits, after the destruction
13077 // of any automatic objects initialized within the handler.
13078 //
Nick Lewycky0f292892013-09-22 10:06:57 +000013079 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6de584c2010-03-05 23:38:39 +000013080 // it can be destroyed later.
David Majnemerfba75df2015-03-03 04:38:34 +000013081 QualType initType = Context.getExceptionObjectType(ExDeclType);
John McCall1bf58462011-02-16 08:02:54 +000013082
13083 InitializedEntity entity =
13084 InitializedEntity::InitializeVariable(ExDecl);
13085 InitializationKind initKind =
13086 InitializationKind::CreateCopy(Loc, SourceLocation());
13087
13088 Expr *opaqueValue =
13089 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +000013090 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13091 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCall1bf58462011-02-16 08:02:54 +000013092 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +000013093 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +000013094 else {
13095 // If the constructor used was non-trivial, set this as the
13096 // "initializer".
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013097 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
John McCall1bf58462011-02-16 08:02:54 +000013098 if (!construct->getConstructor()->isTrivial()) {
13099 Expr *init = MaybeCreateExprWithCleanups(construct);
13100 ExDecl->setInit(init);
13101 }
13102
13103 // And make sure it's destructable.
13104 FinalizeVarWithDestructor(ExDecl, recordType);
13105 }
Douglas Gregor6de584c2010-03-05 23:38:39 +000013106 }
13107 }
13108
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013109 if (Invalid)
13110 ExDecl->setInvalidDecl();
13111
13112 return ExDecl;
13113}
13114
13115/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13116/// handler.
John McCall48871652010-08-21 09:40:31 +000013117Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +000013118 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +000013119 bool Invalid = D.isInvalidType();
13120
13121 // Check for unexpanded parameter packs.
Jordan Rosed03d99d2013-03-05 01:27:54 +000013122 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13123 UPPC_ExceptionType)) {
Douglas Gregor72772f62010-12-16 17:48:04 +000013124 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13125 D.getIdentifierLoc());
13126 Invalid = true;
13127 }
13128
Sebastian Redl54c04d42008-12-22 19:15:10 +000013129 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +000013130 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +000013131 LookupOrdinaryName,
13132 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000013133 // The scope should be freshly made just for us. There is just no way
Aaron Ballman9ef622e2014-06-02 13:10:07 +000013134 // it contains any previous declaration, except for function parameters in
13135 // a function-try-block's catch statement.
John McCall48871652010-08-21 09:40:31 +000013136 assert(!S->isDeclScope(PrevDecl));
Aaron Ballman9ef622e2014-06-02 13:10:07 +000013137 if (isDeclInScope(PrevDecl, CurContext, S)) {
13138 Diag(D.getIdentifierLoc(), diag::err_redefinition)
13139 << D.getIdentifier();
13140 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13141 Invalid = true;
13142 } else if (PrevDecl->isTemplateParameter())
Sebastian Redl54c04d42008-12-22 19:15:10 +000013143 // Maybe we will complain about the shadowed template parameter.
13144 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000013145 }
13146
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000013147 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +000013148 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13149 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000013150 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +000013151 }
13152
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +000013153 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013154 D.getLocStart(),
Abramo Bagnaradff19302011-03-08 08:55:46 +000013155 D.getIdentifierLoc(),
13156 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +000013157 if (Invalid)
13158 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +000013159
Sebastian Redl54c04d42008-12-22 19:15:10 +000013160 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +000013161 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +000013162 PushOnScopeChains(ExDecl, S);
13163 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000013164 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +000013165
Douglas Gregor758a8692009-06-17 21:51:59 +000013166 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +000013167 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +000013168}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000013169
Abramo Bagnaraea947882011-03-08 16:41:52 +000013170Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +000013171 Expr *AssertExpr,
Richard Smithded9c2e2012-07-11 22:37:56 +000013172 Expr *AssertMessageExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +000013173 SourceLocation RParenLoc) {
Richard Smith085a64f2014-06-20 19:57:12 +000013174 StringLiteral *AssertMessage =
13175 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000013176
Richard Smithded9c2e2012-07-11 22:37:56 +000013177 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
Craig Topperc3ec1492014-05-26 06:22:03 +000013178 return nullptr;
Richard Smithded9c2e2012-07-11 22:37:56 +000013179
13180 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13181 AssertMessage, RParenLoc, false);
13182}
13183
13184Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13185 Expr *AssertExpr,
13186 StringLiteral *AssertMessage,
13187 SourceLocation RParenLoc,
13188 bool Failed) {
Richard Smith085a64f2014-06-20 19:57:12 +000013189 assert(AssertExpr != nullptr && "Expected non-null condition");
Richard Smithded9c2e2012-07-11 22:37:56 +000013190 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13191 !Failed) {
Richard Smithf4c51d92012-02-04 09:53:13 +000013192 // In a static_assert-declaration, the constant-expression shall be a
13193 // constant expression that can be contextually converted to bool.
13194 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13195 if (Converted.isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000013196 Failed = true;
Richard Smithf4c51d92012-02-04 09:53:13 +000013197
Richard Smith902ca212011-12-14 23:32:26 +000013198 llvm::APSInt Cond;
Richard Smithded9c2e2012-07-11 22:37:56 +000013199 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregore2b37442012-05-04 22:38:52 +000013200 diag::err_static_assert_expression_is_not_constant,
Richard Smithf4c51d92012-02-04 09:53:13 +000013201 /*AllowFold=*/false).isInvalid())
Richard Smithded9c2e2012-07-11 22:37:56 +000013202 Failed = true;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000013203
Richard Smithded9c2e2012-07-11 22:37:56 +000013204 if (!Failed && !Cond) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +000013205 SmallString<256> MsgBuffer;
Richard Smithf506eaf2012-03-05 23:20:05 +000013206 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smith085a64f2014-06-20 19:57:12 +000013207 if (AssertMessage)
13208 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
Abramo Bagnaraea947882011-03-08 16:41:52 +000013209 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith085a64f2014-06-20 19:57:12 +000013210 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
Richard Smithded9c2e2012-07-11 22:37:56 +000013211 Failed = true;
Richard Smithf506eaf2012-03-05 23:20:05 +000013212 }
Anders Carlsson54b26982009-03-14 00:33:21 +000013213 }
Mike Stump11289f42009-09-09 15:08:12 +000013214
Abramo Bagnaraea947882011-03-08 16:41:52 +000013215 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithded9c2e2012-07-11 22:37:56 +000013216 AssertExpr, AssertMessage, RParenLoc,
13217 Failed);
Mike Stump11289f42009-09-09 15:08:12 +000013218
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000013219 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +000013220 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +000013221}
Sebastian Redlf769df52009-03-24 22:27:57 +000013222
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013223/// \brief Perform semantic analysis of the given friend type declaration.
13224///
13225/// \returns A friend declaration that.
Richard Smitha31a89a2012-09-20 01:31:00 +000013226FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara254b6302011-10-29 20:52:52 +000013227 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013228 TypeSourceInfo *TSInfo) {
13229 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
13230
13231 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +000013232 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013233
Richard Smithc8239732011-10-18 21:39:00 +000013234 // C++03 [class.friend]p2:
13235 // An elaborated-type-specifier shall be used in a friend declaration
13236 // for a class.*
13237 //
13238 // * The class-key of the elaborated-type-specifier is required.
13239 if (!ActiveTemplateInstantiations.empty()) {
13240 // Do not complain about the form of friend template types during
13241 // template instantiation; we will already have complained when the
13242 // template was declared.
Nick Lewycky36722d22013-02-06 05:59:33 +000013243 } else {
13244 if (!T->isElaboratedTypeSpecifier()) {
13245 // If we evaluated the type to a record type, suggest putting
13246 // a tag in front.
13247 if (const RecordType *RT = T->getAs<RecordType>()) {
13248 RecordDecl *RD = RT->getDecl();
Alp Tokera030cd02014-05-05 12:38:48 +000013249
13250 SmallString<16> InsertionText(" ");
13251 InsertionText += RD->getKindName();
13252
Nick Lewycky36722d22013-02-06 05:59:33 +000013253 Diag(TypeRange.getBegin(),
13254 getLangOpts().CPlusPlus11 ?
13255 diag::warn_cxx98_compat_unelaborated_friend_type :
13256 diag::ext_unelaborated_friend_type)
13257 << (unsigned) RD->getTagKind()
13258 << T
Craig Topper07fa1762015-11-15 02:31:46 +000013259 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
Nick Lewycky36722d22013-02-06 05:59:33 +000013260 InsertionText);
13261 } else {
13262 Diag(FriendLoc,
13263 getLangOpts().CPlusPlus11 ?
13264 diag::warn_cxx98_compat_nonclass_type_friend :
13265 diag::ext_nonclass_type_friend)
13266 << T
13267 << TypeRange;
13268 }
13269 } else if (T->getAs<EnumType>()) {
Richard Smithc8239732011-10-18 21:39:00 +000013270 Diag(FriendLoc,
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013271 getLangOpts().CPlusPlus11 ?
Nick Lewycky36722d22013-02-06 05:59:33 +000013272 diag::warn_cxx98_compat_enum_friend :
13273 diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013274 << T
Richard Smitha31a89a2012-09-20 01:31:00 +000013275 << TypeRange;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013276 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013277
Nick Lewycky36722d22013-02-06 05:59:33 +000013278 // C++11 [class.friend]p3:
13279 // A friend declaration that does not declare a function shall have one
13280 // of the following forms:
13281 // friend elaborated-type-specifier ;
13282 // friend simple-type-specifier ;
13283 // friend typename-specifier ;
13284 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
13285 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
13286 }
Richard Smitha31a89a2012-09-20 01:31:00 +000013287
Douglas Gregor3b4abb62010-04-07 17:57:12 +000013288 // If the type specifier in a friend declaration designates a (possibly
Richard Smitha31a89a2012-09-20 01:31:00 +000013289 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor3b4abb62010-04-07 17:57:12 +000013290 // the friend declaration is ignored.
Nikola Smiljanic3a01af02014-05-23 12:48:27 +000013291 return FriendDecl::Create(Context, CurContext,
13292 TSInfo->getTypeLoc().getLocStart(), TSInfo,
13293 FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013294}
13295
John McCallace48cd2010-10-19 01:40:49 +000013296/// Handle a friend tag declaration where the scope specifier was
13297/// templated.
13298Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
13299 unsigned TagSpec, SourceLocation TagLoc,
13300 CXXScopeSpec &SS,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000013301 IdentifierInfo *Name,
13302 SourceLocation NameLoc,
John McCallace48cd2010-10-19 01:40:49 +000013303 AttributeList *Attr,
13304 MultiTemplateParamsArg TempParamLists) {
13305 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13306
13307 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000013308 bool Invalid = false;
13309
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000013310 if (TemplateParameterList *TemplateParams =
13311 MatchTemplateParametersToScopeSpecifier(
Craig Topperc3ec1492014-05-26 06:22:03 +000013312 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
Robert Wilhelmf2d2e8f2013-07-21 15:20:44 +000013313 isExplicitSpecialization, Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000013314 if (TemplateParams->size() > 0) {
13315 // This is a declaration of a class template.
13316 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +000013317 return nullptr;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000013318
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000013319 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
13320 NameLoc, Attr, TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000013321 /*ModulePrivateLoc=*/SourceLocation(),
Nikola Smiljanic4fc91532014-07-17 01:59:34 +000013322 FriendLoc, TempParamLists.size() - 1,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013323 TempParamLists.data()).get();
John McCallace48cd2010-10-19 01:40:49 +000013324 } else {
13325 // The "template<>" header is extraneous.
13326 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13327 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13328 isExplicitSpecialization = true;
13329 }
13330 }
13331
Craig Topperc3ec1492014-05-26 06:22:03 +000013332 if (Invalid) return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000013333
John McCallace48cd2010-10-19 01:40:49 +000013334 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000013335 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +000013336 if (TempParamLists[I]->size()) {
John McCallace48cd2010-10-19 01:40:49 +000013337 isAllExplicitSpecializations = false;
13338 break;
13339 }
13340 }
13341
13342 // FIXME: don't ignore attributes.
13343
13344 // If it's explicit specializations all the way down, just forget
13345 // about the template header and build an appropriate non-templated
13346 // friend. TODO: for source fidelity, remember the headers.
13347 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013348 if (SS.isEmpty()) {
13349 bool Owned = false;
13350 bool IsDependent = false;
13351 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Richard Smith649c7b062014-01-08 00:56:48 +000013352 Attr, AS_public,
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013353 /*ModulePrivateLoc=*/SourceLocation(),
Richard Smith649c7b062014-01-08 00:56:48 +000013354 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000013355 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013356 /*ScopedEnumUsesClassTag=*/false,
Richard Smith649c7b062014-01-08 00:56:48 +000013357 /*UnderlyingType=*/TypeResult(),
13358 /*IsTypeSpecifier=*/false);
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013359 }
Richard Smith649c7b062014-01-08 00:56:48 +000013360
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000013361 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000013362 ElaboratedTypeKeyword Keyword
13363 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000013364 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000013365 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000013366 if (T.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +000013367 return nullptr;
John McCallace48cd2010-10-19 01:40:49 +000013368
13369 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13370 if (isa<DependentNameType>(T)) {
David Blaikie6adc78e2013-02-18 22:06:02 +000013371 DependentNameTypeLoc TL =
13372 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000013373 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000013374 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000013375 TL.setNameLoc(NameLoc);
13376 } else {
David Blaikie6adc78e2013-02-18 22:06:02 +000013377 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000013378 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000013379 TL.setQualifierLoc(QualifierLoc);
David Blaikie6adc78e2013-02-18 22:06:02 +000013380 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000013381 }
13382
13383 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000013384 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000013385 Friend->setAccess(AS_public);
13386 CurContext->addDecl(Friend);
13387 return Friend;
13388 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000013389
13390 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
13391
13392
John McCallace48cd2010-10-19 01:40:49 +000013393
13394 // Handle the case of a templated-scope friend class. e.g.
13395 // template <class T> class A<T>::B;
13396 // FIXME: we don't support these right now.
Richard Smithcd556eb2013-11-08 18:59:56 +000013397 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
13398 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCallace48cd2010-10-19 01:40:49 +000013399 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13400 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
13401 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie6adc78e2013-02-18 22:06:02 +000013402 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000013403 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000013404 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000013405 TL.setNameLoc(NameLoc);
13406
13407 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanellaeb22c872013-01-31 09:54:08 +000013408 TSI, FriendLoc, TempParamLists);
John McCallace48cd2010-10-19 01:40:49 +000013409 Friend->setAccess(AS_public);
13410 Friend->setUnsupportedFriend(true);
13411 CurContext->addDecl(Friend);
13412 return Friend;
13413}
13414
13415
John McCall11083da2009-09-16 22:47:08 +000013416/// Handle a friend type declaration. This works in tandem with
13417/// ActOnTag.
13418///
13419/// Notes on friend class templates:
13420///
13421/// We generally treat friend class declarations as if they were
13422/// declaring a class. So, for example, the elaborated type specifier
13423/// in a friend declaration is required to obey the restrictions of a
13424/// class-head (i.e. no typedefs in the scope chain), template
13425/// parameters are required to match up with simple template-ids, &c.
13426/// However, unlike when declaring a template specialization, it's
13427/// okay to refer to a template specialization without an empty
13428/// template parameter declaration, e.g.
13429/// friend class A<T>::B<unsigned>;
13430/// We permit this as a special case; if there are any template
13431/// parameters present at all, require proper matching, i.e.
James Dennettf14a6e52012-06-15 22:23:43 +000013432/// template <> template \<class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000013433Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000013434 MultiTemplateParamsArg TempParams) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013435 SourceLocation Loc = DS.getLocStart();
John McCall07e91c02009-08-06 02:15:43 +000013436
13437 assert(DS.isFriendSpecified());
13438 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13439
John McCall11083da2009-09-16 22:47:08 +000013440 // Try to convert the decl specifier to a type. This works for
13441 // friend templates because ActOnTag never produces a ClassTemplateDecl
13442 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000013443 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000013444 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
13445 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000013446 if (TheDeclarator.isInvalidType())
Craig Topperc3ec1492014-05-26 06:22:03 +000013447 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000013448
Douglas Gregor6c110f32010-12-16 01:14:37 +000013449 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000013450 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000013451
John McCall11083da2009-09-16 22:47:08 +000013452 // This is definitely an error in C++98. It's probably meant to
13453 // be forbidden in C++0x, too, but the specification is just
13454 // poorly written.
13455 //
13456 // The problem is with declarations like the following:
13457 // template <T> friend A<T>::foo;
13458 // where deciding whether a class C is a friend or not now hinges
13459 // on whether there exists an instantiation of A that causes
13460 // 'foo' to equal C. There are restrictions on class-heads
13461 // (which we declare (by fiat) elaborated friend declarations to
13462 // be) that makes this tractable.
13463 //
13464 // FIXME: handle "template <> friend class A<T>;", which
13465 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000013466 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000013467 Diag(Loc, diag::err_tagless_friend_type_template)
13468 << DS.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +000013469 return nullptr;
John McCall11083da2009-09-16 22:47:08 +000013470 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013471
John McCallaa74a0c2009-08-28 07:59:38 +000013472 // C++98 [class.friend]p1: A friend of a class is a function
13473 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000013474 // This is fixed in DR77, which just barely didn't make the C++03
13475 // deadline. It's also a very silly restriction that seriously
13476 // affects inner classes and which nobody else seems to implement;
13477 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000013478 //
13479 // But note that we could warn about it: it's always useless to
13480 // friend one of your own members (it's not, however, worthless to
13481 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000013482
John McCall11083da2009-09-16 22:47:08 +000013483 Decl *D;
David Majnemerdfecf1a2016-07-06 04:19:16 +000013484 if (!TempParams.empty())
John McCall11083da2009-09-16 22:47:08 +000013485 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
David Majnemerdfecf1a2016-07-06 04:19:16 +000013486 TempParams,
John McCall15ad0962010-03-25 18:04:51 +000013487 TSI,
John McCall11083da2009-09-16 22:47:08 +000013488 DS.getFriendSpecLoc());
13489 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000013490 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000013491
13492 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +000013493 return nullptr;
13494
John McCall11083da2009-09-16 22:47:08 +000013495 D->setAccess(AS_public);
13496 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000013497
John McCall48871652010-08-21 09:40:31 +000013498 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000013499}
13500
Rafael Espindola0a67e2f2013-01-08 20:44:06 +000013501NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
13502 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000013503 const DeclSpec &DS = D.getDeclSpec();
13504
13505 assert(DS.isFriendSpecified());
13506 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13507
13508 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000013509 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000013510
13511 // C++ [class.friend]p1
13512 // A friend of a class is a function or class....
13513 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000013514 // It *doesn't* see through dependent types, which is correct
13515 // according to [temp.arg.type]p3:
13516 // If a declaration acquires a function type through a
13517 // type dependent on a template-parameter and this causes
13518 // a declaration that does not use the syntactic form of a
13519 // function declarator to have a function type, the program
13520 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013521 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000013522 Diag(Loc, diag::err_unexpected_friend);
13523
13524 // It might be worthwhile to try to recover by creating an
13525 // appropriate declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000013526 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000013527 }
13528
13529 // C++ [namespace.memdef]p3
13530 // - If a friend declaration in a non-local class first declares a
13531 // class or function, the friend class or function is a member
13532 // of the innermost enclosing namespace.
13533 // - The name of the friend is not found by simple name lookup
13534 // until a matching declaration is provided in that namespace
13535 // scope (either before or after the class declaration granting
13536 // friendship).
13537 // - If a friend function is called, its name may be found by the
13538 // name lookup that considers functions from namespaces and
13539 // classes associated with the types of the function arguments.
13540 // - When looking for a prior declaration of a class or a function
13541 // declared as a friend, scopes outside the innermost enclosing
13542 // namespace scope are not considered.
13543
John McCallde3fd222010-10-12 23:13:28 +000013544 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000013545 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
13546 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000013547 assert(Name);
13548
Douglas Gregor6c110f32010-12-16 01:14:37 +000013549 // Check for unexpanded parameter packs.
13550 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
13551 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
13552 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
Craig Topperc3ec1492014-05-26 06:22:03 +000013553 return nullptr;
Douglas Gregor6c110f32010-12-16 01:14:37 +000013554
John McCall07e91c02009-08-06 02:15:43 +000013555 // The context we found the declaration in, or in which we should
13556 // create the declaration.
13557 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000013558 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000013559 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000013560 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000013561
Richard Smith114394f2013-08-09 04:35:01 +000013562 // There are five cases here.
13563 // - There's no scope specifier and we're in a local class. Only look
13564 // for functions declared in the immediately-enclosing block scope.
13565 // We recover from invalid scope qualifiers as if they just weren't there.
Craig Topperc3ec1492014-05-26 06:22:03 +000013566 FunctionDecl *FunctionContainingLocalClass = nullptr;
Richard Smith114394f2013-08-09 04:35:01 +000013567 if ((SS.isInvalid() || !SS.isSet()) &&
13568 (FunctionContainingLocalClass =
13569 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
13570 // C++11 [class.friend]p11:
John McCallf7cfb222010-10-13 05:45:15 +000013571 // If a friend declaration appears in a local class and the name
13572 // specified is an unqualified name, a prior declaration is
13573 // looked up without considering scopes that are outside the
13574 // innermost enclosing non-class scope. For a friend function
13575 // declaration, if there is no prior declaration, the program is
13576 // ill-formed.
Richard Smith114394f2013-08-09 04:35:01 +000013577
13578 // Find the innermost enclosing non-class scope. This is the block
13579 // scope containing the local class definition (or for a nested class,
13580 // the outer local class).
13581 DCScope = S->getFnParent();
13582
13583 // Look up the function name in the scope.
13584 Previous.clear(LookupLocalFriendName);
13585 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
13586
13587 if (!Previous.empty()) {
13588 // All possible previous declarations must have the same context:
13589 // either they were declared at block scope or they are members of
13590 // one of the enclosing local classes.
13591 DC = Previous.getRepresentativeDecl()->getDeclContext();
13592 } else {
13593 // This is ill-formed, but provide the context that we would have
13594 // declared the function in, if we were permitted to, for error recovery.
13595 DC = FunctionContainingLocalClass;
13596 }
Richard Smith541b38b2013-09-20 01:15:31 +000013597 adjustContextForLocalExternDecl(DC);
Richard Smith114394f2013-08-09 04:35:01 +000013598
13599 // C++ [class.friend]p6:
13600 // A function can be defined in a friend declaration of a class if and
13601 // only if the class is a non-local class (9.8), the function name is
13602 // unqualified, and the function has namespace scope.
13603 if (D.isFunctionDefinition()) {
13604 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
13605 }
13606
13607 // - There's no scope specifier, in which case we just go to the
13608 // appropriate scope and look for a function or function template
13609 // there as appropriate.
13610 } else if (SS.isInvalid() || !SS.isSet()) {
13611 // C++11 [namespace.memdef]p3:
13612 // If the name in a friend declaration is neither qualified nor
13613 // a template-id and the declaration is a function or an
13614 // elaborated-type-specifier, the lookup to determine whether
13615 // the entity has been previously declared shall not consider
13616 // any scopes outside the innermost enclosing namespace.
John McCallf4776592010-10-14 22:22:28 +000013617 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000013618
John McCallf7cfb222010-10-13 05:45:15 +000013619 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000013620 DC = CurContext;
John McCall07e91c02009-08-06 02:15:43 +000013621
Rafael Espindola3626b7e2013-04-25 20:12:36 +000013622 // Skip class contexts. If someone can cite chapter and verse
13623 // for this behavior, that would be nice --- it's what GCC and
13624 // EDG do, and it seems like a reasonable intent, but the spec
13625 // really only says that checks for unqualified existing
13626 // declarations should stop at the nearest enclosing namespace,
13627 // not that they should only consider the nearest enclosing
13628 // namespace.
13629 while (DC->isRecord())
13630 DC = DC->getParent();
13631
13632 DeclContext *LookupDC = DC;
13633 while (LookupDC->isTransparentContext())
13634 LookupDC = LookupDC->getParent();
13635
13636 while (true) {
13637 LookupQualifiedName(Previous, LookupDC);
John McCall07e91c02009-08-06 02:15:43 +000013638
Rafael Espindola3626b7e2013-04-25 20:12:36 +000013639 if (!Previous.empty()) {
13640 DC = LookupDC;
13641 break;
John McCallf4776592010-10-14 22:22:28 +000013642 }
Rafael Espindola3626b7e2013-04-25 20:12:36 +000013643
13644 if (isTemplateId) {
13645 if (isa<TranslationUnitDecl>(LookupDC)) break;
13646 } else {
13647 if (LookupDC->isFileContext()) break;
13648 }
13649 LookupDC = LookupDC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000013650 }
13651
John McCallccbc0322010-10-13 06:22:15 +000013652 DCScope = getScopeForDeclContext(S, DC);
Richard Smith114394f2013-08-09 04:35:01 +000013653
John McCallde3fd222010-10-12 23:13:28 +000013654 // - There's a non-dependent scope specifier, in which case we
13655 // compute it and do a previous lookup there for a function
13656 // or function template.
13657 } else if (!SS.getScopeRep()->isDependent()) {
13658 DC = computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +000013659 if (!DC) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000013660
Craig Topperc3ec1492014-05-26 06:22:03 +000013661 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000013662
13663 LookupQualifiedName(Previous, DC);
13664
13665 // Ignore things found implicitly in the wrong scope.
13666 // TODO: better diagnostics for this case. Suggesting the right
13667 // qualified scope would be nice...
13668 LookupResult::Filter F = Previous.makeFilter();
13669 while (F.hasNext()) {
13670 NamedDecl *D = F.next();
13671 if (!DC->InEnclosingNamespaceSetOf(
13672 D->getDeclContext()->getRedeclContext()))
13673 F.erase();
13674 }
13675 F.done();
13676
13677 if (Previous.empty()) {
13678 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013679 Diag(Loc, diag::err_qualified_friend_not_found)
13680 << Name << TInfo->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +000013681 return nullptr;
John McCallde3fd222010-10-12 23:13:28 +000013682 }
13683
13684 // C++ [class.friend]p1: A friend of a class is a function or
13685 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000013686 if (DC->Equals(CurContext))
13687 Diag(DS.getFriendSpecLoc(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +000013688 getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +000013689 diag::warn_cxx98_compat_friend_is_member :
13690 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000013691
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013692 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000013693 // C++ [class.friend]p6:
13694 // A function can be defined in a friend declaration of a class if and
13695 // only if the class is a non-local class (9.8), the function name is
13696 // unqualified, and the function has namespace scope.
13697 SemaDiagnosticBuilder DB
13698 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
13699
13700 DB << SS.getScopeRep();
13701 if (DC->isFileContext())
13702 DB << FixItHint::CreateRemoval(SS.getRange());
13703 SS.clear();
13704 }
John McCallde3fd222010-10-12 23:13:28 +000013705
13706 // - There's a scope specifier that does not match any template
13707 // parameter lists, in which case we use some arbitrary context,
13708 // create a method or method template, and wait for instantiation.
13709 // - There's a scope specifier that does match some template
13710 // parameter lists, which we don't handle right now.
13711 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013712 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000013713 // C++ [class.friend]p6:
13714 // A function can be defined in a friend declaration of a class if and
13715 // only if the class is a non-local class (9.8), the function name is
13716 // unqualified, and the function has namespace scope.
13717 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
13718 << SS.getScopeRep();
13719 }
13720
John McCallde3fd222010-10-12 23:13:28 +000013721 DC = CurContext;
13722 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000013723 }
David Majnemere14d5302015-09-30 22:07:43 +000013724
John McCallf7cfb222010-10-13 05:45:15 +000013725 if (!DC->isRecord()) {
David Majnemere14d5302015-09-30 22:07:43 +000013726 int DiagArg = -1;
13727 switch (D.getName().getKind()) {
13728 case UnqualifiedId::IK_ConstructorTemplateId:
13729 case UnqualifiedId::IK_ConstructorName:
13730 DiagArg = 0;
13731 break;
13732 case UnqualifiedId::IK_DestructorName:
13733 DiagArg = 1;
13734 break;
13735 case UnqualifiedId::IK_ConversionFunctionId:
13736 DiagArg = 2;
13737 break;
13738 case UnqualifiedId::IK_Identifier:
13739 case UnqualifiedId::IK_ImplicitSelfParam:
13740 case UnqualifiedId::IK_LiteralOperatorId:
13741 case UnqualifiedId::IK_OperatorFunctionId:
13742 case UnqualifiedId::IK_TemplateId:
13743 break;
David Majnemere14d5302015-09-30 22:07:43 +000013744 }
John McCall07e91c02009-08-06 02:15:43 +000013745 // This implies that it has to be an operator or function.
David Majnemere14d5302015-09-30 22:07:43 +000013746 if (DiagArg >= 0) {
13747 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
Craig Topperc3ec1492014-05-26 06:22:03 +000013748 return nullptr;
John McCall07e91c02009-08-06 02:15:43 +000013749 }
John McCall07e91c02009-08-06 02:15:43 +000013750 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013751
Douglas Gregordd847ba2011-11-03 16:37:14 +000013752 // FIXME: This is an egregious hack to cope with cases where the scope stack
13753 // does not contain the declaration context, i.e., in an out-of-line
13754 // definition of a class.
13755 Scope FakeDCScope(S, Scope::DeclScope, Diags);
13756 if (!DCScope) {
13757 FakeDCScope.setEntity(DC);
13758 DCScope = &FakeDCScope;
13759 }
Richard Smith114394f2013-08-09 04:35:01 +000013760
Francois Pichet00c7e6c2011-08-14 03:52:19 +000013761 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000013762 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer62b95d82012-08-23 21:35:17 +000013763 TemplateParams, AddToScope);
Craig Topperc3ec1492014-05-26 06:22:03 +000013764 if (!ND) return nullptr;
John McCall759e32b2009-08-31 22:39:49 +000013765
Douglas Gregora29a3ff2009-09-28 00:08:27 +000013766 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000013767
Richard Smith114394f2013-08-09 04:35:01 +000013768 // If we performed typo correction, we might have added a scope specifier
13769 // and changed the decl context.
13770 DC = ND->getDeclContext();
13771
John McCall759e32b2009-08-31 22:39:49 +000013772 // Add the function declaration to the appropriate lookup tables,
13773 // adjusting the redeclarations list as necessary. We don't
13774 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000013775 //
John McCall759e32b2009-08-31 22:39:49 +000013776 // Also update the scope-based lookup if the target context's
13777 // lookup context is in lexical scope.
13778 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000013779 DC = DC->getRedeclContext();
Richard Smith05afe5e2012-03-13 03:12:56 +000013780 DC->makeDeclVisibleInContext(ND);
John McCall759e32b2009-08-31 22:39:49 +000013781 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000013782 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000013783 }
John McCallaa74a0c2009-08-28 07:59:38 +000013784
13785 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000013786 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000013787 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000013788 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000013789 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000013790
John McCalla0a96892012-08-10 03:15:35 +000013791 if (ND->isInvalidDecl()) {
John McCallde3fd222010-10-12 23:13:28 +000013792 FrD->setInvalidDecl();
John McCalla0a96892012-08-10 03:15:35 +000013793 } else {
13794 if (DC->isRecord()) CheckFriendAccess(ND);
13795
John McCall2c2eb122010-10-16 06:59:13 +000013796 FunctionDecl *FD;
13797 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
13798 FD = FTD->getTemplatedDecl();
13799 else
13800 FD = cast<FunctionDecl>(ND);
13801
David Majnemer502b0ed2013-06-25 23:09:30 +000013802 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
13803 // default argument expression, that declaration shall be a definition
13804 // and shall be the only declaration of the function or function
13805 // template in the translation unit.
13806 if (functionDeclHasDefaultArgument(FD)) {
Serge Pavlov06b7a872016-10-04 10:11:43 +000013807 // We can't look at FD->getPreviousDecl() because it may not have been set
Richard Smithfdf08882016-10-21 03:15:03 +000013808 // if we're in a dependent context. If the function is known to be a
13809 // redeclaration, we will have narrowed Previous down to the right decl.
13810 if (D.isRedeclaration()) {
David Majnemer502b0ed2013-06-25 23:09:30 +000013811 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
Serge Pavlov06b7a872016-10-04 10:11:43 +000013812 Diag(Previous.getRepresentativeDecl()->getLocation(),
13813 diag::note_previous_declaration);
David Majnemer502b0ed2013-06-25 23:09:30 +000013814 } else if (!D.isFunctionDefinition())
13815 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
13816 }
13817
John McCall2c2eb122010-10-16 06:59:13 +000013818 // Mark templated-scope function declarations as unsupported.
Richard Smith04b35e92014-09-29 05:57:29 +000013819 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
13820 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
13821 << SS.getScopeRep() << SS.getRange()
13822 << cast<CXXRecordDecl>(CurContext);
John McCall2c2eb122010-10-16 06:59:13 +000013823 FrD->setUnsupportedFriend(true);
Richard Smith04b35e92014-09-29 05:57:29 +000013824 }
John McCall2c2eb122010-10-16 06:59:13 +000013825 }
John McCallde3fd222010-10-12 23:13:28 +000013826
John McCall48871652010-08-21 09:40:31 +000013827 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000013828}
13829
John McCall48871652010-08-21 09:40:31 +000013830void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
13831 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000013832
Aaron Ballmanf96361e2013-01-16 23:39:10 +000013833 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redlf769df52009-03-24 22:27:57 +000013834 if (!Fn) {
13835 Diag(DelLoc, diag::err_deleted_non_function);
13836 return;
13837 }
Richard Smithb4d2a152013-04-02 19:38:47 +000013838
Douglas Gregorec9fd132012-01-14 16:38:05 +000013839 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikie36805522012-06-25 21:55:30 +000013840 // Don't consider the implicit declaration we generate for explicit
13841 // specializations. FIXME: Do not generate these implicit declarations.
Richard Smithbdd14642014-02-04 01:14:30 +000013842 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
13843 Prev->getPreviousDecl()) &&
13844 !Prev->isDefined()) {
David Blaikie36805522012-06-25 21:55:30 +000013845 Diag(DelLoc, diag::err_deleted_decl_not_first);
Richard Smithbdd14642014-02-04 01:14:30 +000013846 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
13847 Prev->isImplicit() ? diag::note_previous_implicit_declaration
13848 : diag::note_previous_declaration);
David Blaikie36805522012-06-25 21:55:30 +000013849 }
Sebastian Redlf769df52009-03-24 22:27:57 +000013850 // If the declaration wasn't the first, we delete the function anyway for
13851 // recovery.
Richard Smithb4d2a152013-04-02 19:38:47 +000013852 Fn = Fn->getCanonicalDecl();
Sebastian Redlf769df52009-03-24 22:27:57 +000013853 }
Richard Smithb4d2a152013-04-02 19:38:47 +000013854
Nico Rieck9de0a572014-05-29 16:51:19 +000013855 // dllimport/dllexport cannot be deleted.
13856 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
13857 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
13858 Fn->setInvalidDecl();
13859 }
13860
Richard Smithb4d2a152013-04-02 19:38:47 +000013861 if (Fn->isDeleted())
13862 return;
13863
13864 // See if we're deleting a function which is already known to override a
13865 // non-deleted virtual function.
Richard Smithf3cec652016-10-31 18:18:29 +000013866 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
Richard Smithb4d2a152013-04-02 19:38:47 +000013867 bool IssuedDiagnostic = false;
13868 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
13869 E = MD->end_overridden_methods();
13870 I != E; ++I) {
13871 if (!(*MD->begin_overridden_methods())->isDeleted()) {
13872 if (!IssuedDiagnostic) {
13873 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
13874 IssuedDiagnostic = true;
13875 }
13876 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
13877 }
13878 }
Richard Smithf3cec652016-10-31 18:18:29 +000013879 // If this function was implicitly deleted because it was defaulted,
13880 // explain why it was deleted.
13881 if (IssuedDiagnostic && MD->isDefaulted())
13882 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
13883 /*Diagnose*/true);
Richard Smithb4d2a152013-04-02 19:38:47 +000013884 }
13885
Richard Smithb63b6ee2014-01-22 01:43:19 +000013886 // C++11 [basic.start.main]p3:
13887 // A program that defines main as deleted [...] is ill-formed.
13888 if (Fn->isMain())
13889 Diag(DelLoc, diag::err_deleted_main);
13890
Eric Fiselier525a3512016-10-31 23:07:15 +000013891 // C++11 [dcl.fct.def.delete]p4:
13892 // A deleted function is implicitly inline.
13893 Fn->setImplicitlyInline();
Alexis Hunt4a8ea102011-05-06 20:44:56 +000013894 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000013895}
Sebastian Redl4c018662009-04-27 21:33:24 +000013896
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013897void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanf96361e2013-01-16 23:39:10 +000013898 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013899
13900 if (MD) {
Richard Trieu3d1235a2016-09-27 23:44:07 +000013901 if (MD->getParent()->isDependentType()) {
13902 MD->setDefaulted();
13903 MD->setExplicitlyDefaulted();
13904 return;
13905 }
13906
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013907 CXXSpecialMember Member = getSpecialMember(MD);
13908 if (Member == CXXInvalid) {
Eli Friedman84c0143e2013-07-11 23:55:07 +000013909 if (!MD->isInvalidDecl())
13910 Diag(DefaultLoc, diag::err_default_special_members);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013911 return;
13912 }
13913
13914 MD->setDefaulted();
13915 MD->setExplicitlyDefaulted();
13916
Alexis Hunt61ae8d32011-05-23 23:14:04 +000013917 // If this definition appears within the record, do the checking when
13918 // the record is complete.
13919 const FunctionDecl *Primary = MD;
Richard Smith802c4b72012-08-23 06:16:52 +000013920 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Vassil Vassilev8ffe3be2016-05-24 12:10:36 +000013921 // Ask the template instantiation pattern that actually had the
13922 // '= default' on it.
13923 Primary = Pattern;
Alexis Hunt61ae8d32011-05-23 23:14:04 +000013924
Richard Smith3901dfe2013-03-27 00:22:47 +000013925 // If the method was defaulted on its first declaration, we will have
13926 // already performed the checking in CheckCompletedCXXClass. Such a
13927 // declaration doesn't trigger an implicit definition.
Vassil Vassilev8ffe3be2016-05-24 12:10:36 +000013928 if (Primary->getCanonicalDecl()->isDefaulted())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013929 return;
13930
Richard Smithd3b5c9082012-07-27 04:22:15 +000013931 CheckExplicitlyDefaultedSpecialMember(MD);
13932
Dmitry Polukhin6194d9f2016-05-24 06:37:14 +000013933 if (!MD->isInvalidDecl())
13934 DefineImplicitSpecialMember(*this, MD, DefaultLoc);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000013935 } else {
13936 Diag(DefaultLoc, diag::err_default_special_members);
13937 }
13938}
13939
Sebastian Redl4c018662009-04-27 21:33:24 +000013940static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
Benjamin Kramer642f1732015-07-02 21:03:14 +000013941 for (Stmt *SubStmt : S->children()) {
Sebastian Redl4c018662009-04-27 21:33:24 +000013942 if (!SubStmt)
13943 continue;
13944 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar62ee6412012-03-09 18:35:03 +000013945 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl4c018662009-04-27 21:33:24 +000013946 diag::err_return_in_constructor_handler);
13947 if (!isa<Expr>(SubStmt))
13948 SearchForReturnInStmt(Self, SubStmt);
13949 }
13950}
13951
13952void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
13953 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
13954 CXXCatchStmt *Handler = TryBlock->getHandler(I);
13955 SearchForReturnInStmt(*this, Handler);
13956 }
13957}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000013958
David Blaikie68f71a32013-01-18 23:03:15 +000013959bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballman02df2e02012-12-09 17:45:41 +000013960 const CXXMethodDecl *Old) {
13961 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
13962 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
13963
13964 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
13965
13966 // If the calling conventions match, everything is fine
13967 if (NewCC == OldCC)
13968 return false;
13969
Hans Wennborg2545efe2013-12-11 17:42:11 +000013970 // If the calling conventions mismatch because the new function is static,
13971 // suppress the calling convention mismatch error; the error about static
13972 // function override (err_static_overrides_virtual from
13973 // Sema::CheckFunctionDeclaration) is more clear.
13974 if (New->getStorageClass() == SC_Static)
13975 return false;
13976
Reid Kleckner78af0702013-08-27 23:08:25 +000013977 Diag(New->getLocation(),
13978 diag::err_conflicting_overriding_cc_attributes)
13979 << New->getDeclName() << New->getType() << Old->getType();
13980 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
13981 return true;
Aaron Ballman02df2e02012-12-09 17:45:41 +000013982}
13983
Mike Stump11289f42009-09-09 15:08:12 +000013984bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000013985 const CXXMethodDecl *Old) {
Alp Toker314cc812014-01-25 16:55:45 +000013986 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
13987 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000013988
Chandler Carruth284bb2e2010-02-15 11:53:20 +000013989 if (Context.hasSameType(NewTy, OldTy) ||
13990 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000013991 return false;
Mike Stump11289f42009-09-09 15:08:12 +000013992
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013993 // Check if the return types are covariant
13994 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000013995
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013996 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000013997 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
13998 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000013999 NewClassTy = NewPT->getPointeeType();
14000 OldClassTy = OldPT->getPointeeType();
14001 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000014002 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14003 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14004 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14005 NewClassTy = NewRT->getPointeeType();
14006 OldClassTy = OldRT->getPointeeType();
14007 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014008 }
14009 }
Mike Stump11289f42009-09-09 15:08:12 +000014010
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014011 // The return types aren't either both pointers or references to a class type.
14012 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000014013 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014014 diag::err_different_return_type_for_overriding_virtual_function)
Alp Tokerd0787eb2014-07-02 01:47:15 +000014015 << New->getDeclName() << NewTy << OldTy
14016 << New->getReturnTypeSourceRange();
14017 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14018 << Old->getReturnTypeSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +000014019
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014020 return true;
14021 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000014022
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000014023 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
David Majnemerd3d91bd2016-01-26 01:37:01 +000014024 // C++14 [class.virtual]p8:
14025 // If the class type in the covariant return type of D::f differs from
14026 // that of B::f, the class type in the return type of D::f shall be
14027 // complete at the point of declaration of D::f or shall be the class
14028 // type D.
14029 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14030 if (!RT->isBeingDefined() &&
14031 RequireCompleteType(New->getLocation(), NewClassTy,
14032 diag::err_covariant_return_incomplete,
14033 New->getDeclName()))
14034 return true;
14035 }
14036
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014037 // Check if the new class derives from the old class.
Richard Smith0f59cb32015-12-18 21:45:41 +000014038 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
Alp Tokerd0787eb2014-07-02 01:47:15 +000014039 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14040 << New->getDeclName() << NewTy << OldTy
14041 << New->getReturnTypeSourceRange();
14042 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14043 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014044 return true;
14045 }
Mike Stump11289f42009-09-09 15:08:12 +000014046
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014047 // Check if we the conversion from derived to base is valid.
Alp Tokerd0787eb2014-07-02 01:47:15 +000014048 if (CheckDerivedToBaseConversion(
14049 NewClassTy, OldClassTy,
14050 diag::err_covariant_return_inaccessible_base,
14051 diag::err_covariant_return_ambiguous_derived_to_base_conv,
14052 New->getLocation(), New->getReturnTypeSourceRange(),
14053 New->getDeclName(), nullptr)) {
John McCallc1465822011-02-14 07:13:47 +000014054 // FIXME: this note won't trigger for delayed access control
14055 // diagnostics, and it's impossible to get an undelayed error
14056 // here from access control during the original parse because
14057 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Alp Tokerd0787eb2014-07-02 01:47:15 +000014058 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14059 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014060 return true;
14061 }
14062 }
Mike Stump11289f42009-09-09 15:08:12 +000014063
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014064 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000014065 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014066 Diag(New->getLocation(),
14067 diag::err_covariant_return_type_different_qualifications)
Alp Tokerd0787eb2014-07-02 01:47:15 +000014068 << New->getDeclName() << NewTy << OldTy
14069 << New->getReturnTypeSourceRange();
14070 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14071 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014072 return true;
David Majnemerfedb8d42016-01-26 01:39:17 +000014073 }
Mike Stump11289f42009-09-09 15:08:12 +000014074
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014075
14076 // The new class type must have the same or less qualifiers as the old type.
14077 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14078 Diag(New->getLocation(),
14079 diag::err_covariant_return_type_class_type_more_qualified)
Alp Tokerd0787eb2014-07-02 01:47:15 +000014080 << New->getDeclName() << NewTy << OldTy
14081 << New->getReturnTypeSourceRange();
14082 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14083 << Old->getReturnTypeSourceRange();
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014084 return true;
David Majnemerfedb8d42016-01-26 01:39:17 +000014085 }
Mike Stump11289f42009-09-09 15:08:12 +000014086
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000014087 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000014088}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014089
Douglas Gregor21920e372009-12-01 17:24:26 +000014090/// \brief Mark the given method pure.
14091///
14092/// \param Method the method to be marked pure.
14093///
14094/// \param InitRange the source range that covers the "0" initializer.
14095bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000014096 SourceLocation EndLoc = InitRange.getEnd();
14097 if (EndLoc.isValid())
14098 Method->setRangeEnd(EndLoc);
14099
Douglas Gregor21920e372009-12-01 17:24:26 +000014100 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14101 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000014102 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000014103 }
Douglas Gregor21920e372009-12-01 17:24:26 +000014104
14105 if (!Method->isInvalidDecl())
14106 Diag(Method->getLocation(), diag::err_non_virtual_pure)
14107 << Method->getDeclName() << InitRange;
14108 return true;
14109}
14110
Richard Smith9ba0fec2015-06-30 01:28:56 +000014111void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14112 if (D->getFriendObjectKind())
14113 Diag(D->getLocation(), diag::err_pure_friend);
14114 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14115 CheckPureMethod(M, ZeroLoc);
14116 else
14117 Diag(D->getLocation(), diag::err_illegal_initializer);
14118}
14119
Douglas Gregor926410d2012-02-21 02:22:07 +000014120/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014121static bool isStaticDataMember(const Decl *D) {
14122 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14123 return Var->isStaticDataMember();
14124
14125 return false;
Douglas Gregor926410d2012-02-21 02:22:07 +000014126}
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014127
John McCall1f4ee7b2009-12-19 09:28:58 +000014128/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
14129/// an initializer for the out-of-line declaration 'Dcl'. The scope
14130/// is a fresh scope pushed for just this purpose.
14131///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014132/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14133/// static data member of class X, names should be looked up in the scope of
14134/// class X.
John McCall48871652010-08-21 09:40:31 +000014135void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014136 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000014137 if (!D || D->isInvalidDecl())
14138 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014139
Richard Smitha2302242013-12-05 07:51:02 +000014140 // We will always have a nested name specifier here, but this declaration
14141 // might not be out of line if the specifier names the current namespace:
14142 // extern int n;
14143 // int ::n = 0;
14144 if (D->isOutOfLine())
14145 EnterDeclaratorContext(S, D->getDeclContext());
14146
Douglas Gregor926410d2012-02-21 02:22:07 +000014147 // If we are parsing the initializer for a static data member, push a
14148 // new expression evaluation context that is associated with this static
14149 // data member.
14150 if (isStaticDataMember(D))
14151 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014152}
14153
14154/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000014155/// initializer for the out-of-line declaration 'D'.
14156void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014157 // If there is no declaration, there was an error parsing it.
Craig Topperc3ec1492014-05-26 06:22:03 +000014158 if (!D || D->isInvalidDecl())
14159 return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014160
Douglas Gregor926410d2012-02-21 02:22:07 +000014161 if (isStaticDataMember(D))
Richard Smitha2302242013-12-05 07:51:02 +000014162 PopExpressionEvaluationContext();
Douglas Gregor926410d2012-02-21 02:22:07 +000014163
Richard Smitha2302242013-12-05 07:51:02 +000014164 if (D->isOutOfLine())
14165 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000014166}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014167
14168/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14169/// C++ if/switch/while/for statement.
14170/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000014171DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014172 // C++ 6.4p2:
14173 // The declarator shall not specify a function or an array.
14174 // The type-specifier-seq shall not contain typedef and shall not declare a
14175 // new class or enumeration.
14176 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14177 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000014178
14179 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000014180 if (!Dcl)
14181 return true;
14182
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000014183 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14184 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014185 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000014186 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014187 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014188
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000014189 return Dcl;
14190}
Anders Carlssonf98849e2009-12-02 17:15:43 +000014191
Douglas Gregor4daf6a32011-07-28 19:11:31 +000014192void Sema::LoadExternalVTableUses() {
14193 if (!ExternalSource)
14194 return;
14195
14196 SmallVector<ExternalVTableUse, 4> VTables;
14197 ExternalSource->ReadUsedVTables(VTables);
14198 SmallVector<VTableUse, 4> NewUses;
14199 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14200 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14201 = VTablesUsed.find(VTables[I].Record);
14202 // Even if a definition wasn't required before, it may be required now.
14203 if (Pos != VTablesUsed.end()) {
14204 if (!Pos->second && VTables[I].DefinitionRequired)
14205 Pos->second = true;
14206 continue;
14207 }
14208
14209 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14210 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14211 }
14212
14213 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14214}
14215
Douglas Gregor88d292c2010-05-13 16:44:06 +000014216void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
14217 bool DefinitionRequired) {
14218 // Ignore any vtable uses in unevaluated operands or for classes that do
14219 // not have a vtable.
14220 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallf413f5e2013-05-03 00:10:13 +000014221 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolae7113ca2010-03-10 02:19:29 +000014222 return;
14223
Douglas Gregor88d292c2010-05-13 16:44:06 +000014224 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000014225 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014226 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
14227 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
14228 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
14229 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000014230 // If we already had an entry, check to see if we are promoting this vtable
Nico Weberf1cebf02015-01-06 23:54:59 +000014231 // to require a definition. If so, we need to reappend to the VTableUses
Daniel Dunbar53217762010-05-25 00:33:13 +000014232 // list, since we may have already processed the first entry.
14233 if (DefinitionRequired && !Pos.first->second) {
14234 Pos.first->second = true;
14235 } else {
14236 // Otherwise, we can early exit.
14237 return;
14238 }
Hans Wennborg3d791542014-02-24 15:58:24 +000014239 } else {
14240 // The Microsoft ABI requires that we perform the destructor body
14241 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
14242 // the deleting destructor is emitted with the vtable, not with the
14243 // destructor definition as in the Itanium ABI.
Hans Wennborg34804352016-04-13 20:21:15 +000014244 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Reid Klecknerad1e22b2016-06-29 18:29:21 +000014245 CXXDestructorDecl *DD = Class->getDestructor();
14246 if (DD && DD->isVirtual() && !DD->isDeleted()) {
14247 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
14248 // If this is an out-of-line declaration, marking it referenced will
14249 // not do anything. Manually call CheckDestructor to look up operator
14250 // delete().
14251 ContextRAII SavedContext(*this, DD);
14252 CheckDestructor(DD);
14253 } else {
14254 MarkFunctionReferenced(Loc, Class->getDestructor());
14255 }
Hans Wennborg34804352016-04-13 20:21:15 +000014256 }
Hans Wennborg3d791542014-02-24 15:58:24 +000014257 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000014258 }
14259
14260 // Local classes need to have their virtual members marked
14261 // immediately. For all other classes, we mark their virtual members
14262 // at the end of the translation unit.
14263 if (Class->isLocalClass())
14264 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000014265 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000014266 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000014267}
14268
Douglas Gregor88d292c2010-05-13 16:44:06 +000014269bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000014270 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014271 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000014272 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000014273
Douglas Gregor88d292c2010-05-13 16:44:06 +000014274 // Note: The VTableUses vector could grow as a result of marking
14275 // the members of a class as "used", so we check the size each
Richard Smithd3b5c9082012-07-27 04:22:15 +000014276 // time through the loop and prefer indices (which are stable) to
Douglas Gregor88d292c2010-05-13 16:44:06 +000014277 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000014278 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014279 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000014280 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014281 if (!Class)
14282 continue;
Reid Klecknerb792e062016-12-06 21:44:41 +000014283 TemplateSpecializationKind ClassTSK =
14284 Class->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014285
14286 SourceLocation Loc = VTableUses[I].second;
14287
Richard Smithd3b5c9082012-07-27 04:22:15 +000014288 bool DefineVTable = true;
14289
Douglas Gregor88d292c2010-05-13 16:44:06 +000014290 // If this class has a key function, but that key function is
14291 // defined in another translation unit, we don't need to emit the
14292 // vtable even though we're using it.
John McCall6bd2a892013-01-25 22:31:03 +000014293 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000014294 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolaef7fe1f2013-08-26 23:23:21 +000014295 // The key function is in another translation unit.
14296 DefineVTable = false;
14297 TemplateSpecializationKind TSK =
14298 KeyFunction->getTemplateSpecializationKind();
14299 assert(TSK != TSK_ExplicitInstantiationDefinition &&
14300 TSK != TSK_ImplicitInstantiation &&
14301 "Instantiations don't have key functions");
14302 (void)TSK;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014303 } else if (!KeyFunction) {
14304 // If we have a class with no key function that is the subject
14305 // of an explicit instantiation declaration, suppress the
14306 // vtable; it will live with the explicit instantiation
14307 // definition.
Reid Klecknerb792e062016-12-06 21:44:41 +000014308 bool IsExplicitInstantiationDeclaration =
14309 ClassTSK == TSK_ExplicitInstantiationDeclaration;
Aaron Ballman86c93902014-03-06 23:45:36 +000014310 for (auto R : Class->redecls()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000014311 TemplateSpecializationKind TSK
Aaron Ballman86c93902014-03-06 23:45:36 +000014312 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor88d292c2010-05-13 16:44:06 +000014313 if (TSK == TSK_ExplicitInstantiationDeclaration)
14314 IsExplicitInstantiationDeclaration = true;
14315 else if (TSK == TSK_ExplicitInstantiationDefinition) {
14316 IsExplicitInstantiationDeclaration = false;
14317 break;
14318 }
14319 }
14320
14321 if (IsExplicitInstantiationDeclaration)
Richard Smithd3b5c9082012-07-27 04:22:15 +000014322 DefineVTable = false;
14323 }
14324
14325 // The exception specifications for all virtual members may be needed even
14326 // if we are not providing an authoritative form of the vtable in this TU.
14327 // We may choose to emit it available_externally anyway.
14328 if (!DefineVTable) {
14329 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
14330 continue;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014331 }
14332
14333 // Mark all of the virtual members of this class as referenced, so
14334 // that we can build a vtable. Then, tell the AST consumer that a
14335 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000014336 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000014337 MarkVirtualMembersReferenced(Loc, Class);
14338 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
Nico Weberb6a5d052015-01-15 04:07:35 +000014339 if (VTablesUsed[Canonical])
14340 Consumer.HandleVTable(Class);
Douglas Gregor88d292c2010-05-13 16:44:06 +000014341
Reid Klecknerb792e062016-12-06 21:44:41 +000014342 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
14343 // no key function or the key function is inlined. Don't warn in C++ ABIs
14344 // that lack key functions, since the user won't be able to make one.
14345 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
14346 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
Craig Topperc3ec1492014-05-26 06:22:03 +000014347 const FunctionDecl *KeyFunctionDef = nullptr;
Reid Klecknerb792e062016-12-06 21:44:41 +000014348 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
14349 KeyFunctionDef->isInlined())) {
14350 Diag(Class->getLocation(),
14351 ClassTSK == TSK_ExplicitInstantiationDefinition
14352 ? diag::warn_weak_template_vtable
14353 : diag::warn_weak_vtable)
14354 << Class;
14355 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000014356 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000014357 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000014358 VTableUses.clear();
14359
Douglas Gregor97509692011-04-22 22:25:37 +000014360 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000014361}
Anders Carlsson82fccd02009-12-07 08:24:59 +000014362
Richard Smithd3b5c9082012-07-27 04:22:15 +000014363void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
14364 const CXXRecordDecl *RD) {
Aaron Ballman2b124d12014-03-13 16:36:16 +000014365 for (const auto *I : RD->methods())
14366 if (I->isVirtual() && !I->isPure())
14367 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithd3b5c9082012-07-27 04:22:15 +000014368}
14369
Rafael Espindola5b334082010-03-26 00:36:59 +000014370void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
14371 const CXXRecordDecl *RD) {
Richard Smith4ff9ff92012-07-07 06:59:51 +000014372 // Mark all functions which will appear in RD's vtable as used.
14373 CXXFinalOverriderMap FinalOverriders;
14374 RD->getFinalOverriders(FinalOverriders);
14375 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
14376 E = FinalOverriders.end();
14377 I != E; ++I) {
14378 for (OverridingMethods::const_iterator OI = I->second.begin(),
14379 OE = I->second.end();
14380 OI != OE; ++OI) {
14381 assert(OI->second.size() > 0 && "no final overrider");
14382 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlsson82fccd02009-12-07 08:24:59 +000014383
Richard Smith4ff9ff92012-07-07 06:59:51 +000014384 // C++ [basic.def.odr]p2:
14385 // [...] A virtual member function is used if it is not pure. [...]
14386 if (!Overrider->isPure())
14387 MarkFunctionReferenced(Loc, Overrider);
14388 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000014389 }
Rafael Espindola5b334082010-03-26 00:36:59 +000014390
14391 // Only classes that have virtual bases need a VTT.
14392 if (RD->getNumVBases() == 0)
14393 return;
14394
Aaron Ballman574705e2014-03-13 15:41:46 +000014395 for (const auto &I : RD->bases()) {
Rafael Espindola5b334082010-03-26 00:36:59 +000014396 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +000014397 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000014398 if (Base->getNumVBases() == 0)
14399 continue;
14400 MarkVirtualMembersReferenced(Loc, Base);
14401 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000014402}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014403
14404/// SetIvarInitializers - This routine builds initialization ASTs for the
14405/// Objective-C implementation whose ivars need be initialized.
14406void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000014407 if (!getLangOpts().CPlusPlus)
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014408 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000014409 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000014410 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014411 CollectIvarsToConstructOrDestruct(OID, ivars);
14412 if (ivars.empty())
14413 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000014414 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014415 for (unsigned i = 0; i < ivars.size(); i++) {
14416 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000014417 if (Field->isInvalidDecl())
14418 continue;
14419
Alexis Hunt1d792652011-01-08 20:30:50 +000014420 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014421 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
14422 InitializationKind InitKind =
14423 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko78852e92013-05-05 20:40:26 +000014424
14425 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
14426 ExprResult MemberInit =
14427 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregora40433a2010-12-07 00:41:46 +000014428 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014429 // Note, MemberInit could actually come back empty if no initialization
14430 // is required (e.g., because it would call a trivial default constructor)
14431 if (!MemberInit.get() || MemberInit.isInvalid())
14432 continue;
John McCallacf0ee52010-10-08 02:01:28 +000014433
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014434 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000014435 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
14436 SourceLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014437 MemberInit.getAs<Expr>(),
Alexis Hunt1d792652011-01-08 20:30:50 +000014438 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014439 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000014440
14441 // Be sure that the destructor is accessible and is marked as referenced.
Nico Weberaa0117c2014-11-12 03:44:43 +000014442 if (const RecordType *RecordTy =
14443 Context.getBaseElementType(Field->getType())
14444 ->getAs<RecordType>()) {
14445 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000014446 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000014447 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000014448 CheckDestructorAccess(Field->getLocation(), Destructor,
14449 PDiag(diag::err_access_dtor_ivar)
14450 << Context.getBaseElementType(Field->getType()));
14451 }
14452 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000014453 }
14454 ObjCImplementation->setIvarInitializers(Context,
14455 AllToInit.data(), AllToInit.size());
14456 }
14457}
Alexis Hunt6118d662011-05-04 05:57:24 +000014458
Alexis Hunt27a761d2011-05-04 23:29:54 +000014459static
14460void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
14461 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
14462 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
14463 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
14464 Sema &S) {
Alexis Hunt27a761d2011-05-04 23:29:54 +000014465 if (Ctor->isInvalidDecl())
14466 return;
14467
Richard Smith802c4b72012-08-23 06:16:52 +000014468 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
14469
14470 // Target may not be determinable yet, for instance if this is a dependent
14471 // call in an uninstantiated template.
14472 if (Target) {
Craig Topperc3ec1492014-05-26 06:22:03 +000014473 const FunctionDecl *FNTarget = nullptr;
Richard Smith802c4b72012-08-23 06:16:52 +000014474 (void)Target->hasBody(FNTarget);
14475 Target = const_cast<CXXConstructorDecl*>(
14476 cast_or_null<CXXConstructorDecl>(FNTarget));
14477 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000014478
14479 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
14480 // Avoid dereferencing a null pointer here.
Craig Topperc3ec1492014-05-26 06:22:03 +000014481 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000014482
David Blaikie82e95a32014-11-19 07:49:47 +000014483 if (!Current.insert(Canonical).second)
Alexis Hunt27a761d2011-05-04 23:29:54 +000014484 return;
14485
14486 // We know that beyond here, we aren't chaining into a cycle.
14487 if (!Target || !Target->isDelegatingConstructor() ||
14488 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014489 Valid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000014490 Current.clear();
14491 // We've hit a cycle.
14492 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
14493 Current.count(TCanonical)) {
14494 // If we haven't diagnosed this cycle yet, do so now.
14495 if (!Invalid.count(TCanonical)) {
14496 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000014497 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000014498 << Ctor;
14499
Richard Smith802c4b72012-08-23 06:16:52 +000014500 // Don't add a note for a function delegating directly to itself.
Alexis Hunt27a761d2011-05-04 23:29:54 +000014501 if (TCanonical != Canonical)
14502 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
14503
14504 CXXConstructorDecl *C = Target;
14505 while (C->getCanonicalDecl() != Canonical) {
Craig Topperc3ec1492014-05-26 06:22:03 +000014506 const FunctionDecl *FNTarget = nullptr;
Alexis Hunt27a761d2011-05-04 23:29:54 +000014507 (void)C->getTargetConstructor()->hasBody(FNTarget);
14508 assert(FNTarget && "Ctor cycle through bodiless function");
14509
Richard Smith802c4b72012-08-23 06:16:52 +000014510 C = const_cast<CXXConstructorDecl*>(
14511 cast<CXXConstructorDecl>(FNTarget));
Alexis Hunt27a761d2011-05-04 23:29:54 +000014512 S.Diag(C->getLocation(), diag::note_which_delegates_to);
14513 }
14514 }
14515
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014516 Invalid.insert(Current.begin(), Current.end());
Alexis Hunt27a761d2011-05-04 23:29:54 +000014517 Current.clear();
14518 } else {
14519 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
14520 }
14521}
14522
14523
Alexis Hunt6118d662011-05-04 05:57:24 +000014524void Sema::CheckDelegatingCtorCycles() {
14525 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
14526
Douglas Gregorbae31202011-07-27 21:57:17 +000014527 for (DelegatingCtorDeclsType::iterator
14528 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000014529 E = DelegatingCtorDecls.end();
Richard Smith802c4b72012-08-23 06:16:52 +000014530 I != E; ++I)
14531 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt27a761d2011-05-04 23:29:54 +000014532
Benjamin Kramer8bf44352013-07-24 15:28:33 +000014533 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
14534 CE = Invalid.end();
14535 CI != CE; ++CI)
Alexis Hunt27a761d2011-05-04 23:29:54 +000014536 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000014537}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000014538
Douglas Gregor3024f072012-04-16 07:05:22 +000014539namespace {
14540 /// \brief AST visitor that finds references to the 'this' expression.
14541 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
14542 Sema &S;
14543
14544 public:
14545 explicit FindCXXThisExpr(Sema &S) : S(S) { }
14546
14547 bool VisitCXXThisExpr(CXXThisExpr *E) {
14548 S.Diag(E->getLocation(), diag::err_this_static_member_func)
14549 << E->isImplicit();
14550 return false;
14551 }
14552 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000014553}
Douglas Gregor3024f072012-04-16 07:05:22 +000014554
14555bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
14556 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14557 if (!TSInfo)
14558 return false;
14559
14560 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000014561 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor3024f072012-04-16 07:05:22 +000014562 if (!ProtoTL)
14563 return false;
14564
14565 // C++11 [expr.prim.general]p3:
14566 // [The expression this] shall not appear before the optional
14567 // cv-qualifier-seq and it shall not appear within the declaration of a
14568 // static member function (although its type and value category are defined
14569 // within a static member function as they are within a non-static member
14570 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumi40edb2a2012-04-21 09:40:04 +000014571 // until the complete declarator is known. - end note ]
David Blaikie6adc78e2013-02-18 22:06:02 +000014572 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor3024f072012-04-16 07:05:22 +000014573 FindCXXThisExpr Finder(*this);
14574
14575 // If the return type came after the cv-qualifier-seq, check it now.
14576 if (Proto->hasTrailingReturn() &&
Alp Toker42a16a62014-01-25 23:51:36 +000014577 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregor3024f072012-04-16 07:05:22 +000014578 return true;
14579
14580 // Check the exception specification.
Douglas Gregor433e0532012-04-16 18:27:27 +000014581 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
14582 return true;
14583
14584 return checkThisInStaticMemberFunctionAttributes(Method);
14585}
14586
14587bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
14588 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14589 if (!TSInfo)
14590 return false;
14591
14592 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +000014593 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor433e0532012-04-16 18:27:27 +000014594 if (!ProtoTL)
14595 return false;
14596
David Blaikie6adc78e2013-02-18 22:06:02 +000014597 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor433e0532012-04-16 18:27:27 +000014598 FindCXXThisExpr Finder(*this);
14599
Douglas Gregor3024f072012-04-16 07:05:22 +000014600 switch (Proto->getExceptionSpecType()) {
Richard Smith0b3a4622014-11-13 20:01:57 +000014601 case EST_Unparsed:
Richard Smithf623c962012-04-17 00:58:00 +000014602 case EST_Uninstantiated:
Richard Smithd3b5c9082012-07-27 04:22:15 +000014603 case EST_Unevaluated:
Douglas Gregor3024f072012-04-16 07:05:22 +000014604 case EST_BasicNoexcept:
Douglas Gregor3024f072012-04-16 07:05:22 +000014605 case EST_DynamicNone:
14606 case EST_MSAny:
14607 case EST_None:
14608 break;
Douglas Gregor433e0532012-04-16 18:27:27 +000014609
Douglas Gregor3024f072012-04-16 07:05:22 +000014610 case EST_ComputedNoexcept:
14611 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
14612 return true;
Douglas Gregor433e0532012-04-16 18:27:27 +000014613
Douglas Gregor3024f072012-04-16 07:05:22 +000014614 case EST_Dynamic:
Aaron Ballmanb088fbe2014-03-17 15:38:09 +000014615 for (const auto &E : Proto->exceptions()) {
14616 if (!Finder.TraverseType(E))
Douglas Gregor3024f072012-04-16 07:05:22 +000014617 return true;
14618 }
14619 break;
14620 }
Douglas Gregor433e0532012-04-16 18:27:27 +000014621
14622 return false;
Douglas Gregor3024f072012-04-16 07:05:22 +000014623}
14624
14625bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
14626 FindCXXThisExpr Finder(*this);
14627
14628 // Check attributes.
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014629 for (const auto *A : Method->attrs()) {
Douglas Gregor3024f072012-04-16 07:05:22 +000014630 // FIXME: This should be emitted by tblgen.
Craig Topperc3ec1492014-05-26 06:22:03 +000014631 Expr *Arg = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +000014632 ArrayRef<Expr *> Args;
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014633 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000014634 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014635 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000014636 Arg = G->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014637 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014638 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014639 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014640 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014641 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000014642 Arg = ETLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000014643 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014644 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregor3024f072012-04-16 07:05:22 +000014645 Arg = STLF->getSuccessValue();
Craig Topper5fc8fc22014-08-27 06:28:36 +000014646 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
Aaron Ballman18d85ae2014-03-20 16:02:49 +000014647 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregor3024f072012-04-16 07:05:22 +000014648 Arg = LR->getArg();
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014649 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014650 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014651 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014652 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014653 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014654 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014655 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014656 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Aaron Ballmanb97112e2014-03-08 22:19:01 +000014657 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Craig Topper5fc8fc22014-08-27 06:28:36 +000014658 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Douglas Gregor3024f072012-04-16 07:05:22 +000014659
14660 if (Arg && !Finder.TraverseStmt(Arg))
14661 return true;
14662
14663 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
14664 if (!Finder.TraverseStmt(Args[I]))
14665 return true;
14666 }
14667 }
14668
14669 return false;
14670}
14671
Richard Smith2e321552014-11-12 02:00:47 +000014672void Sema::checkExceptionSpecification(
14673 bool IsTopLevel, ExceptionSpecificationType EST,
14674 ArrayRef<ParsedType> DynamicExceptions,
14675 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
14676 SmallVectorImpl<QualType> &Exceptions,
14677 FunctionProtoType::ExceptionSpecInfo &ESI) {
Douglas Gregor433e0532012-04-16 18:27:27 +000014678 Exceptions.clear();
Richard Smith8acb4282014-07-31 21:57:55 +000014679 ESI.Type = EST;
Douglas Gregor433e0532012-04-16 18:27:27 +000014680 if (EST == EST_Dynamic) {
14681 Exceptions.reserve(DynamicExceptions.size());
14682 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
14683 // FIXME: Preserve type source info.
14684 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
14685
Richard Smith2e321552014-11-12 02:00:47 +000014686 if (IsTopLevel) {
14687 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
14688 collectUnexpandedParameterPacks(ET, Unexpanded);
14689 if (!Unexpanded.empty()) {
14690 DiagnoseUnexpandedParameterPacks(
14691 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
14692 Unexpanded);
14693 continue;
14694 }
Douglas Gregor433e0532012-04-16 18:27:27 +000014695 }
14696
14697 // Check that the type is valid for an exception spec, and
14698 // drop it if not.
14699 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
14700 Exceptions.push_back(ET);
14701 }
Richard Smith8acb4282014-07-31 21:57:55 +000014702 ESI.Exceptions = Exceptions;
Douglas Gregor433e0532012-04-16 18:27:27 +000014703 return;
14704 }
Richard Smith8acb4282014-07-31 21:57:55 +000014705
Douglas Gregor433e0532012-04-16 18:27:27 +000014706 if (EST == EST_ComputedNoexcept) {
14707 // If an error occurred, there's no expression here.
14708 if (NoexceptExpr) {
14709 assert((NoexceptExpr->isTypeDependent() ||
14710 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
14711 Context.BoolTy) &&
14712 "Parser should have made sure that the expression is boolean");
Richard Smith2e321552014-11-12 02:00:47 +000014713 if (IsTopLevel && NoexceptExpr &&
14714 DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
Richard Smith8acb4282014-07-31 21:57:55 +000014715 ESI.Type = EST_BasicNoexcept;
Douglas Gregor433e0532012-04-16 18:27:27 +000014716 return;
14717 }
Richard Smith8acb4282014-07-31 21:57:55 +000014718
Douglas Gregor433e0532012-04-16 18:27:27 +000014719 if (!NoexceptExpr->isValueDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +000014720 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
Douglas Gregore2b37442012-05-04 22:38:52 +000014721 diag::err_noexcept_needs_constant_expression,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014722 /*AllowFold*/ false).get();
Richard Smith8acb4282014-07-31 21:57:55 +000014723 ESI.NoexceptExpr = NoexceptExpr;
Douglas Gregor433e0532012-04-16 18:27:27 +000014724 }
14725 return;
14726 }
14727}
14728
Richard Smith0b3a4622014-11-13 20:01:57 +000014729void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
14730 ExceptionSpecificationType EST,
14731 SourceRange SpecificationRange,
14732 ArrayRef<ParsedType> DynamicExceptions,
14733 ArrayRef<SourceRange> DynamicExceptionRanges,
14734 Expr *NoexceptExpr) {
14735 if (!MethodD)
14736 return;
14737
14738 // Dig out the method we're referring to.
14739 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
14740 MethodD = FunTmpl->getTemplatedDecl();
14741
14742 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
14743 if (!Method)
14744 return;
14745
14746 // Check the exception specification.
14747 llvm::SmallVector<QualType, 4> Exceptions;
14748 FunctionProtoType::ExceptionSpecInfo ESI;
14749 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
14750 DynamicExceptionRanges, NoexceptExpr, Exceptions,
14751 ESI);
14752
14753 // Update the exception specification on the function type.
14754 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
14755
14756 if (Method->isStatic())
14757 checkThisInStaticMemberFunctionExceptionSpec(Method);
14758
14759 if (Method->isVirtual()) {
14760 // Check overrides, which we previously had to delay.
14761 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
14762 OEnd = Method->end_overridden_methods();
14763 O != OEnd; ++O)
14764 CheckOverridingFunctionExceptionSpec(Method, *O);
14765 }
14766}
14767
John McCall5e77d762013-04-16 07:28:30 +000014768/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
14769///
14770MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
14771 SourceLocation DeclStart,
14772 Declarator &D, Expr *BitWidth,
14773 InClassInitStyle InitStyle,
14774 AccessSpecifier AS,
14775 AttributeList *MSPropertyAttr) {
14776 IdentifierInfo *II = D.getIdentifier();
14777 if (!II) {
14778 Diag(DeclStart, diag::err_anonymous_property);
Craig Topperc3ec1492014-05-26 06:22:03 +000014779 return nullptr;
John McCall5e77d762013-04-16 07:28:30 +000014780 }
14781 SourceLocation Loc = D.getIdentifierLoc();
14782
14783 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14784 QualType T = TInfo->getType();
14785 if (getLangOpts().CPlusPlus) {
14786 CheckExtraCXXDefaultArguments(D);
14787
14788 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14789 UPPC_DataMemberType)) {
14790 D.setInvalidType();
14791 T = Context.IntTy;
14792 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14793 }
14794 }
14795
14796 DiagnoseFunctionSpecifiers(D.getDeclSpec());
14797
Richard Smith62f19e72016-06-25 00:15:56 +000014798 if (D.getDeclSpec().isInlineSpecified())
14799 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14800 << getLangOpts().CPlusPlus1z;
John McCall5e77d762013-04-16 07:28:30 +000014801 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14802 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14803 diag::err_invalid_thread)
14804 << DeclSpec::getSpecifierName(TSCS);
14805
14806 // Check to see if this name was declared as a member previously
Craig Topperc3ec1492014-05-26 06:22:03 +000014807 NamedDecl *PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000014808 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
14809 LookupName(Previous, S);
14810 switch (Previous.getResultKind()) {
14811 case LookupResult::Found:
14812 case LookupResult::FoundUnresolvedValue:
14813 PrevDecl = Previous.getAsSingle<NamedDecl>();
14814 break;
14815
14816 case LookupResult::FoundOverloaded:
14817 PrevDecl = Previous.getRepresentativeDecl();
14818 break;
14819
14820 case LookupResult::NotFound:
14821 case LookupResult::NotFoundInCurrentInstantiation:
14822 case LookupResult::Ambiguous:
14823 break;
14824 }
14825
14826 if (PrevDecl && PrevDecl->isTemplateParameter()) {
14827 // Maybe we will complain about the shadowed template parameter.
14828 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14829 // Just pretend that we didn't see the previous declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +000014830 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000014831 }
14832
14833 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Craig Topperc3ec1492014-05-26 06:22:03 +000014834 PrevDecl = nullptr;
John McCall5e77d762013-04-16 07:28:30 +000014835
14836 SourceLocation TSSL = D.getLocStart();
John McCall5e77d762013-04-16 07:28:30 +000014837 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Richard Smithf7981722013-11-22 09:01:48 +000014838 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
14839 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall5e77d762013-04-16 07:28:30 +000014840 ProcessDeclAttributes(TUScope, NewPD, D);
14841 NewPD->setAccess(AS);
14842
14843 if (NewPD->isInvalidDecl())
14844 Record->setInvalidDecl();
14845
14846 if (D.getDeclSpec().isModulePrivateSpecified())
14847 NewPD->setModulePrivate();
14848
14849 if (NewPD->isInvalidDecl() && PrevDecl) {
14850 // Don't introduce NewFD into scope; there's already something
14851 // with the same name in the same scope.
14852 } else if (II) {
14853 PushOnScopeChains(NewPD, S);
14854 } else
14855 Record->addDecl(NewPD);
14856
14857 return NewPD;
14858}